diff --git a/.editorconfig b/.editorconfig index 0c0dc310ea..e157f7116c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -36,6 +36,7 @@ roslynator_infinite_loop_style = while roslynator_doc_comment_summary_style = multi_line roslynator_enum_flag_value_style = shift_operator roslynator_blank_line_after_file_scoped_namespace_declaration = true +roslynator_null_check_style = pattern_matching csharp_style_namespace_declarations = file_scoped:suggestion @@ -134,6 +135,7 @@ dotnet_diagnostic.RCS1189.severity = suggestion dotnet_diagnostic.RCS1207.severity = suggestion dotnet_diagnostic.RCS1237.severity = none dotnet_diagnostic.RCS1244.severity = suggestion +dotnet_diagnostic.RCS1248.severity = suggestion dotnet_diagnostic.RCS1250.severity = suggestion dotnet_diagnostic.RCS1252.severity = suggestion dotnet_diagnostic.RCS1253.severity = suggestion diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AddOrRemoveParenthesesWhenCreatingNewObjectCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AddOrRemoveParenthesesWhenCreatingNewObjectCodeFixProvider.cs index 4277f59422..7790eca2fe 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AddOrRemoveParenthesesWhenCreatingNewObjectCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AddOrRemoveParenthesesWhenCreatingNewObjectCodeFixProvider.cs @@ -32,7 +32,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) Document document = context.Document; Diagnostic diagnostic = context.Diagnostics[0]; - if (objectCreationExpression.ArgumentList != null) + if (objectCreationExpression.ArgumentList is not null) { CodeAction codeAction = CodeAction.Create( "Remove parentheses", diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AvoidNullReferenceExceptionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AvoidNullReferenceExceptionCodeFixProvider.cs index f00e107db5..9dbb94c2fb 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AvoidNullReferenceExceptionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AvoidNullReferenceExceptionCodeFixProvider.cs @@ -66,7 +66,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) bool IsPartOfLeftSideOfAssignment() { - for (SyntaxNode node = expression; node != null; node = node.Parent) + for (SyntaxNode node = expression; node is not null; node = node.Parent) { var assignmentExpression = node.Parent as AssignmentExpressionSyntax; diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BinaryExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BinaryExpressionCodeFixProvider.cs index 64019a6f65..8d5292e360 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BinaryExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BinaryExpressionCodeFixProvider.cs @@ -78,7 +78,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { ExpressionSyntax expression = binaryExpression.Left; - if (expression == null + if (expression is null || !context.Span.Contains(expression.Span)) { expression = binaryExpression.Right; @@ -348,11 +348,11 @@ private static ConditionalAccessExpressionSyntax CreateConditionalAccess(Express } BinaryExpressionSyntax newBinaryExpression = BinaryExpression( - (binaryExpression != null) + (binaryExpression is not null) ? right.Kind() : SyntaxKind.EqualsExpression, nullCheck.Expression.WithLeadingTrivia(logicalAnd.GetLeadingTrivia()), - (binaryExpression != null) + (binaryExpression is not null) ? ((BinaryExpressionSyntax)right).OperatorToken : Token(SyntaxKind.EqualsEqualsToken).WithTriviaFrom(logicalAnd.OperatorToken), newRight) diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BlockCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BlockCodeFixProvider.cs index af70a1817e..c1b5176661 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BlockCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BlockCodeFixProvider.cs @@ -154,7 +154,7 @@ static SyntaxTriviaList AddTriviaIfNecessary(SyntaxTriviaList trivia, SyntaxTriv { ExpressionSyntax right = SimpleAssignmentExpression(expression, assignment.Right.WithoutTrivia()).Parenthesize(); - if (valueName != null) + if (valueName is not null) right = SimpleMemberAccessExpression(right.Parenthesize(), valueName); coalesceExpression = CoalesceExpression(expression, right); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs index 712def34aa..695b2cbc75 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs @@ -102,7 +102,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) semanticModel, context.CancellationToken); - if (recursiveCodeAction != null) + if (recursiveCodeAction is not null) context.RegisterCodeFix(recursiveCodeAction, diagnostic); break; diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumDeclarationCodeFixProvider.cs index 01417c49c6..70cb187715 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumDeclarationCodeFixProvider.cs @@ -66,7 +66,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ImmutableArray values = enumInfo .Fields - .Where(f => f.HasValue && ((EnumMemberDeclarationSyntax)f.Symbol.GetSyntax(context.CancellationToken)).EqualsValue != null) + .Where(f => f.HasValue && ((EnumMemberDeclarationSyntax)f.Symbol.GetSyntax(context.CancellationToken)).EqualsValue is not null) .Select(f => f.Value) .ToImmutableArray(); @@ -209,7 +209,7 @@ private static bool AreSeparatedWithEmptyLine(SeparatedSyntaxList GetExpressionsToRewrite() { ExpressionSyntax expression = member.EqualsValue?.Value.WalkDownParentheses(); - if (expression != null + if (expression is not null && semanticModel.GetDeclaredSymbol(member, cancellationToken) is IFieldSymbol fieldSymbol && fieldSymbol.HasConstantValue) { diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumMemberDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumMemberDeclarationCodeFixProvider.cs index b3a19af13d..93203ca5d6 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumMemberDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumMemberDeclarationCodeFixProvider.cs @@ -170,7 +170,7 @@ private static IdentifierNameSyntax CreateIdentifierName(in EnumFieldSymbolInfo EnumMemberDeclarationSyntax newEnumMember; - if (equalsValue != null) + if (equalsValue is not null) { IdentifierNameSyntax newValue = IdentifierName(Identifier(equalsValue.Value.GetLeadingTrivia(), valueText, equalsValue.Value.GetTrailingTrivia())); newEnumMember = enumMember.WithEqualsValue(equalsValue.WithValue(newValue)); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/IfStatementCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/IfStatementCodeFixProvider.cs index 76ce45cca2..70320b2b05 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/IfStatementCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/IfStatementCodeFixProvider.cs @@ -153,9 +153,9 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) SyntaxList newStatements; if (ifStatement.Statement.SingleNonBlockStatementOrDefault() is ThrowStatementSyntax throwStatement - && throwStatement.Expression == null) + && throwStatement.Expression is null) { - if (elseClause != null) + if (elseClause is not null) { newStatements = ReplaceStatement(elseClause.Statement); } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeStringBuilderAppendCallCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeStringBuilderAppendCallCodeFixProvider.cs index 0effd7a66e..cf7ec2293e 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeStringBuilderAppendCallCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeStringBuilderAppendCallCodeFixProvider.cs @@ -212,7 +212,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) arguments = ReplaceStringLiteralWithCharacterLiteral(arguments); } - if (newExpression == null) + if (newExpression is null) { arguments = arguments.Replace(arguments[0], arguments[0].WithLeadingTrivia(interpolatedString.GetLeadingTrivia())); @@ -336,11 +336,11 @@ private static ImmutableArray ReplaceStringLiteralWithCharacterL { ArgumentSyntax argument = arguments.SingleOrDefault(shouldThrow: false); - if (argument != null) + if (argument is not null) { ExpressionSyntax expression = argument.Expression; - if (expression != null) + if (expression is not null) { ExpressionSyntax newExpression = ReplaceStringLiteralWithCharacterLiteral(expression); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OrderElementsInDocumentationCommentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OrderElementsInDocumentationCommentCodeFixProvider.cs index 6d21f94c5b..75fb2ada16 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OrderElementsInDocumentationCommentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OrderElementsInDocumentationCommentCodeFixProvider.cs @@ -112,7 +112,7 @@ SyntaxList GetNewContent() ? ((XmlElementSyntax)element).GetAttributeValue("name") : ((XmlEmptyElementSyntax)element).GetAttributeValue("name"); - if (value != null) + if (value is not null) { ranks[element] = indexOf(nodes, value); } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemovePartialModifierFromTypeWithSinglePartCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemovePartialModifierFromTypeWithSinglePartCodeFixProvider.cs index 6f866d8168..4a7e4a87da 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemovePartialModifierFromTypeWithSinglePartCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemovePartialModifierFromTypeWithSinglePartCodeFixProvider.cs @@ -37,7 +37,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ct => { TypeDeclarationSyntax newTypeDeclaration = typeDeclaration.ReplaceNodes( - typeDeclaration.Members.OfType().Where(f => f.Modifiers.Contains(SyntaxKind.PartialKeyword) && f.BodyOrExpressionBody() != null), + typeDeclaration.Members.OfType().Where(f => f.Modifiers.Contains(SyntaxKind.PartialKeyword) && f.BodyOrExpressionBody() is not null), (f, _) => f.RemoveModifier(SyntaxKind.PartialKeyword)); int count = newTypeDeclaration.Members.Count; diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantAssignmentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantAssignmentCodeFixProvider.cs index 7534fa6012..014f282594 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantAssignmentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantAssignmentCodeFixProvider.cs @@ -94,7 +94,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ExpressionSyntax value = initializer?.Value; - VariableDeclaratorSyntax newDeclarator = (value != null) + VariableDeclaratorSyntax newDeclarator = (value is not null) ? declarator.ReplaceNode(value, right) : declarator.WithInitializer(EqualsValueClause(right)); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryAssignmentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryAssignmentCodeFixProvider.cs index def2fd6ec1..494e7ca86c 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryAssignmentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryAssignmentCodeFixProvider.cs @@ -195,11 +195,11 @@ static SwitchSectionSyntax CreateNewSection(SwitchSectionSyntax section) VariableDeclaratorSyntax declarator = declarators.FirstOrDefault(f => SymbolEqualityComparer.Default.Equals(semanticModel.GetDeclaredSymbol(f, cancellationToken), symbol)); - if (declarator != null) + if (declarator is not null) { ExpressionSyntax value = declarator.Initializer?.Value; - if (removeReturnStatement || value != null) + if (removeReturnStatement || value is not null) { IEnumerable referencedSymbols = await SymbolFinder.FindReferencesAsync(symbol, document.Solution(), cancellationToken).ConfigureAwait(false); @@ -246,7 +246,7 @@ static SwitchSectionSyntax CreateNewSection(SwitchSectionSyntax section) { statementsInfo = statementsInfo.RemoveNode(returnStatement, SyntaxRefactorings.GetRemoveOptions(returnStatement)); } - else if (newReturnExpression != null) + else if (newReturnExpression is not null) { ReturnStatementSyntax newReturnStatement = returnStatement.WithExpression(newReturnExpression.WithTriviaFrom(returnExpression)); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAutoPropertyCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAutoPropertyCodeFixProvider.cs index b2bfb24e35..620dae2e04 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAutoPropertyCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAutoPropertyCodeFixProvider.cs @@ -136,7 +136,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) SyntaxNode nodeToRemove = newRoot.GetAnnotatedNodes(_removeAnnotation).FirstOrDefault(); - if (nodeToRemove != null) + if (nodeToRemove is not null) newRoot = newRoot.RemoveNode(nodeToRemove, SyntaxRemoveOptions.KeepUnbalancedDirectives); return document.WithSyntaxRoot(newRoot); @@ -146,7 +146,7 @@ private static ISymbol GetFieldSymbol(PropertyDeclarationSyntax property, Semant { ArrowExpressionClauseSyntax expressionBody = property.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { return semanticModel.GetSymbol(expressionBody.Expression, cancellationToken); } @@ -156,7 +156,7 @@ private static ISymbol GetFieldSymbol(PropertyDeclarationSyntax property, Semant BlockSyntax body = getter.Body; - if (body != null) + if (body is not null) { var returnStatement = (ReturnStatementSyntax)body.Statements[0]; @@ -173,7 +173,7 @@ public static PropertyDeclarationSyntax CreateAutoProperty(PropertyDeclarationSy { AccessorListSyntax accessorList = property.AccessorList; - if (accessorList != null) + if (accessorList is not null) { SyntaxList newAccessors = accessorList .Accessors @@ -214,7 +214,7 @@ public static PropertyDeclarationSyntax CreateAutoProperty(PropertyDeclarationSy accessorList: accessorList, expressionBody: default(ArrowExpressionClauseSyntax), initializer: initializer, - semicolonToken: (initializer != null) ? SemicolonToken() : default); + semicolonToken: (initializer is not null) ? SemicolonToken() : default); return newProperty .WithTriviaFrom(property) diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/AddSummaryToDocumentationCommentRefactoring.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/AddSummaryToDocumentationCommentRefactoring.cs index d927447203..ae99c05521 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/AddSummaryToDocumentationCommentRefactoring.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/AddSummaryToDocumentationCommentRefactoring.cs @@ -57,7 +57,7 @@ private static string CreateSummaryElement(string indent, string text = null) sb.Append(indent); sb.AppendLine("/// "); - if (text == null) + if (text is null) sb.Append(indent); return sb.ToString(); diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/DeclareUsingDirectiveOnTopLevelRefactoring.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/DeclareUsingDirectiveOnTopLevelRefactoring.cs index f4c4dd433c..bdcb61afc8 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/DeclareUsingDirectiveOnTopLevelRefactoring.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/DeclareUsingDirectiveOnTopLevelRefactoring.cs @@ -58,9 +58,9 @@ NameSyntax EnsureFullyQualifiedName() { ISymbol symbol = semanticModel.GetSymbol(name, cancellationToken); - if (symbol != null) + if (symbol is not null) { - if (semanticModel.GetAliasInfo(name, cancellationToken) != null + if (semanticModel.GetAliasInfo(name, cancellationToken) is not null || !symbol.ContainingNamespace.IsGlobalNamespace) { SymbolKind kind = symbol.Kind; diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/Documentation/DocumentationCommentRefactoring`1.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/Documentation/DocumentationCommentRefactoring`1.cs index 3a2c5ea3e9..0221521176 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/Documentation/DocumentationCommentRefactoring`1.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/Documentation/DocumentationCommentRefactoring`1.cs @@ -137,7 +137,7 @@ internal abstract class DocumentationCommentRefactoring where TNode : Syn { XmlElementSyntax previousElement = GetPreviousElement(comment, element); - if (previousElement != null) + if (previousElement is not null) { insertIndex = previousElement.FullSpan.End; } diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/FormatAccessorListRefactoring.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/FormatAccessorListRefactoring.cs index c061104223..62c3015be1 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/FormatAccessorListRefactoring.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/FormatAccessorListRefactoring.cs @@ -19,7 +19,7 @@ internal static class FormatAccessorListRefactoring AccessorListSyntax accessorList, CancellationToken cancellationToken) { - if (accessorList.Accessors.All(f => f.BodyOrExpressionBody() == null)) + if (accessorList.Accessors.All(f => f.BodyOrExpressionBody() is null)) { SyntaxNode parent = accessorList.Parent; @@ -120,7 +120,7 @@ private static bool ShouldBeFormatted(AccessorDeclarationSyntax accessor) { BlockSyntax body = accessor.Body; - if (body != null) + if (body is not null) { SyntaxList statements = body.Statements; @@ -137,7 +137,7 @@ private static bool ShouldBeFormatted(AccessorDeclarationSyntax accessor) { ArrowExpressionClauseSyntax expressionBody = accessor.ExpressionBody; - if (expressionBody != null + if (expressionBody is not null && accessor.SyntaxTree.IsMultiLineSpan(TextSpan.FromBounds(accessor.Keyword.SpanStart, accessor.Span.End)) && expressionBody.Expression?.IsSingleLine() == true) { diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/RemoveEmptyInitializerRefactoring.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/RemoveEmptyInitializerRefactoring.cs index 54c86d6770..df5f3078e2 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/RemoveEmptyInitializerRefactoring.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/RemoveEmptyInitializerRefactoring.cs @@ -22,7 +22,7 @@ internal static class RemoveEmptyInitializerRefactoring InitializerExpressionSyntax initializer = objectCreationExpression.Initializer; ObjectCreationExpressionSyntax newNode = objectCreationExpression.WithInitializer(null); - if (argumentList == null) + if (argumentList is null) { TypeSyntax type = objectCreationExpression.Type; diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/SimplifyNullCheckRefactoring.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/SimplifyNullCheckRefactoring.cs index d1671e7f9f..b95ec328af 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/SimplifyNullCheckRefactoring.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/SimplifyNullCheckRefactoring.cs @@ -31,7 +31,7 @@ internal static class SimplifyNullCheckRefactoring var castExpression = whenNotNull as CastExpressionSyntax; - ExpressionSyntax expression = (castExpression != null) + ExpressionSyntax expression = (castExpression is not null) ? UseConditionalAccessAnalyzer.FindExpressionThatCanBeConditionallyAccessed(nullCheck.Expression, castExpression.Expression, semanticModel, cancellationToken) : UseConditionalAccessAnalyzer.FindExpressionThatCanBeConditionallyAccessed(nullCheck.Expression, whenNotNull, semanticModel, cancellationToken); @@ -66,7 +66,7 @@ internal static class SimplifyNullCheckRefactoring { newNode = ParseExpression($"{expression}?{whenNotNull.ToString().Substring(memberAccessExpression.Span.End - whenNotNull.SpanStart)}"); - if (castExpression != null) + if (castExpression is not null) { newNode = castExpression .WithExpression(newNode.Parenthesize()) @@ -77,7 +77,7 @@ internal static class SimplifyNullCheckRefactoring } } - if (newNode == null) + if (newNode is null) newNode = ParseExpression(whenNotNull.ToString().Insert(expression.Span.End - whenNotNull.SpanStart, "?")); if (coalesce diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/UseRegexInstanceInsteadOfStaticMethodRefactoring.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/UseRegexInstanceInsteadOfStaticMethodRefactoring.cs index eb4f578db9..997daaeb27 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/UseRegexInstanceInsteadOfStaticMethodRefactoring.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/UseRegexInstanceInsteadOfStaticMethodRefactoring.cs @@ -23,15 +23,15 @@ internal static class UseRegexInstanceInsteadOfStaticMethodRefactoring MemberDeclarationSyntax memberDeclaration = invocationExpression.FirstAncestor(); - Debug.Assert(memberDeclaration != null, ""); + Debug.Assert(memberDeclaration is not null, ""); - if (memberDeclaration != null) + if (memberDeclaration is not null) { TypeDeclarationSyntax typeDeclaration = memberDeclaration.FirstAncestor(); - Debug.Assert(typeDeclaration != null, ""); + Debug.Assert(typeDeclaration is not null, ""); - if (typeDeclaration != null) + if (typeDeclaration is not null) { SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression); @@ -84,11 +84,11 @@ internal static class UseRegexInstanceInsteadOfStaticMethodRefactoring { IParameterSymbol parameterSymbol = semanticModel.DetermineParameter(arguments[i], cancellationToken: cancellationToken); - Debug.Assert(parameterSymbol != null, ""); + Debug.Assert(parameterSymbol is not null, ""); - if (parameterSymbol != null) + if (parameterSymbol is not null) { - if (pattern == null + if (pattern is null && parameterSymbol.Type.IsString() && parameterSymbol.Name == "pattern") { @@ -96,14 +96,14 @@ internal static class UseRegexInstanceInsteadOfStaticMethodRefactoring newArguments = newArguments.RemoveAt(i); } - if (regexOptions == null + if (regexOptions is null && parameterSymbol.Type.HasMetadataName(MetadataNames.System_Text_RegularExpressions_RegexOptions)) { regexOptions = arguments[i]; newArguments = newArguments.RemoveAt(i); } - if (matchTimeout == null + if (matchTimeout is null && parameterSymbol.Type.HasMetadataName(MetadataNames.System_TimeSpan)) { matchTimeout = arguments[i]; @@ -116,13 +116,13 @@ internal static class UseRegexInstanceInsteadOfStaticMethodRefactoring var arguments2 = new List(); - if (pattern != null) + if (pattern is not null) arguments2.Add(pattern); - if (regexOptions != null) + if (regexOptions is not null) arguments2.Add(regexOptions); - if (matchTimeout != null) + if (matchTimeout is not null) arguments2.Add(matchTimeout); return new ArgumentListPair(argumentList, ArgumentList(arguments2.ToArray())); diff --git a/src/Analyzers/CSharp/Analysis/AbstractTypeShouldNotHavePublicConstructorsAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AbstractTypeShouldNotHavePublicConstructorsAnalyzer.cs index a24740b07d..575baafcf7 100644 --- a/src/Analyzers/CSharp/Analysis/AbstractTypeShouldNotHavePublicConstructorsAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AbstractTypeShouldNotHavePublicConstructorsAnalyzer.cs @@ -52,7 +52,7 @@ private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext cont { INamedTypeSymbol classSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclaration, context.CancellationToken); - if (classSymbol != null) + if (classSymbol is not null) isAbstract = classSymbol.IsAbstract; } diff --git a/src/Analyzers/CSharp/Analysis/AddBracesAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddBracesAnalyzer.cs index 00af1798ec..498ca0a897 100644 --- a/src/Analyzers/CSharp/Analysis/AddBracesAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddBracesAnalyzer.cs @@ -47,7 +47,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = ifStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -62,7 +62,7 @@ private static void AnalyzeElseClause(SyntaxNodeAnalysisContext context) StatementSyntax statement = elseClause.EmbeddedStatement(allowIfStatement: false); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -77,7 +77,7 @@ private static void AnalyzeCommonForEachStatement(SyntaxNodeAnalysisContext cont StatementSyntax statement = forEachStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -92,7 +92,7 @@ private static void AnalyzeForStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = forStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -107,7 +107,7 @@ private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = usingStatement.EmbeddedStatement(allowUsingStatement: false); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -122,7 +122,7 @@ private static void AnalyzeWhileStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = whileStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -137,7 +137,7 @@ private static void AnalyzeDoStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = doStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -152,7 +152,7 @@ private static void AnalyzeLockStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = lockStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -167,7 +167,7 @@ private static void AnalyzeFixedStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = fixedStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) diff --git a/src/Analyzers/CSharp/Analysis/AddBracesToIfElseAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddBracesToIfElseAnalyzer.cs index a4eee78e4a..64b45ef86c 100644 --- a/src/Analyzers/CSharp/Analysis/AddBracesToIfElseAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddBracesToIfElseAnalyzer.cs @@ -42,7 +42,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = ifStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -57,7 +57,7 @@ private static void AnalyzeElseClause(SyntaxNodeAnalysisContext context) StatementSyntax statement = elseClause.EmbeddedStatement(allowIfStatement: false); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) diff --git a/src/Analyzers/CSharp/Analysis/AddBracesToIfElseWhenMultiLineAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddBracesToIfElseWhenMultiLineAnalyzer.cs index 9bedc9cdd0..e64ce92852 100644 --- a/src/Analyzers/CSharp/Analysis/AddBracesToIfElseWhenMultiLineAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddBracesToIfElseWhenMultiLineAnalyzer.cs @@ -39,7 +39,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) if (ifStatement.IsParentKind(SyntaxKind.ElseClause)) return; - if (ifStatement.Else == null) + if (ifStatement.Else is null) return; if (ifStatement.Else.ContainsDirectives) diff --git a/src/Analyzers/CSharp/Analysis/AddBracesWhenMultilineAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddBracesWhenMultilineAnalyzer.cs index 47df403634..f3bf86748f 100644 --- a/src/Analyzers/CSharp/Analysis/AddBracesWhenMultilineAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddBracesWhenMultilineAnalyzer.cs @@ -50,7 +50,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = ifStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -68,7 +68,7 @@ private static void AnalyzeCommonForEachStatement(SyntaxNodeAnalysisContext cont StatementSyntax statement = forEachStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -86,7 +86,7 @@ private static void AnalyzeForStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = forStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -104,7 +104,7 @@ private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = usingStatement.EmbeddedStatement(allowUsingStatement: false); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -122,7 +122,7 @@ private static void AnalyzeWhileStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = whileStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -140,7 +140,7 @@ private static void AnalyzeDoStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = doStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -158,7 +158,7 @@ private static void AnalyzeLockStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = lockStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) @@ -176,7 +176,7 @@ private static void AnalyzeFixedStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = fixedStatement.EmbeddedStatement(); - if (statement == null) + if (statement is null) return; if (statement.ContainsDirectives) diff --git a/src/Analyzers/CSharp/Analysis/AddExceptionToDocumentationCommentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddExceptionToDocumentationCommentAnalyzer.cs index 736cf2272e..dfcd959e8e 100644 --- a/src/Analyzers/CSharp/Analysis/AddExceptionToDocumentationCommentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddExceptionToDocumentationCommentAnalyzer.cs @@ -35,7 +35,7 @@ public override void Initialize(AnalysisContext context) { INamedTypeSymbol exceptionSymbol = startContext.Compilation.GetTypeByMetadataName("System.Exception"); - if (exceptionSymbol == null) + if (exceptionSymbol is null) return; startContext.RegisterSyntaxNodeAction(f => AnalyzeThrowStatement(f, exceptionSymbol), SyntaxKind.ThrowStatement); diff --git a/src/Analyzers/CSharp/Analysis/AddOrRemoveAccessibilityModifiersAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddOrRemoveAccessibilityModifiersAnalyzer.cs index 3d9179a335..6c6702d66e 100644 --- a/src/Analyzers/CSharp/Analysis/AddOrRemoveAccessibilityModifiersAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddOrRemoveAccessibilityModifiersAnalyzer.cs @@ -24,7 +24,7 @@ public sealed class AddOrRemoveAccessibilityModifiersAnalyzer : BaseDiagnosticAn { get { - if (_properties == null) + if (_properties is null) Interlocked.CompareExchange(ref _properties, CreateProperties(), null); return _properties; @@ -203,7 +203,7 @@ private static void Analyze(SyntaxNodeAnalysisContext context, MemberDeclaration Location location = GetLocation(declaration); - if (location == null) + if (location is null) return; DiagnosticHelpers.ReportDiagnostic( @@ -240,7 +240,7 @@ private static Accessibility GetAccessibility(SyntaxNodeAnalysisContext context, { Accessibility? accessibility = GetPartialAccessibility(context, declaration); - if (accessibility != null) + if (accessibility is not null) { if (accessibility == Accessibility.NotApplicable) { @@ -269,7 +269,7 @@ private static Accessibility GetAccessibility(SyntaxNodeAnalysisContext context, ISymbol symbol = context.SemanticModel.GetDeclaredSymbol(declaration, context.CancellationToken); - if (symbol != null) + if (symbol is not null) { foreach (SyntaxReference syntaxReference in symbol.DeclaringSyntaxReferences) { diff --git a/src/Analyzers/CSharp/Analysis/AddOrRemoveParenthesesFromConditionInConditionalExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddOrRemoveParenthesesFromConditionInConditionalExpressionAnalyzer.cs index 0a369fa574..47e121ace7 100644 --- a/src/Analyzers/CSharp/Analysis/AddOrRemoveParenthesesFromConditionInConditionalExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddOrRemoveParenthesesFromConditionInConditionalExpressionAnalyzer.cs @@ -43,7 +43,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte ExpressionSyntax condition = conditionalExpression.Condition; - if (condition == null) + if (condition is null) return; ConditionalExpressionParenthesesStyle style = context.GetConditionalExpressionParenthesesStyle(); diff --git a/src/Analyzers/CSharp/Analysis/AddOrRemoveParenthesesWhenCreatingNewObjectAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddOrRemoveParenthesesWhenCreatingNewObjectAnalyzer.cs index 85eb5b0640..a5d52436be 100644 --- a/src/Analyzers/CSharp/Analysis/AddOrRemoveParenthesesWhenCreatingNewObjectAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddOrRemoveParenthesesWhenCreatingNewObjectAnalyzer.cs @@ -52,7 +52,7 @@ private static void AnalyzeObjectCreationExpression(SyntaxNodeAnalysisContext co ArgumentListSyntax argumentList = objectCreationExpression.ArgumentList; - if (argumentList == null) + if (argumentList is null) { if (style == ObjectCreationParenthesesStyle.Include) { diff --git a/src/Analyzers/CSharp/Analysis/AddOrRemoveRegionNameAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddOrRemoveRegionNameAnalyzer.cs index c8307d06c7..ed5fbc5f7c 100644 --- a/src/Analyzers/CSharp/Analysis/AddOrRemoveRegionNameAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddOrRemoveRegionNameAnalyzer.cs @@ -38,7 +38,7 @@ private static void AnalyzeEndRegionDirectiveTrivia(SyntaxNodeAnalysisContext co RegionDirectiveTriviaSyntax regionDirective = endRegionDirective.GetRegionDirective(); - if (regionDirective == null) + if (regionDirective is null) return; SyntaxTrivia trivia = regionDirective.GetPreprocessingMessageTrivia(); diff --git a/src/Analyzers/CSharp/Analysis/AddParagraphToDocumentationCommentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddParagraphToDocumentationCommentAnalyzer.cs index e593e835ab..acbea246f2 100644 --- a/src/Analyzers/CSharp/Analysis/AddParagraphToDocumentationCommentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddParagraphToDocumentationCommentAnalyzer.cs @@ -121,7 +121,7 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys name = xmlEmptyElement.Name?.LocalName.ValueText; } - if (name != null) + if (name is not null) { if (string.Equals(name, "code", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "inheritdoc", StringComparison.OrdinalIgnoreCase) @@ -264,7 +264,7 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys if (!stopOnFirstMatch) { - if (spans == null) + if (spans is null) spans = new List() { TextSpan.FromBounds(index, endIndex) }; spans.Add(TextSpan.FromBounds(index2, endIndex2)); @@ -309,7 +309,7 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys if (stopOnFirstMatch) return (TextSpan.FromBounds(index, endIndex), TextSpan.FromBounds(index2, endIndex2), default); - if (spans == null) + if (spans is null) spans = new List() { TextSpan.FromBounds(index, endIndex) }; spans.Add(TextSpan.FromBounds(index2, endIndex2)); diff --git a/src/Analyzers/CSharp/Analysis/AddParenthesesWhenNecessaryAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddParenthesesWhenNecessaryAnalyzer.cs index 75ab79464a..7332240ce6 100644 --- a/src/Analyzers/CSharp/Analysis/AddParenthesesWhenNecessaryAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddParenthesesWhenNecessaryAnalyzer.cs @@ -86,7 +86,7 @@ private static void Analyze(SyntaxNodeAnalysisContext context, ExpressionSyntax private static bool IsNestedDiagnostic(SyntaxNode node) { - for (SyntaxNode current = node.Parent; current != null; current = current.Parent) + for (SyntaxNode current = node.Parent; current is not null; current = current.Parent) { if (IsFixable(current)) return true; @@ -99,7 +99,7 @@ internal static bool IsFixable(SyntaxNode node) { SyntaxNode parent = node.Parent; - return parent != null + return parent is not null && IsFixable(node, parent.Kind()); } diff --git a/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalysis.cs b/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalysis.cs index 46992013b7..79986603ea 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalysis.cs @@ -15,7 +15,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv { IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(invocationInfo.InvocationExpression, context.CancellationToken); - if (methodSymbol == null) + if (methodSymbol is null) return; if (methodSymbol.IsExtensionMethod) @@ -34,7 +34,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv { ArgumentSyntax argument = invocationInfo.Arguments.SingleOrDefault(shouldThrow: false); - if (argument != null) + if (argument is not null) { ExpressionSyntax expression = argument.Expression; diff --git a/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalyzer.cs index 81c0638b86..d6d362b67b 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalyzer.cs @@ -38,15 +38,15 @@ private static void AnalyzeInterpolation(SyntaxNodeAnalysisContext context) if (interpolation.ContainsDiagnostics) return; - if (interpolation.AlignmentClause != null) + if (interpolation.AlignmentClause is not null) return; - if (interpolation.FormatClause != null) + if (interpolation.FormatClause is not null) return; ExpressionSyntax expression = interpolation.Expression?.WalkDownParentheses(); - if (expression == null) + if (expression is null) return; ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken); diff --git a/src/Analyzers/CSharp/Analysis/AvoidEmptyCatchClauseThatCatchesSystemExceptionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidEmptyCatchClauseThatCatchesSystemExceptionAnalyzer.cs index 025a78f171..c9768c878d 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidEmptyCatchClauseThatCatchesSystemExceptionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidEmptyCatchClauseThatCatchesSystemExceptionAnalyzer.cs @@ -33,7 +33,7 @@ public override void Initialize(AnalysisContext context) { INamedTypeSymbol exceptionSymbol = startContext.Compilation.GetTypeByMetadataName("System.Exception"); - if (exceptionSymbol == null) + if (exceptionSymbol is null) return; startContext.RegisterSyntaxNodeAction(nodeContext => AnalyzeCatchClause(nodeContext, exceptionSymbol), SyntaxKind.CatchClause); @@ -47,7 +47,7 @@ private static void AnalyzeCatchClause(SyntaxNodeAnalysisContext context, ITypeS if (catchClause.ContainsDiagnostics) return; - if (catchClause.Filter != null) + if (catchClause.Filter is not null) return; if (catchClause.Block?.Statements.Any() != false) @@ -55,7 +55,7 @@ private static void AnalyzeCatchClause(SyntaxNodeAnalysisContext context, ITypeS TypeSyntax type = catchClause.Declaration?.Type; - if (type == null) + if (type is null) return; ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(type, context.CancellationToken); diff --git a/src/Analyzers/CSharp/Analysis/AvoidLockingOnPubliclyAccessibleInstanceAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidLockingOnPubliclyAccessibleInstanceAnalyzer.cs index 9be668d41b..9eb1ec0228 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidLockingOnPubliclyAccessibleInstanceAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidLockingOnPubliclyAccessibleInstanceAnalyzer.cs @@ -43,7 +43,7 @@ private static void AnalyzeLockStatement(SyntaxNodeAnalysisContext context) ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; if (!typeSymbol.DeclaredAccessibility.Is( diff --git a/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs index b8e4b662b7..b77857feed 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs @@ -43,14 +43,14 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv ExpressionSyntax accessExpression = GetAccessExpression(expression); - if (accessExpression == null) + if (accessExpression is null) return; if (accessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { IMethodSymbol methodSymbol2 = context.SemanticModel.GetMethodSymbol(accessExpression, context.CancellationToken); - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; if (methodSymbol2.IsExtensionMethod @@ -69,7 +69,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv INamedTypeSymbol containingType = methodSymbol.ContainingType; - if (containingType == null) + if (containingType is null) return; string methodName = methodSymbol.Name.Remove(methodSymbol.Name.Length - "OrDefault".Length); @@ -129,10 +129,10 @@ static bool ParameterSymbolEquals(IParameterSymbol x, IParameterSymbol y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x.RefKind != y.RefKind) @@ -195,7 +195,7 @@ private static void AnalyzeAsExpression(SyntaxNodeAnalysisContext context) SyntaxKind.InvocationExpression, SyntaxKind.ParenthesizedExpression)); - if (topExpression == null) + if (topExpression is null) return; if (semanticModel @@ -207,7 +207,7 @@ private static void AnalyzeAsExpression(SyntaxNodeAnalysisContext context) ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(topExpression, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; if (!typeSymbol.IsReferenceType && !typeSymbol.IsValueType) diff --git a/src/Analyzers/CSharp/Analysis/AvoidSemicolonAtEndOfDeclarationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidSemicolonAtEndOfDeclarationAnalyzer.cs index 9dc9c9de80..8eaec7d586 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidSemicolonAtEndOfDeclarationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidSemicolonAtEndOfDeclarationAnalyzer.cs @@ -43,7 +43,7 @@ private static void AnalyzeNamespaceDeclaration(SyntaxNodeAnalysisContext contex SyntaxToken semicolon = declaration.SemicolonToken; - if (semicolon.Parent != null + if (semicolon.Parent is not null && !semicolon.IsMissing) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidSemicolonAtEndOfDeclaration, semicolon); @@ -56,7 +56,7 @@ private static void AnalyzeClassDeclaration(SyntaxNodeAnalysisContext context) SyntaxToken semicolon = declaration.SemicolonToken; - if (semicolon.Parent != null + if (semicolon.Parent is not null && !semicolon.IsMissing) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidSemicolonAtEndOfDeclaration, semicolon); @@ -69,7 +69,7 @@ private static void AnalyzeInterfaceDeclaration(SyntaxNodeAnalysisContext contex SyntaxToken semicolon = declaration.SemicolonToken; - if (semicolon.Parent != null + if (semicolon.Parent is not null && !semicolon.IsMissing) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidSemicolonAtEndOfDeclaration, semicolon); @@ -82,7 +82,7 @@ private static void AnalyzeStructDeclaration(SyntaxNodeAnalysisContext context) SyntaxToken semicolon = declaration.SemicolonToken; - if (semicolon.Parent != null + if (semicolon.Parent is not null && !semicolon.IsMissing) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidSemicolonAtEndOfDeclaration, semicolon); @@ -97,7 +97,7 @@ private static void AnalyzeRecordDeclaration(SyntaxNodeAnalysisContext context) { SyntaxToken semicolon = declaration.SemicolonToken; - if (semicolon.Parent != null + if (semicolon.Parent is not null && !semicolon.IsMissing) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidSemicolonAtEndOfDeclaration, semicolon); @@ -111,7 +111,7 @@ private static void AnalyzeEnumDeclaration(SyntaxNodeAnalysisContext context) SyntaxToken semicolon = declaration.SemicolonToken; - if (semicolon.Parent != null + if (semicolon.Parent is not null && !semicolon.IsMissing) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidSemicolonAtEndOfDeclaration, semicolon); diff --git a/src/Analyzers/CSharp/Analysis/AvoidUsageOfForStatementToCreateInfiniteLoopAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidUsageOfForStatementToCreateInfiniteLoopAnalyzer.cs index 4dc4cb802e..56bbd92a61 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidUsageOfForStatementToCreateInfiniteLoopAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidUsageOfForStatementToCreateInfiniteLoopAnalyzer.cs @@ -36,8 +36,8 @@ private static void AnalyzeForStatement(SyntaxNodeAnalysisContext context) { var forStatement = (ForStatementSyntax)context.Node; - if (forStatement.Declaration == null - && forStatement.Condition == null + if (forStatement.Declaration is null + && forStatement.Condition is null && !forStatement.Incrementors.Any() && !forStatement.Initializers.Any() && !forStatement.OpenParenToken.ContainsDirectives diff --git a/src/Analyzers/CSharp/Analysis/AvoidUsageOfUsingAliasDirectiveAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidUsageOfUsingAliasDirectiveAnalyzer.cs index aef9495baf..3ff91074f4 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidUsageOfUsingAliasDirectiveAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidUsageOfUsingAliasDirectiveAnalyzer.cs @@ -36,7 +36,7 @@ private static void AnalyzeUsingDirective(SyntaxNodeAnalysisContext context) { var usingDirective = (UsingDirectiveSyntax)context.Node; - if (usingDirective.Alias == null) + if (usingDirective.Alias is null) return; if (usingDirective.ContainsDiagnostics) diff --git a/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs index b9907083e3..b92c5b6dd0 100644 --- a/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs @@ -228,7 +228,7 @@ bool IsReversedForStatement() VariableDeclarationSyntax declaration = forStatement.Declaration; - if (declaration == null) + if (declaration is null) return false; string name = identifierName.Identifier.ValueText; @@ -325,7 +325,7 @@ private static void AnalyzeLogicalOrExpression(SyntaxNodeAnalysisContext context ExpressionSyntax expression = nullCheck.Expression; - if (expression == null) + if (expression is null) return; ExpressionSyntax right = binaryExpression.Right.WalkDownParentheses(); diff --git a/src/Analyzers/CSharp/Analysis/BitwiseOperatorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/BitwiseOperatorAnalyzer.cs index 746d0a6fc2..63f3e30275 100644 --- a/src/Analyzers/CSharp/Analysis/BitwiseOperatorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/BitwiseOperatorAnalyzer.cs @@ -34,7 +34,7 @@ public override void Initialize(AnalysisContext context) { INamedTypeSymbol flagsAttribute = startContext.Compilation.GetTypeByMetadataName("System.FlagsAttribute"); - if (flagsAttribute == null) + if (flagsAttribute is null) return; startContext.RegisterSyntaxNodeAction(nodeContext => AnalyzeBinaryExpression(nodeContext, flagsAttribute), SyntaxKind.BitwiseAndExpression); diff --git a/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs b/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs index 1904363cd1..d17f02aca0 100644 --- a/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs @@ -295,11 +295,11 @@ private static void AnalyzeLogicalOrExpression(SyntaxNodeAnalysisContext context ExpressionSyntax operand = logicalNot.Operand; - if (operand != null) + if (operand is not null) { ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(operand, cancellationToken).ConvertedType; - if (typeSymbol != null) + if (typeSymbol is not null) { if (typeSymbol.SpecialType == SpecialType.System_Boolean) { diff --git a/src/Analyzers/CSharp/Analysis/CallCastInsteadOfSelectAnalysis.cs b/src/Analyzers/CSharp/Analysis/CallCastInsteadOfSelectAnalysis.cs index 71d61d4ce9..8779b30ffc 100644 --- a/src/Analyzers/CSharp/Analysis/CallCastInsteadOfSelectAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/CallCastInsteadOfSelectAnalysis.cs @@ -30,7 +30,7 @@ internal static class CallCastInsteadOfSelectAnalysis ExtensionMethodSymbolInfo extensionInfo = semanticModel.GetExtensionMethodInfo(invocationExpression, cancellationToken); - if (extensionInfo.Symbol == null) + if (extensionInfo.Symbol is null) return; if (!SymbolUtility.IsLinqSelect(extensionInfo.Symbol, allowImmutableArrayExtension: true)) @@ -53,7 +53,7 @@ internal static class CallCastInsteadOfSelectAnalysis CastExpressionSyntax castExpression = GetCastExpression(lambdaInfo.Body); - if (castExpression == null) + if (castExpression is null) return; if (castExpression.Expression is not IdentifierNameSyntax identifierName) diff --git a/src/Analyzers/CSharp/Analysis/CombineEnumerableWhereMethodChainAnalysis.cs b/src/Analyzers/CSharp/Analysis/CombineEnumerableWhereMethodChainAnalysis.cs index 4393f6e4aa..923235a0cb 100644 --- a/src/Analyzers/CSharp/Analysis/CombineEnumerableWhereMethodChainAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/CombineEnumerableWhereMethodChainAnalysis.cs @@ -33,7 +33,7 @@ internal static class CombineEnumerableWhereMethodChainAnalysis IMethodSymbol methodSymbol2 = semanticModel.GetReducedExtensionMethodInfo(invocationInfo2.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfT(methodSymbol2, "Where", parameterCount: 2)) @@ -45,7 +45,7 @@ internal static class CombineEnumerableWhereMethodChainAnalysis { IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationInfo.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol != null + if (methodSymbol is not null && SymbolUtility.IsLinqWhere(methodSymbol)) { Analyze(context, invocationInfo, invocationInfo2); @@ -58,7 +58,7 @@ internal static class CombineEnumerableWhereMethodChainAnalysis { IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationInfo.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol != null + if (methodSymbol is not null && SymbolUtility.IsLinqWhereWithIndex(methodSymbol)) { Analyze(context, invocationInfo, invocationInfo2); @@ -98,10 +98,10 @@ internal static class CombineEnumerableWhereMethodChainAnalysis private static bool AreEquivalentLambdas(ExpressionSyntax expression1, ExpressionSyntax expression2) { - if (expression1 == null) + if (expression1 is null) return false; - if (expression2 == null) + if (expression2 is null) return false; SyntaxKind kind = expression1.Kind(); @@ -126,8 +126,8 @@ private static bool AreEquivalentLambdas(ExpressionSyntax expression1, Expressio ParameterListSyntax parameterList1 = lambda1.ParameterList; ParameterListSyntax parameterList2 = lambda2.ParameterList; - if (parameterList1 != null - && parameterList2 != null) + if (parameterList1 is not null + && parameterList2 is not null) { SeparatedSyntaxList parameters1 = parameterList1.Parameters; SeparatedSyntaxList parameters2 = parameterList2.Parameters; diff --git a/src/Analyzers/CSharp/Analysis/ConfigureAwaitAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ConfigureAwaitAnalyzer.cs index 53b6f3a62f..5725ec32f3 100644 --- a/src/Analyzers/CSharp/Analysis/ConfigureAwaitAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ConfigureAwaitAnalyzer.cs @@ -43,7 +43,7 @@ public override void Initialize(AnalysisContext context) RemoveCallToConfigureAwait(c); } else if (style == ConfigureAwaitStyle.Include - && c.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1") != null) + && c.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1") is not null) { AddCallToConfigureAwait(c); } @@ -62,7 +62,7 @@ private static void AddCallToConfigureAwait(SyntaxNodeAnalysisContext context) ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; if (!SymbolUtility.IsAwaitable(typeSymbol)) @@ -84,7 +84,7 @@ private static void RemoveCallToConfigureAwait(SyntaxNodeAnalysisContext context ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; switch (typeSymbol.MetadataName) diff --git a/src/Analyzers/CSharp/Analysis/ConvertCommentToDocumentationCommentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ConvertCommentToDocumentationCommentAnalyzer.cs index f692058f5a..385dda04a8 100644 --- a/src/Analyzers/CSharp/Analysis/ConvertCommentToDocumentationCommentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ConvertCommentToDocumentationCommentAnalyzer.cs @@ -150,7 +150,7 @@ private static void AnalyzeEnumMembers(SyntaxNodeAnalysisContext context, Separa TrailingAnalysis? analysis = AnalyzeTrailing(enumMember); - if (analysis == null + if (analysis is null && (separatorCount == count || i < count - 1)) { analysis = AnalyzeTrailing(members.GetSeparator(i)); @@ -339,7 +339,7 @@ private static bool AnalyzeLeading(SyntaxNodeAnalysisContext context, SyntaxNode private static TrailingAnalysis? AnalyzeTrailing(SyntaxNodeOrToken? nodeOrToken) { - return (nodeOrToken != null) ? AnalyzeTrailing(nodeOrToken.Value) : default; + return (nodeOrToken is not null) ? AnalyzeTrailing(nodeOrToken.Value) : default; } private static TrailingAnalysis? AnalyzeTrailing(SyntaxNodeOrToken nodeOrToken) @@ -361,7 +361,7 @@ private static bool AnalyzeLeading(SyntaxNodeAnalysisContext context, SyntaxNode { TrailingAnalysis? analysis = AnalyzeTrailing(node); - if (analysis != null) + if (analysis is not null) return analysis; } diff --git a/src/Analyzers/CSharp/Analysis/ConvertInterpolatedStringToConcatenationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ConvertInterpolatedStringToConcatenationAnalyzer.cs index f16eb2dd04..b191c29d21 100644 --- a/src/Analyzers/CSharp/Analysis/ConvertInterpolatedStringToConcatenationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ConvertInterpolatedStringToConcatenationAnalyzer.cs @@ -67,13 +67,13 @@ private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContex ExpressionSyntax expression = interpolation.Expression; - if (expression == null) + if (expression is null) return; - if (interpolation.AlignmentClause != null) + if (interpolation.AlignmentClause is not null) return; - if (interpolation.FormatClause != null) + if (interpolation.FormatClause is not null) return; ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken); diff --git a/src/Analyzers/CSharp/Analysis/DeclareEachTypeInSeparateFileAnalyzer.cs b/src/Analyzers/CSharp/Analysis/DeclareEachTypeInSeparateFileAnalyzer.cs index d10b7ebe68..81e17e97d0 100644 --- a/src/Analyzers/CSharp/Analysis/DeclareEachTypeInSeparateFileAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/DeclareEachTypeInSeparateFileAnalyzer.cs @@ -63,7 +63,7 @@ void Analyze(SyntaxList members) } else if (SyntaxFacts.IsTypeDeclaration(kind)) { - if (firstTypeDeclaration == null) + if (firstTypeDeclaration is null) { firstTypeDeclaration = member; } @@ -103,7 +103,7 @@ private static bool ContainsSingleNamespaceWithSingleNonNamespaceMember(SyntaxLi member = namespaceDeclaration.Members.SingleOrDefault(shouldThrow: false); - return member != null + return member is not null && member.Kind() != SyntaxKind.NamespaceDeclaration; } } diff --git a/src/Analyzers/CSharp/Analysis/DeclareTypeInsideNamespaceAnalyzer.cs b/src/Analyzers/CSharp/Analysis/DeclareTypeInsideNamespaceAnalyzer.cs index c5f6f92929..ddd01c399c 100644 --- a/src/Analyzers/CSharp/Analysis/DeclareTypeInsideNamespaceAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/DeclareTypeInsideNamespaceAnalyzer.cs @@ -36,7 +36,7 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) if (symbol.ContainingNamespace?.IsGlobalNamespace != true) return; - if (symbol.ContainingType != null) + if (symbol.ContainingType is not null) return; SyntaxNode node = symbol @@ -44,7 +44,7 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) .SingleOrDefault(shouldThrow: false)? .GetSyntax(context.CancellationToken); - if (node == null) + if (node is null) return; SyntaxToken identifier = CSharpUtility.GetIdentifier(node); diff --git a/src/Analyzers/CSharp/Analysis/DefaultExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/DefaultExpressionAnalyzer.cs index 61f470a477..ada2189814 100644 --- a/src/Analyzers/CSharp/Analysis/DefaultExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/DefaultExpressionAnalyzer.cs @@ -170,7 +170,7 @@ void ReportDiagnostic() SyntaxNodeAnalysisContext context, SyntaxNode node) { - while (node != null) + while (node is not null) { SyntaxKind kind = node.Kind(); @@ -221,7 +221,7 @@ void ReportDiagnostic() { ITypeParameterSymbol typeParameterSymbol = namedTypeSymbol.TypeParameters.LastOrDefault(); - if (typeParameterSymbol != null + if (typeParameterSymbol is not null && parameterSymbol.ContainingSymbol.OriginalDefinition is IMethodSymbol methodSymbol2) { foreach (ITypeParameterSymbol typeParameterSymbol2 in methodSymbol2.TypeParameters) diff --git a/src/Analyzers/CSharp/Analysis/EnumShouldDeclareExplicitValuesAnalyzer.cs b/src/Analyzers/CSharp/Analysis/EnumShouldDeclareExplicitValuesAnalyzer.cs index f972454723..fa1054e9c3 100644 --- a/src/Analyzers/CSharp/Analysis/EnumShouldDeclareExplicitValuesAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/EnumShouldDeclareExplicitValuesAnalyzer.cs @@ -38,7 +38,7 @@ private static void AnalyzeEnumDeclaration(SyntaxNodeAnalysisContext context) foreach (EnumMemberDeclarationSyntax enumMember in enumDeclaration.Members) { - if (enumMember.EqualsValue == null + if (enumMember.EqualsValue is null && context.SemanticModel.GetDeclaredSymbol(enumMember, context.CancellationToken)?.HasConstantValue == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.EnumShouldDeclareExplicitValues, enumDeclaration.Identifier); diff --git a/src/Analyzers/CSharp/Analysis/EnumSymbolAnalyzer.cs b/src/Analyzers/CSharp/Analysis/EnumSymbolAnalyzer.cs index ed8d4ce331..9062b002c6 100644 --- a/src/Analyzers/CSharp/Analysis/EnumSymbolAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/EnumSymbolAnalyzer.cs @@ -115,7 +115,7 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) ExpressionSyntax expression = declaration.EqualsValue?.Value.WalkDownParentheses(); - if (expression != null + if (expression is not null && (expression.IsKind(SyntaxKind.NumericLiteralExpression) || expression .DescendantNodes() @@ -198,25 +198,25 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) var enumMember1 = (EnumMemberDeclarationSyntax)symbolInfo1.Symbol.GetSyntax(context.CancellationToken); - if (enumMember1 == null) + if (enumMember1 is null) continue; var enumMember2 = (EnumMemberDeclarationSyntax)symbolInfo2.Symbol.GetSyntax(context.CancellationToken); - if (enumMember2 == null) + if (enumMember2 is null) continue; ExpressionSyntax value1 = enumMember1.EqualsValue?.Value?.WalkDownParentheses(); ExpressionSyntax value2 = enumMember2.EqualsValue?.Value?.WalkDownParentheses(); - if (value1 == null) + if (value1 is null) { - if (value2 != null) + if (value2 is not null) { ReportDuplicateValue(context, enumMember1, value2); } } - else if (value2 == null) + else if (value2 is null) { ReportDuplicateValue(context, enumMember2, value1); } diff --git a/src/Analyzers/CSharp/Analysis/FormatDocumentationCommentSummaryAnalyzer.cs b/src/Analyzers/CSharp/Analysis/FormatDocumentationCommentSummaryAnalyzer.cs index 0ac7981120..d72acb83be 100644 --- a/src/Analyzers/CSharp/Analysis/FormatDocumentationCommentSummaryAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/FormatDocumentationCommentSummaryAnalyzer.cs @@ -81,7 +81,7 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys { XmlElementSyntax summaryElement = documentationComment.SummaryElement(); - if (summaryElement != null) + if (summaryElement is not null) { XmlElementStartTagSyntax startTag = summaryElement?.StartTag; diff --git a/src/Analyzers/CSharp/Analysis/FormatSummaryOnSingleLineAnalyzer.cs b/src/Analyzers/CSharp/Analysis/FormatSummaryOnSingleLineAnalyzer.cs index f9f48df292..32d20c8055 100644 --- a/src/Analyzers/CSharp/Analysis/FormatSummaryOnSingleLineAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/FormatSummaryOnSingleLineAnalyzer.cs @@ -61,7 +61,7 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys XmlElementSyntax summaryElement = documentationComment.SummaryElement(); - if (summaryElement != null) + if (summaryElement is not null) { XmlElementStartTagSyntax startTag = summaryElement?.StartTag; diff --git a/src/Analyzers/CSharp/Analysis/ImplementExceptionConstructorsAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ImplementExceptionConstructorsAnalyzer.cs index 4507114d5d..a24d18657d 100644 --- a/src/Analyzers/CSharp/Analysis/ImplementExceptionConstructorsAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ImplementExceptionConstructorsAnalyzer.cs @@ -32,7 +32,7 @@ public override void Initialize(AnalysisContext context) { INamedTypeSymbol exceptionSymbol = startContext.Compilation.GetTypeByMetadataName("System.Exception"); - if (exceptionSymbol == null) + if (exceptionSymbol is null) return; startContext.RegisterSymbolAction(f => AnalyzeNamedType(f, exceptionSymbol), SymbolKind.NamedType); diff --git a/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs b/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs index 2d5125d89f..0fb1c0900e 100644 --- a/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs @@ -65,7 +65,7 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c ExpressionSyntax value = localDeclarationInfo.Value; - if (value == null) + if (value is null) return; SyntaxList statements = SyntaxInfo.StatementListInfo(localDeclarationStatement).Statements; @@ -171,7 +171,7 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c } finally { - if (walker != null) + if (walker is not null) ContainsLocalOrParameterReferenceWalker.Free(walker); } @@ -211,7 +211,7 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c } finally { - if (walker != null) + if (walker is not null) ContainsLocalOrParameterReferenceWalker.Free(walker); } @@ -267,7 +267,7 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c } finally { - if (walker != null) + if (walker is not null) ContainsLocalOrParameterReferenceWalker.Free(walker); } } @@ -317,7 +317,7 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c } finally { - if (walker != null) + if (walker is not null) ContainsLocalOrParameterReferenceWalker.Free(walker); } } diff --git a/src/Analyzers/CSharp/Analysis/JoinStringExpressionsAnalyzer.cs b/src/Analyzers/CSharp/Analysis/JoinStringExpressionsAnalyzer.cs index 7488cf6fd6..eec9b92e79 100644 --- a/src/Analyzers/CSharp/Analysis/JoinStringExpressionsAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/JoinStringExpressionsAnalyzer.cs @@ -68,7 +68,7 @@ private static void AnalyzeAddExpression(SyntaxNodeAnalysisContext context) bool isVerbatim2 = stringLiteral.IsVerbatim; - if (firstExpression == null) + if (firstExpression is null) { firstExpression = expression; isLiteral = true; @@ -81,7 +81,7 @@ private static void AnalyzeAddExpression(SyntaxNodeAnalysisContext context) || isVerbatim != isVerbatim2 || (!isVerbatim && !CheckHexadecimalEscapeSequence(stringLiteral))) { - if (lastExpression != null) + if (lastExpression is not null) Analyze(context, firstExpression, lastExpression, isVerbatim); firstExpression = null; @@ -115,7 +115,7 @@ private static void AnalyzeAddExpression(SyntaxNodeAnalysisContext context) bool isVerbatim2 = interpolatedString.IsVerbatim(); - if (firstExpression == null) + if (firstExpression is null) { firstExpression = expression; isLiteral = false; @@ -128,7 +128,7 @@ private static void AnalyzeAddExpression(SyntaxNodeAnalysisContext context) || isVerbatim != isVerbatim2 || (!isVerbatim && !CheckHexadecimalEscapeSequence(interpolatedString))) { - if (lastExpression != null) + if (lastExpression is not null) Analyze(context, firstExpression, lastExpression, isVerbatim); firstExpression = null; @@ -158,7 +158,7 @@ private static void AnalyzeAddExpression(SyntaxNodeAnalysisContext context) } default: { - if (lastExpression != null) + if (lastExpression is not null) Analyze(context, firstExpression, lastExpression, isVerbatim); firstExpression = null; @@ -168,7 +168,7 @@ private static void AnalyzeAddExpression(SyntaxNodeAnalysisContext context) } } - if (lastExpression != null) + if (lastExpression is not null) Analyze(context, firstExpression, lastExpression, isVerbatim); } diff --git a/src/Analyzers/CSharp/Analysis/MakeClassStaticAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MakeClassStaticAnalyzer.cs index 0e243b96cd..97380965d5 100644 --- a/src/Analyzers/CSharp/Analysis/MakeClassStaticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MakeClassStaticAnalyzer.cs @@ -86,7 +86,7 @@ private static void AnalyzeClassDeclaration(SyntaxNodeAnalysisContext context) } finally { - if (walker != null) + if (walker is not null) MakeClassStaticWalker.Free(walker); } @@ -217,10 +217,10 @@ public static MakeClassStaticWalker GetInstance() { MakeClassStaticWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { - Debug.Assert(walker.Symbol == null); - Debug.Assert(walker.SemanticModel == null); + Debug.Assert(walker.Symbol is null); + Debug.Assert(walker.SemanticModel is null); Debug.Assert(walker.CancellationToken == default); _cachedInstance = null; diff --git a/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs index 676f0c97e7..858c1f1c5e 100644 --- a/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs @@ -67,7 +67,7 @@ private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) } finally { - if (walker != null) + if (walker is not null) MakeMemberReadOnlyWalker.Free(walker); } } @@ -98,7 +98,7 @@ private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) AccessorDeclarationSyntax setter = propertyDeclaration.Setter(); if (setter?.IsKind(SyntaxKind.InitAccessorDeclaration) == false - && setter.BodyOrExpressionBody() == null + && setter.BodyOrExpressionBody() is null && !setter.AttributeLists.Any() && !setter.SpanContainsDirectives()) { diff --git a/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyWalker.cs b/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyWalker.cs index 3b85491d55..ffdc44955e 100644 --- a/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyWalker.cs +++ b/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyWalker.cs @@ -32,10 +32,10 @@ public static MakeMemberReadOnlyWalker GetInstance() { MakeMemberReadOnlyWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { Debug.Assert(walker.Symbols.Count == 0); - Debug.Assert(walker.SemanticModel == null); + Debug.Assert(walker.SemanticModel is null); Debug.Assert(walker.CancellationToken == default); _cachedInstance = null; @@ -126,7 +126,7 @@ public override void VisitRefExpression(RefExpressionSyntax node) { ExpressionSyntax expression = node.Expression; - if (expression != null) + if (expression is not null) { VisitAssignedExpression(expression); } diff --git a/src/Analyzers/CSharp/Analysis/MakeMethodExtensionMethodAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MakeMethodExtensionMethodAnalyzer.cs index 05cc567e4c..471894c46d 100644 --- a/src/Analyzers/CSharp/Analysis/MakeMethodExtensionMethodAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MakeMethodExtensionMethodAnalyzer.cs @@ -61,10 +61,10 @@ private static void AnalyzeClassDeclaration(SyntaxNodeAnalysisContext context) ParameterSyntax parameter = methodDeclaration.ParameterList?.Parameters.FirstOrDefault(); - if (parameter == null) + if (parameter is null) continue; - if (parameter.Default != null) + if (parameter.Default is not null) continue; if (parameter.Type.IsKind(SyntaxKind.PointerType)) diff --git a/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstAnalyzer.cs index edc632c2ae..7e069a0481 100644 --- a/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstAnalyzer.cs @@ -128,7 +128,7 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c } finally { - if (walker != null) + if (walker is not null) MarkLocalVariableAsConstWalker.Free(walker); } diff --git a/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstWalker.cs b/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstWalker.cs index e0118e1e60..0714013ea6 100644 --- a/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstWalker.cs +++ b/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstWalker.cs @@ -76,7 +76,7 @@ public static MarkLocalVariableAsConstWalker GetInstance() { MarkLocalVariableAsConstWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { Debug.Assert(walker.Identifiers.Count == 0); Debug.Assert(!walker.Result); diff --git a/src/Analyzers/CSharp/Analysis/MarkTypeWithDebuggerDisplayAttributeAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MarkTypeWithDebuggerDisplayAttributeAnalyzer.cs index 1f0dd25ee5..675d072707 100644 --- a/src/Analyzers/CSharp/Analysis/MarkTypeWithDebuggerDisplayAttributeAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MarkTypeWithDebuggerDisplayAttributeAnalyzer.cs @@ -32,7 +32,7 @@ public override void Initialize(AnalysisContext context) { INamedTypeSymbol debuggerDisplayAttributeSymbol = startContext.Compilation.GetTypeByMetadataName("System.Diagnostics.DebuggerDisplayAttribute"); - if (debuggerDisplayAttributeSymbol != null) + if (debuggerDisplayAttributeSymbol is not null) { startContext.RegisterSymbolAction( nodeContext => AnalyzerNamedTypeSymbol(nodeContext, debuggerDisplayAttributeSymbol), diff --git a/src/Analyzers/CSharp/Analysis/MergeSwitchSectionsAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MergeSwitchSectionsAnalyzer.cs index a56c8c0fb6..289ee74b96 100644 --- a/src/Analyzers/CSharp/Analysis/MergeSwitchSectionsAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MergeSwitchSectionsAnalyzer.cs @@ -47,7 +47,7 @@ private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) SwitchSectionSyntax section = FindFixableSection(sections); - if (section == null) + if (section is null) return; DiagnosticHelpers.ReportDiagnostic( @@ -114,15 +114,15 @@ private static bool AreEquivalentJumpStatements(StatementSyntax statement1, Stat } case ReturnStatementSyntax returnStatement: { - return returnStatement.Expression == null + return returnStatement.Expression is null && (statement2 is ReturnStatementSyntax returnStatement2) - && returnStatement2.Expression == null; + && returnStatement2.Expression is null; } case ThrowStatementSyntax throwStatement: { - return throwStatement.Expression == null + return throwStatement.Expression is null && (statement2 is ThrowStatementSyntax throwStatement2) - && throwStatement2.Expression == null; + && throwStatement2.Expression is null; } } diff --git a/src/Analyzers/CSharp/Analysis/NonAsynchronousMethodNameShouldNotEndWithAsyncAnalyzer.cs b/src/Analyzers/CSharp/Analysis/NonAsynchronousMethodNameShouldNotEndWithAsyncAnalyzer.cs index cd0f13271e..b4b02463e6 100644 --- a/src/Analyzers/CSharp/Analysis/NonAsynchronousMethodNameShouldNotEndWithAsyncAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/NonAsynchronousMethodNameShouldNotEndWithAsyncAnalyzer.cs @@ -40,7 +40,7 @@ public override void Initialize(AnalysisContext context) { INamedTypeSymbol asyncAction = startContext.Compilation.GetTypeByMetadataName("Windows.Foundation.IAsyncAction"); - bool shouldCheckWindowsRuntimeTypes = asyncAction != null; + bool shouldCheckWindowsRuntimeTypes = asyncAction is not null; startContext.RegisterSyntaxNodeAction( c => diff --git a/src/Analyzers/CSharp/Analysis/NormalizeFormatOfEnumFlagValueAnalyzer.cs b/src/Analyzers/CSharp/Analysis/NormalizeFormatOfEnumFlagValueAnalyzer.cs index d54b2b023b..447dfdb866 100644 --- a/src/Analyzers/CSharp/Analysis/NormalizeFormatOfEnumFlagValueAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/NormalizeFormatOfEnumFlagValueAnalyzer.cs @@ -58,7 +58,7 @@ private void AnalyzeEnumDeclaration(SyntaxNodeAnalysisContext context) { ExpressionSyntax value = member.EqualsValue?.Value.WalkDownParentheses(); - if (value != null) + if (value is not null) { if (value.IsKind(SyntaxKind.NumericLiteralExpression)) { diff --git a/src/Analyzers/CSharp/Analysis/NormalizeUsageOfInfiniteLoopAnalyzer.cs b/src/Analyzers/CSharp/Analysis/NormalizeUsageOfInfiniteLoopAnalyzer.cs index 72b857b260..fa0663092c 100644 --- a/src/Analyzers/CSharp/Analysis/NormalizeUsageOfInfiniteLoopAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/NormalizeUsageOfInfiniteLoopAnalyzer.cs @@ -44,8 +44,8 @@ private void AnalyzeForStatement(SyntaxNodeAnalysisContext context) { var forStatement = (ForStatementSyntax)context.Node; - if (forStatement.Declaration == null - && forStatement.Condition == null + if (forStatement.Declaration is null + && forStatement.Condition is null && !forStatement.Incrementors.Any() && !forStatement.Initializers.Any() && !forStatement.OpenParenToken.ContainsDirectives diff --git a/src/Analyzers/CSharp/Analysis/OptimizeLinqMethodCallAnalysis.cs b/src/Analyzers/CSharp/Analysis/OptimizeLinqMethodCallAnalysis.cs index 2b147b9a91..3ab7b3a250 100644 --- a/src/Analyzers/CSharp/Analysis/OptimizeLinqMethodCallAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/OptimizeLinqMethodCallAnalysis.cs @@ -55,7 +55,7 @@ public static void AnalyzeAny(SyntaxNodeAnalysisContext context, in SimpleMember ? conditionalExpression.WhenTrue?.WalkDownParentheses() : conditionalExpression.WhenFalse?.WalkDownParentheses(); - if (secondExpression == null) + if (secondExpression is null) return; SimpleMemberInvocationExpressionInfo invocationInfo2 = SyntaxInfo.SimpleMemberInvocationExpressionInfo((InvocationExpressionSyntax)firstExpression); @@ -68,7 +68,7 @@ public static void AnalyzeAny(SyntaxNodeAnalysisContext context, in SimpleMember ExtensionMethodSymbolInfo extensionMethodSymbolInfo = semanticModel.GetExtensionMethodInfo(invocationExpression, cancellationToken); - if (extensionMethodSymbolInfo.Symbol == null) + if (extensionMethodSymbolInfo.Symbol is null) return; if (!extensionMethodSymbolInfo.IsReduced) @@ -79,7 +79,7 @@ public static void AnalyzeAny(SyntaxNodeAnalysisContext context, in SimpleMember IMethodSymbol methodSymbol2 = semanticModel.GetExtensionMethodInfo(invocationInfo2.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol2, "First")) @@ -151,7 +151,7 @@ public static void AnalyzeWhere(SyntaxNodeAnalysisContext context, in SimpleMemb IMethodSymbol methodSymbol = semanticModel.GetExtensionMethodInfo(invocation, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, invocationInfo.NameText)) @@ -159,7 +159,7 @@ public static void AnalyzeWhere(SyntaxNodeAnalysisContext context, in SimpleMemb IMethodSymbol methodSymbol2 = semanticModel.GetExtensionMethodInfo(invocationInfo2.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; switch (methodName) @@ -207,7 +207,7 @@ public static void AnalyzeFirstOrDefault(SyntaxNodeAnalysisContext context, in S IMethodSymbol methodSymbol = extensionMethodSymbolInfo.Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (methodSymbol.DeclaredAccessibility != Accessibility.Public) @@ -215,7 +215,7 @@ public static void AnalyzeFirstOrDefault(SyntaxNodeAnalysisContext context, in S INamedTypeSymbol containingType = methodSymbol.ContainingType; - if (containingType == null) + if (containingType is null) return; var success = false; @@ -233,7 +233,7 @@ public static void AnalyzeFirstOrDefault(SyntaxNodeAnalysisContext context, in S { ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(invocationInfo.Expression, context.CancellationToken); - if (typeSymbol != null) + if (typeSymbol is not null) { if (typeSymbol.Kind == SymbolKind.ArrayType) { @@ -318,7 +318,7 @@ public static void AnalyzeWhereAndAny(SyntaxNodeAnalysisContext context, in Simp ArgumentSyntax argument2 = invocationInfo2.Arguments.SingleOrDefault(shouldThrow: false); - if (argument2 == null) + if (argument2 is null) return; SemanticModel semanticModel = context.SemanticModel; @@ -328,7 +328,7 @@ public static void AnalyzeWhereAndAny(SyntaxNodeAnalysisContext context, in Simp IMethodSymbol methodSymbol = semanticModel.GetExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithPredicate(methodSymbol, "Any")) @@ -336,7 +336,7 @@ public static void AnalyzeWhereAndAny(SyntaxNodeAnalysisContext context, in Simp IMethodSymbol methodSymbol2 = semanticModel.GetExtensionMethodInfo(invocationInfo2.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; if (!SymbolUtility.IsLinqWhere(methodSymbol2, allowImmutableArrayExtension: true)) @@ -373,7 +373,7 @@ public static void AnalyzeWhereAndCast(SyntaxNodeAnalysisContext context, in Sim ArgumentSyntax argument = invocationInfo2.Arguments.SingleOrDefault(shouldThrow: false); - if (argument == null) + if (argument is null) return; if (!string.Equals(invocationInfo2.NameText, "Where", StringComparison.Ordinal)) @@ -385,7 +385,7 @@ public static void AnalyzeWhereAndCast(SyntaxNodeAnalysisContext context, in Sim IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqCast(methodSymbol)) @@ -393,7 +393,7 @@ public static void AnalyzeWhereAndCast(SyntaxNodeAnalysisContext context, in Sim IMethodSymbol methodSymbol2 = semanticModel.GetReducedExtensionMethodInfo(invocationInfo2.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; if (!SymbolUtility.IsLinqWhere(methodSymbol2)) @@ -406,12 +406,12 @@ public static void AnalyzeWhereAndCast(SyntaxNodeAnalysisContext context, in Sim TypeSyntax type2 = (invocationInfo.Name as GenericNameSyntax)?.TypeArgumentList?.Arguments.SingleOrDefault(shouldThrow: false); - if (type2 == null) + if (type2 is null) return; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(isExpressionInfo.Type, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; ITypeSymbol typeSymbol2 = semanticModel.GetTypeSymbol(type2, cancellationToken); @@ -433,7 +433,7 @@ public static void AnalyzeWhereAndCast(SyntaxNodeAnalysisContext context, in Sim .Arguments .SingleOrDefault(shouldThrow: false); - if (typeArgument == null) + if (typeArgument is null) return; SemanticModel semanticModel = context.SemanticModel; @@ -443,7 +443,7 @@ public static void AnalyzeWhereAndCast(SyntaxNodeAnalysisContext context, in Sim IMethodSymbol methodSymbol = extensionMethodSymbolInfo.Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqOfType(methodSymbol)) @@ -472,7 +472,7 @@ public static void AnalyzeWhereAndCast(SyntaxNodeAnalysisContext context, in Sim IMethodSymbol methodSymbol = extensionMethodSymbolInfo.Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "First")) @@ -501,7 +501,7 @@ public static void AnalyzeCount(SyntaxNodeAnalysisContext context, in SimpleMemb IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "Count")) @@ -511,12 +511,12 @@ public static void AnalyzeCount(SyntaxNodeAnalysisContext context, in SimpleMemb ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; string propertyName = SymbolUtility.GetCountOrLengthPropertyName(typeSymbol, semanticModel, expression.SpanStart); - if (propertyName != null) + if (propertyName is not null) { if (CanBeReplacedWithMemberAccessExpression(invocationExpression) && CheckInfiniteRecursion(typeSymbol, propertyName, invocationExpression.SpanStart, semanticModel, cancellationToken)) @@ -635,7 +635,7 @@ public static void AnalyzeOrderByAndWhere(SyntaxNodeAnalysisContext context, in IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfT(methodSymbol, "Where", parameterCount: 2)) @@ -643,7 +643,7 @@ public static void AnalyzeOrderByAndWhere(SyntaxNodeAnalysisContext context, in IMethodSymbol methodSymbol2 = semanticModel.GetReducedExtensionMethodInfo(invocationInfo2.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfT(methodSymbol2, name2, new Interval(2, 3))) @@ -664,7 +664,7 @@ public static void AnalyzeOrderByAndReverse(SyntaxNodeAnalysisContext context, i ArgumentSyntax argument = invocationInfo2.Arguments.SingleOrDefault(shouldThrow: false); - if (argument == null) + if (argument is null) return; if (!string.Equals(invocationInfo2.NameText, "OrderBy", StringComparison.Ordinal)) @@ -677,7 +677,7 @@ public static void AnalyzeOrderByAndReverse(SyntaxNodeAnalysisContext context, i IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "Reverse")) @@ -685,7 +685,7 @@ public static void AnalyzeOrderByAndReverse(SyntaxNodeAnalysisContext context, i IMethodSymbol methodSymbol2 = semanticModel.GetReducedExtensionMethodInfo(invocationInfo2.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfT(methodSymbol2, "OrderBy", parameterCount: 2)) @@ -706,7 +706,7 @@ public static bool AnalyzeSelectManyAndCount(SyntaxNodeAnalysisContext context, ArgumentSyntax argument = invocationInfo2.Arguments.SingleOrDefault(shouldThrow: false); - if (argument == null) + if (argument is null) return false; if (!string.Equals(invocationInfo2.NameText, "SelectMany", StringComparison.Ordinal)) @@ -719,7 +719,7 @@ public static bool AnalyzeSelectManyAndCount(SyntaxNodeAnalysisContext context, IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return false; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "Count")) @@ -727,7 +727,7 @@ public static bool AnalyzeSelectManyAndCount(SyntaxNodeAnalysisContext context, IMethodSymbol methodSymbol2 = semanticModel.GetReducedExtensionMethodInfo(invocationInfo2.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol2 == null) + if (methodSymbol2 is null) return false; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfT(methodSymbol2, "SelectMany", parameterCount: 2)) @@ -735,17 +735,17 @@ public static bool AnalyzeSelectManyAndCount(SyntaxNodeAnalysisContext context, ExpressionSyntax expression = GetLambdaExpression(argument.Expression); - if (expression == null) + if (expression is null) return false; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return false; string propertyName = SymbolUtility.GetCountOrLengthPropertyName(typeSymbol, semanticModel, expression.SpanStart); - if (propertyName != null + if (propertyName is not null && CheckInfiniteRecursion(typeSymbol, propertyName, invocationExpression.SpanStart, semanticModel, cancellationToken)) { TextSpan span = TextSpan.FromBounds(invocationInfo2.Name.SpanStart, invocationExpression.Span.End); @@ -785,7 +785,7 @@ private static ExpressionSyntax GetLambdaExpression(ExpressionSyntax expression) { ISymbol symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); - if (symbol != null) + if (symbol is not null) { IPropertySymbol propertySymbol = null; diff --git a/src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs b/src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs index 4bc5c7d918..8f6dbc2b59 100644 --- a/src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs @@ -149,7 +149,7 @@ public static void OptimizeStringJoin(SyntaxNodeAnalysisContext context, in Simp ArgumentSyntax firstArgument = invocationInfo.Arguments.FirstOrDefault(); - if (firstArgument == null) + if (firstArgument is null) return; if (invocationInfo.MemberAccessExpression.SpanOrTrailingTriviaContainsDirectives() @@ -187,7 +187,7 @@ public static void OptimizeStringJoin(SyntaxNodeAnalysisContext context, in Simp return; } - if (firstArgument.Expression == null) + if (firstArgument.Expression is null) return; if (!CSharpUtility.IsEmptyStringExpression(firstArgument.Expression, semanticModel, cancellationToken)) @@ -354,7 +354,7 @@ public static void OptimizeAdd(SyntaxNodeAnalysisContext context, in SimpleMembe && context.SemanticModel.IsImplicitConversion(forEachStatement.Expression, methodSymbol.Parameters[0].Type) && forEachStatement.CloseParenToken.TrailingTrivia.IsEmptyOrWhitespace() && invocation.GetLeadingTrivia().IsEmptyOrWhitespace() - && (block == null + && (block is null || SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(block.OpenBraceToken))) { DiagnosticHelpers.ReportDiagnostic( diff --git a/src/Analyzers/CSharp/Analysis/OptimizeStringBuilderAppendCallAnalysis.cs b/src/Analyzers/CSharp/Analysis/OptimizeStringBuilderAppendCallAnalysis.cs index f0b6267102..b8fa284912 100644 --- a/src/Analyzers/CSharp/Analysis/OptimizeStringBuilderAppendCallAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/OptimizeStringBuilderAppendCallAnalysis.cs @@ -15,7 +15,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv { IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(invocationInfo.InvocationExpression, context.CancellationToken); - if (methodSymbol == null) + if (methodSymbol is null) return; if (methodSymbol.IsExtensionMethod) @@ -59,7 +59,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv ArgumentSyntax argument = invocationInfo.Arguments.SingleOrDefault(shouldThrow: false); - if (argument == null) + if (argument is null) return; ExpressionSyntax expression = argument.Expression; @@ -105,7 +105,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv IMethodSymbol methodSymbol2 = context.SemanticModel.GetMethodSymbol(invocationInfo2.InvocationExpression, context.CancellationToken); - if (methodSymbol2 == null) + if (methodSymbol2 is null) return; if (!methodSymbol2.IsContainingType(SpecialType.System_String)) diff --git a/src/Analyzers/CSharp/Analysis/OrderNamedArgumentsAnalyzer.cs b/src/Analyzers/CSharp/Analysis/OrderNamedArgumentsAnalyzer.cs index f87ca04724..df07ee281f 100644 --- a/src/Analyzers/CSharp/Analysis/OrderNamedArgumentsAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/OrderNamedArgumentsAnalyzer.cs @@ -71,7 +71,7 @@ private static void AnalyzeBaseArgumentList(SyntaxNodeAnalysisContext context) for (int i = arguments.Count - 1; i >= 0; i--) { - if (arguments[i].NameColon != null) + if (arguments[i].NameColon is not null) { firstIndex = i; } diff --git a/src/Analyzers/CSharp/Analysis/OverridingMemberShouldNotChangeParamsModifierAnalyzer.cs b/src/Analyzers/CSharp/Analysis/OverridingMemberShouldNotChangeParamsModifierAnalyzer.cs index 5b1351f5ee..250e9abb6d 100644 --- a/src/Analyzers/CSharp/Analysis/OverridingMemberShouldNotChangeParamsModifierAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/OverridingMemberShouldNotChangeParamsModifierAnalyzer.cs @@ -39,7 +39,7 @@ private static void AnalyzeMethodSymbol(SymbolAnalysisContext context) IParameterSymbol lastParameterSymbol = methodSymbol.OverriddenMethod?.Parameters.LastOrDefault(); - if (lastParameterSymbol == null) + if (lastParameterSymbol is null) return; if (methodSymbol.GetSyntaxOrDefault(context.CancellationToken) is not MethodDeclarationSyntax methodDeclaration) @@ -47,7 +47,7 @@ private static void AnalyzeMethodSymbol(SymbolAnalysisContext context) ParameterSyntax lastParameter = methodDeclaration.ParameterList?.Parameters.LastOrDefault(); - if (lastParameter == null) + if (lastParameter is null) return; if (lastParameter.Modifiers.Contains(SyntaxKind.ParamsKeyword) == lastParameterSymbol.IsParams) @@ -65,7 +65,7 @@ private static void AnalyzePropertySymbol(SymbolAnalysisContext context) IParameterSymbol lastParameterSymbol = propertySymbol.OverriddenProperty?.Parameters.LastOrDefault(); - if (lastParameterSymbol == null) + if (lastParameterSymbol is null) return; if (propertySymbol.GetSyntaxOrDefault(context.CancellationToken) is not IndexerDeclarationSyntax indexerDeclaration) @@ -73,7 +73,7 @@ private static void AnalyzePropertySymbol(SymbolAnalysisContext context) ParameterSyntax lastParameter = indexerDeclaration.ParameterList?.Parameters.LastOrDefault(); - if (lastParameter == null) + if (lastParameter is null) return; if (lastParameter.Modifiers.Contains(SyntaxKind.ParamsKeyword) == lastParameterSymbol.IsParams) diff --git a/src/Analyzers/CSharp/Analysis/ParameterNameDiffersFromBaseAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ParameterNameDiffersFromBaseAnalyzer.cs index e78df1aa2b..a6e5ad334e 100644 --- a/src/Analyzers/CSharp/Analysis/ParameterNameDiffersFromBaseAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ParameterNameDiffersFromBaseAnalyzer.cs @@ -44,7 +44,7 @@ private static void AnalyzeMethodSymbol(SymbolAnalysisContext context) { IMethodSymbol baseSymbol = methodSymbol.OverriddenMethod ?? methodSymbol.FindFirstImplementedInterfaceMember(); - if (baseSymbol != null) + if (baseSymbol is not null) Analyze(context, parameters, baseSymbol.Parameters); } } @@ -61,7 +61,7 @@ private static void AnalyzePropertySymbol(SymbolAnalysisContext context) { IPropertySymbol baseSymbol = propertySymbol.OverriddenProperty ?? propertySymbol.FindFirstImplementedInterfaceMember(); - if (baseSymbol != null) + if (baseSymbol is not null) Analyze(context, parameters, baseSymbol.Parameters); } } diff --git a/src/Analyzers/CSharp/Analysis/RefReadOnlyParameterAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RefReadOnlyParameterAnalyzer.cs index 3b1e7e25cc..1eb281af7b 100644 --- a/src/Analyzers/CSharp/Analysis/RefReadOnlyParameterAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RefReadOnlyParameterAnalyzer.cs @@ -99,10 +99,10 @@ private static void AnalyzeLocalFunction(SyntaxNodeAnalysisContext context) ParameterListSyntax parameterList, CSharpSyntaxNode bodyOrExpressionBody) { - if (parameterList == null) + if (parameterList is null) return; - if (bodyOrExpressionBody == null) + if (bodyOrExpressionBody is null) return; if (!parameterList.Parameters.Any()) @@ -145,7 +145,7 @@ private static void AnalyzeLocalFunction(SyntaxNodeAnalysisContext context) if (parameter.RefKind != RefKind.None) continue; - if (walker == null) + if (walker is null) { if (methodSymbol.ImplementsInterfaceMember(allInterfaces: true)) break; @@ -161,7 +161,7 @@ private static void AnalyzeLocalFunction(SyntaxNodeAnalysisContext context) walker.Parameters.Add(parameter.Name, parameter); } - if (walker == null) + if (walker is null) return; try @@ -326,10 +326,10 @@ public static SyntaxWalker GetInstance() { SyntaxWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { Debug.Assert(walker.Parameters.Count == 0); - Debug.Assert(walker.SemanticModel == null); + Debug.Assert(walker.SemanticModel is null); Debug.Assert(walker.CancellationToken == default); _cachedInstance = null; diff --git a/src/Analyzers/CSharp/Analysis/RemoveBracesAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveBracesAnalyzer.cs index 81198ed015..9bfa9ea2d7 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveBracesAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveBracesAnalyzer.cs @@ -117,7 +117,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = GetFixableBlock(ifStatement.Statement); - if (block == null) + if (block is null) return; if (!FormattingSupportsEmbeddedStatement(ifStatement)) @@ -132,7 +132,7 @@ private static void AnalyzeCommonForEachStatement(SyntaxNodeAnalysisContext cont BlockSyntax block = GetFixableBlock(forEachStatement.Statement); - if (block == null) + if (block is null) return; if (!FormattingSupportsEmbeddedStatement(forEachStatement)) @@ -147,7 +147,7 @@ private static void AnalyzeForStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = GetFixableBlock(forStatement.Statement); - if (block == null) + if (block is null) return; if (!FormattingSupportsEmbeddedStatement(forStatement)) @@ -162,7 +162,7 @@ private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = GetFixableBlock(usingStatement.Statement); - if (block == null) + if (block is null) return; if (!FormattingSupportsEmbeddedStatement(usingStatement)) @@ -177,7 +177,7 @@ private static void AnalyzeWhileStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = GetFixableBlock(whileStatement.Statement); - if (block == null) + if (block is null) return; if (!FormattingSupportsEmbeddedStatement(whileStatement)) @@ -192,7 +192,7 @@ private static void AnalyzeDoStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = GetFixableBlock(doStatement.Statement); - if (block == null) + if (block is null) return; if (!FormattingSupportsEmbeddedStatement(doStatement)) @@ -207,7 +207,7 @@ private static void AnalyzeLockStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = GetFixableBlock(lockStatement.Statement); - if (block == null) + if (block is null) return; if (!FormattingSupportsEmbeddedStatement(lockStatement)) @@ -222,7 +222,7 @@ private static void AnalyzeFixedStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = GetFixableBlock(fixedStatement.Statement); - if (block == null) + if (block is null) return; if (!FormattingSupportsEmbeddedStatement(fixedStatement)) @@ -238,7 +238,7 @@ private static BlockSyntax GetFixableBlock(StatementSyntax statement) statement = block.Statements.SingleOrDefault(shouldThrow: false); - if (statement == null) + if (statement is null) return null; if (statement.IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.LabeledStatement)) diff --git a/src/Analyzers/CSharp/Analysis/RemoveBracesFromIfElseAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveBracesFromIfElseAnalyzer.cs index 4d4817480d..f5a3625066 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveBracesFromIfElseAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveBracesFromIfElseAnalyzer.cs @@ -50,7 +50,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) if (ifStatement.IsParentKind(SyntaxKind.ElseClause)) return; - if (ifStatement.Else == null) + if (ifStatement.Else is null) return; BracesAnalysis analysis = BracesAnalysis.AnalyzeBraces(ifStatement); diff --git a/src/Analyzers/CSharp/Analysis/RemoveEmptyElseClauseAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveEmptyElseClauseAnalyzer.cs index 70dcfa7fd9..0fdc993778 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveEmptyElseClauseAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveEmptyElseClauseAnalyzer.cs @@ -51,7 +51,7 @@ private static void AnalyzeElseClause(SyntaxNodeAnalysisContext context) { var parentIf = (IfStatementSyntax)topmostIf.Parent; - if (parentIf.Else != null) + if (parentIf.Else is not null) return; } diff --git a/src/Analyzers/CSharp/Analysis/RemoveEmptyStatementAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveEmptyStatementAnalyzer.cs index e1331b4814..db74af6eba 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveEmptyStatementAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveEmptyStatementAnalyzer.cs @@ -37,7 +37,7 @@ private static void AnalyzeEmptyStatement(SyntaxNodeAnalysisContext context) SyntaxNode parent = emptyStatement.Parent; - if (parent == null) + if (parent is null) return; SyntaxKind kind = parent.Kind(); diff --git a/src/Analyzers/CSharp/Analysis/RemoveOriginalExceptionFromThrowStatementAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveOriginalExceptionFromThrowStatementAnalyzer.cs index ddb315d608..4e69f4e70c 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveOriginalExceptionFromThrowStatementAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveOriginalExceptionFromThrowStatementAnalyzer.cs @@ -41,7 +41,7 @@ private static void AnalyzeCatchClause(SyntaxNodeAnalysisContext context) CatchDeclarationSyntax declaration = catchClause.Declaration; - if (declaration == null) + if (declaration is null) return; SemanticModel semanticModel = context.SemanticModel; @@ -69,11 +69,11 @@ private static void AnalyzeCatchClause(SyntaxNodeAnalysisContext context) } finally { - if (walker != null) + if (walker is not null) Walker.Free(walker); } - if (expression != null) + if (expression is not null) { DiagnosticHelpers.ReportDiagnostic( context, @@ -103,7 +103,7 @@ public override void VisitThrowStatement(ThrowStatementSyntax node) { ExpressionSyntax expression = node.Expression; - if (expression != null) + if (expression is not null) { ISymbol symbol = SemanticModel.GetSymbol(expression, CancellationToken); @@ -118,12 +118,12 @@ public static Walker GetInstance() { Walker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { - Debug.Assert(walker.Symbol == null); - Debug.Assert(walker.SemanticModel == null); + Debug.Assert(walker.Symbol is null); + Debug.Assert(walker.SemanticModel is null); Debug.Assert(walker.CancellationToken == default); - Debug.Assert(walker.ThrowStatement == null); + Debug.Assert(walker.ThrowStatement is null); _cachedInstance = null; return walker; diff --git a/src/Analyzers/CSharp/Analysis/RemovePartialModifierFromTypeWithSinglePartAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemovePartialModifierFromTypeWithSinglePartAnalyzer.cs index a557547868..794047b3aa 100644 --- a/src/Analyzers/CSharp/Analysis/RemovePartialModifierFromTypeWithSinglePartAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemovePartialModifierFromTypeWithSinglePartAnalyzer.cs @@ -47,7 +47,7 @@ private void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) INamedTypeSymbol symbol = context.SemanticModel.GetDeclaredSymbol(typeDeclaration, context.CancellationToken); - if (symbol?.DeclaringSyntaxReferences.SingleOrDefault(shouldThrow: false) == null) + if (symbol?.DeclaringSyntaxReferences.SingleOrDefault(shouldThrow: false) is null) return; if (symbol.InheritsFrom(_componentBaseName)) @@ -60,7 +60,7 @@ private void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) var method = (MethodDeclarationSyntax)member; if (method.Modifiers.Contains(SyntaxKind.PartialKeyword) - && method.BodyOrExpressionBody() == null + && method.BodyOrExpressionBody() is null && method.ContainsUnbalancedIfElseDirectives(method.Span)) { return; diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs index fe3e6af807..d8a8978378 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs @@ -103,11 +103,11 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c ExpressionSyntax value = localInfo.Value; - if (value != null) + if (value is not null) { ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(localInfo.Type, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; if (!semanticModel.IsDefaultValue(typeSymbol, value, cancellationToken)) @@ -119,7 +119,7 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.RemoveRedundantAssignment, localInfo.Identifier); - if (value != null) + if (value is not null) { DiagnosticHelpers.ReportNode(context, DiagnosticRules.RemoveRedundantAssignmentFadeOut, localInfo.Initializer); DiagnosticHelpers.ReportToken(context, DiagnosticRules.RemoveRedundantAssignmentFadeOut, assignmentInfo.OperatorToken); @@ -245,7 +245,7 @@ private static void AnalyzeSimpleAssignment(SyntaxNodeAnalysisContext context) } finally { - if (walker != null) + if (walker is not null) RemoveRedundantAssignmentWalker.Free(walker); } @@ -266,13 +266,13 @@ bool IsAssignedInsideAnonymousFunctionButDeclaredOutsideOfIt() { if (CSharpFacts.IsAnonymousFunctionExpression(n.Kind())) { - if (declaringSyntax == null) + if (declaringSyntax is null) { declaringSyntax = symbol.GetSyntaxOrDefault(); - Debug.Assert(declaringSyntax != null, ""); + Debug.Assert(declaringSyntax is not null, ""); - if (declaringSyntax == null) + if (declaringSyntax is null) break; SyntaxDebug.Assert(declaringSyntax.IsKind(SyntaxKind.VariableDeclarator, SyntaxKind.Parameter), declaringSyntax); @@ -290,7 +290,7 @@ bool IsAssignedInsideAnonymousFunctionButDeclaredOutsideOfIt() n2 = n2.Parent; } - while (n2 != null); + while (n2 is not null); return true; } @@ -301,7 +301,7 @@ bool IsAssignedInsideAnonymousFunctionButDeclaredOutsideOfIt() n = n.Parent; } - while (n != null); + while (n is not null); return false; } @@ -314,7 +314,7 @@ bool IsAssignedInsideAnonymousFunctionButDeclaredOutsideOfIt() { SyntaxNode node = statement.Parent; - while (node != null + while (node is not null && node is not MemberDeclarationSyntax && !node.IsKind(SyntaxKind.FinallyClause)) { @@ -322,7 +322,7 @@ bool IsAssignedInsideAnonymousFunctionButDeclaredOutsideOfIt() { BlockSyntax block = tryStatement.Finally?.Block; - if (block != null) + if (block is not null) { ContainsLocalOrParameterReferenceWalker walker = null; @@ -337,7 +337,7 @@ bool IsAssignedInsideAnonymousFunctionButDeclaredOutsideOfIt() } finally { - if (walker != null) + if (walker is not null) ContainsLocalOrParameterReferenceWalker.Free(walker); } } @@ -405,10 +405,10 @@ public static RemoveRedundantAssignmentWalker GetInstance() { RemoveRedundantAssignmentWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { - Debug.Assert(walker.Symbol == null); - Debug.Assert(walker.SemanticModel == null); + Debug.Assert(walker.Symbol is null); + Debug.Assert(walker.SemanticModel is null); Debug.Assert(walker.CancellationToken == default); _cachedInstance = null; diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantAsyncAwaitAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantAsyncAwaitAnalyzer.cs index 098176628d..e9cdde45b5 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantAsyncAwaitAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantAsyncAwaitAnalyzer.cs @@ -157,7 +157,7 @@ private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxTo DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.RemoveRedundantAsyncAwait, asyncKeyword); DiagnosticHelpers.ReportToken(context, DiagnosticRules.RemoveRedundantAsyncAwaitFadeOut, asyncKeyword); - if (analysis.AwaitExpression != null) + if (analysis.AwaitExpression is not null) { ReportAwaitAndConfigureAwait(analysis.AwaitExpression); } diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantAutoPropertyInitializationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantAutoPropertyInitializationAnalyzer.cs index ebd4c72238..89c8aa4a57 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantAutoPropertyInitializationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantAutoPropertyInitializationAnalyzer.cs @@ -43,7 +43,7 @@ private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context ExpressionSyntax value = initializer?.Value?.WalkDownParentheses(); - if (value == null) + if (value is null) return; if (!CanBeConstantValue(value)) @@ -57,7 +57,7 @@ private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(propertyDeclaration.Type, context.CancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; if (!context.SemanticModel.IsDefaultValue(typeSymbol, value, context.CancellationToken)) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantBaseInterfaceAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantBaseInterfaceAnalyzer.cs index 796313c25e..eb567542c3 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantBaseInterfaceAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantBaseInterfaceAnalyzer.cs @@ -88,7 +88,7 @@ private static void AnalyzeBaseList(SyntaxNodeAnalysisContext context) { var baseInterfaceInfo = new SymbolInterfaceInfo(baseType, baseSymbol, allInterfaces); - if (baseInterfaceInfos == null) + if (baseInterfaceInfos is null) { if (allInterfaces.Any()) baseInterfaceInfos = new List() { baseInterfaceInfo }; @@ -102,9 +102,9 @@ private static void AnalyzeBaseList(SyntaxNodeAnalysisContext context) } } - if (baseClassInfo.Symbol != null) + if (baseClassInfo.Symbol is not null) { - if (typeSymbol == null) + if (typeSymbol is null) typeSymbol = context.SemanticModel.GetDeclaredSymbol((TypeDeclarationSyntax)baseList.Parent, context.CancellationToken); Analyze(baseInterfaceInfo, baseClassInfo); @@ -126,7 +126,7 @@ private static void AnalyzeBaseList(SyntaxNodeAnalysisContext context) { if (SymbolEqualityComparer.Default.Equals(interfaceInfo.Symbol, interfaceSymbol)) { - if (typeSymbol != null) + if (typeSymbol is not null) { if (members.IsDefault) members = typeSymbol.GetMembers(); @@ -228,7 +228,7 @@ bool IsExplicitlyImplemented(ISymbol interfaceSymbol) ISymbol symbol = typeSymbol.FindImplementationForInterfaceMember(member); - if (symbol != null) + if (symbol is not null) { foreach (SyntaxReference syntaxReference in symbol.DeclaringSyntaxReferences) { diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantCastAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantCastAnalyzer.cs index 4b621fdb36..120e89b26c 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantCastAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantCastAnalyzer.cs @@ -47,17 +47,17 @@ private static void AnalyzeCastExpression(SyntaxNodeAnalysisContext context) ExpressionSyntax accessedExpression = GetAccessedExpression(parenthesizedExpression.Parent); - if (accessedExpression == null) + if (accessedExpression is null) return; TypeSyntax type = castExpression.Type; - if (type == null) + if (type is null) return; ExpressionSyntax expression = castExpression.Expression; - if (expression == null) + if (expression is null) return; SemanticModel semanticModel = context.SemanticModel; @@ -88,7 +88,7 @@ private static void AnalyzeCastExpression(SyntaxNodeAnalysisContext context) INamedTypeSymbol containingType = accessedSymbol?.ContainingType; - if (containingType == null) + if (containingType is null) return; if (typeSymbol.TypeKind == TypeKind.Interface) @@ -124,7 +124,7 @@ private static bool CheckExplicitImplementation(ITypeSymbol typeSymbol, ISymbol { ISymbol implementation = typeSymbol.FindImplementationForInterfaceMember(symbol); - if (implementation == null) + if (implementation is null) return false; switch (implementation.Kind) @@ -173,7 +173,7 @@ private static bool CheckExplicitImplementation(ITypeSymbol typeSymbol, ISymbol { INamedTypeSymbol containingType = semanticModel.GetEnclosingNamedType(position, cancellationToken); - while (containingType != null) + while (containingType is not null) { if (SymbolEqualityComparer.Default.Equals(containingType, expressionTypeSymbol)) return true; @@ -190,7 +190,7 @@ private static bool CheckExplicitImplementation(ITypeSymbol typeSymbol, ISymbol if (SymbolEqualityComparer.Default.Equals(containingType?.ContainingAssembly, expressionTypeSymbol.ContainingAssembly)) return true; - while (containingType != null) + while (containingType is not null) { if (SymbolEqualityComparer.Default.Equals(containingType, expressionTypeSymbol)) return true; @@ -227,7 +227,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv ExtensionMethodSymbolInfo extensionInfo = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken); - if (extensionInfo.Symbol == null) + if (extensionInfo.Symbol is null) return; if (!SymbolUtility.IsLinqCast(extensionInfo.Symbol)) @@ -235,7 +235,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv ITypeSymbol typeArgument = extensionInfo.ReducedSymbol.TypeArguments.SingleOrDefault(shouldThrow: false); - if (typeArgument == null) + if (typeArgument is null) return; var memberAccessExpressionType = semanticModel.GetTypeSymbol(invocationInfo.Expression, cancellationToken) as INamedTypeSymbol; diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantConstructorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantConstructorAnalyzer.cs index d64cafcfb0..a7a678b48f 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantConstructorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantConstructorAnalyzer.cs @@ -57,7 +57,7 @@ private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext cont ConstructorInitializerSyntax initializer = constructor.Initializer; - if (initializer != null + if (initializer is not null && initializer.ArgumentList?.Arguments.Any() != false) { return; diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantDefaultSwitchSectionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantDefaultSwitchSectionAnalyzer.cs index 2fe7551f61..de99f0cfd7 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantDefaultSwitchSectionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantDefaultSwitchSectionAnalyzer.cs @@ -43,7 +43,7 @@ private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) SwitchSectionSyntax defaultSection = switchStatement.DefaultSection(); - if (defaultSection == null) + if (defaultSection is null) return; if (!ContainsOnlyBreakStatement(defaultSection)) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantDelegateCreationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantDelegateCreationAnalyzer.cs index f656a6e707..f42ee0b004 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantDelegateCreationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantDelegateCreationAnalyzer.cs @@ -84,7 +84,7 @@ private static void AnalyzeAssignmentExpression(SyntaxNodeAnalysisContext contex .Expression .WalkDownParentheses(); - if (expression == null) + if (expression is null) return; if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantDisposeOrCloseCallAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantDisposeOrCloseCallAnalyzer.cs index 135e97b84f..a11b2f193c 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantDisposeOrCloseCallAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantDisposeOrCloseCallAnalyzer.cs @@ -46,7 +46,7 @@ private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) StatementSyntax lastStatement = block.Statements.LastOrDefault(); - if (lastStatement == null) + if (lastStatement is null) return; if (lastStatement.SpanContainsDirectives()) @@ -67,7 +67,7 @@ private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) ExpressionSyntax usingExpression = usingStatement.Expression; - if (usingExpression != null) + if (usingExpression is not null) { if (CSharpFactory.AreEquivalent(info.Expression, usingExpression)) ReportDiagnostic(context, info.Statement, methodName); @@ -76,14 +76,14 @@ private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) { VariableDeclarationSyntax usingDeclaration = usingStatement.Declaration; - if (usingDeclaration != null + if (usingDeclaration is not null && info.Expression.Kind() == SyntaxKind.IdentifierName) { var identifierName = (IdentifierNameSyntax)info.Expression; VariableDeclaratorSyntax declarator = usingDeclaration.Variables.LastOrDefault(); - if (declarator != null + if (declarator is not null && declarator.Identifier.ValueText == identifierName.Identifier.ValueText) { ISymbol symbol = context.SemanticModel.GetDeclaredSymbol(declarator, context.CancellationToken); diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantFieldInitializationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantFieldInitializationAnalyzer.cs index ce9b775742..7c4562ee7b 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantFieldInitializationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantFieldInitializationAnalyzer.cs @@ -52,7 +52,7 @@ private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) VariableDeclarationSyntax declaration = fieldDeclaration.Declaration; - if (declaration == null) + if (declaration is null) return; foreach (VariableDeclaratorSyntax declarator in declaration.Variables) @@ -72,7 +72,7 @@ private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(declaration.Type, cancellationToken); - if (typeSymbol != null) + if (typeSymbol is not null) { if (CSharpFacts.IsNumericType(typeSymbol.SpecialType) && value.IsNumericLiteralExpression("0")) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantOverridingMemberAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantOverridingMemberAnalyzer.cs index 1d67dae21f..54003185ef 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantOverridingMemberAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantOverridingMemberAnalyzer.cs @@ -76,12 +76,12 @@ private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); - if (methodSymbol == null) + if (methodSymbol is null) return; IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; - if (overriddenMethod == null) + if (overriddenMethod is null) return; ISymbol symbol = semanticModel.GetSymbol(invocationInfo.Name, cancellationToken); @@ -153,7 +153,7 @@ private static bool CheckModifiers(SyntaxTokenList modifiers) private static IParameterSymbol GetParameterSymbol(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { - if (expression == null) + if (expression is null) return null; ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); @@ -217,11 +217,11 @@ private static ExpressionSyntax GetMethodExpression(MethodDeclarationSyntax meth { BlockSyntax body = methodDeclaration.Body; - if (body != null) + if (body is not null) { StatementSyntax statement = body.Statements.SingleOrDefault(shouldThrow: false); - if (statement != null) + if (statement is not null) { if (methodDeclaration.ReturnsVoid()) { @@ -266,7 +266,7 @@ private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context AccessorListSyntax accessorList = propertyDeclaration.AccessorList; - if (accessorList == null) + if (accessorList is null) return; foreach (AccessorDeclarationSyntax accessor in accessorList.Accessors) @@ -306,12 +306,12 @@ private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); - if (propertySymbol == null) + if (propertySymbol is null) return false; IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty == null) + if (overriddenProperty is null) return false; ISymbol symbol = semanticModel.GetSymbol(simpleName, cancellationToken); @@ -345,17 +345,17 @@ private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context SimpleNameSyntax simpleName = memberAccess.Name; - if (simpleName == null) + if (simpleName is null) return false; IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); - if (propertySymbol == null) + if (propertySymbol is null) return false; IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty == null) + if (overriddenProperty is null) return false; ISymbol symbol = semanticModel.GetSymbol(simpleName, cancellationToken); @@ -398,7 +398,7 @@ private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) AccessorListSyntax accessorList = indexerDeclaration.AccessorList; - if (accessorList == null) + if (accessorList is null) return; foreach (AccessorDeclarationSyntax accessor in accessorList.Accessors) @@ -432,17 +432,17 @@ private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) if (elementAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) return false; - if (elementAccess.ArgumentList == null) + if (elementAccess.ArgumentList is null) return false; IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(indexerDeclaration, cancellationToken); - if (propertySymbol == null) + if (propertySymbol is null) return false; IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty == null) + if (overriddenProperty is null) return false; ISymbol symbol = semanticModel.GetSymbol(elementAccess, cancellationToken); @@ -468,7 +468,7 @@ private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) if (elementAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) return false; - if (elementAccess.ArgumentList == null) + if (elementAccess.ArgumentList is null) return false; if (assignment.Right.Kind() != SyntaxKind.IdentifierName) @@ -481,12 +481,12 @@ private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(indexerDeclaration, cancellationToken); - if (propertySymbol == null) + if (propertySymbol is null) return false; IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty == null) + if (overriddenProperty is null) return false; ISymbol symbol = semanticModel.GetSymbol(elementAccess, cancellationToken); @@ -511,7 +511,7 @@ private static ExpressionSyntax GetGetAccessorExpression(AccessorDeclarationSynt { BlockSyntax body = accessor.Body; - if (body != null) + if (body is not null) { StatementSyntax statement = body.Statements.SingleOrDefault(shouldThrow: false); @@ -530,7 +530,7 @@ private static ExpressionSyntax GetSetAccessorExpression(AccessorDeclarationSynt { BlockSyntax body = accessor.Body; - if (body != null) + if (body is not null) { StatementSyntax statement = body.Statements.SingleOrDefault(shouldThrow: false); diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantToStringCallAnalysis.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantToStringCallAnalysis.cs index 324f5cd166..4d631c849a 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantToStringCallAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantToStringCallAnalysis.cs @@ -83,7 +83,7 @@ private static bool IsNotHidden(IMethodSymbol methodSymbol, INamedTypeSymbol con { IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; - while (overriddenMethod != null) + while (overriddenMethod is not null) { if (overriddenMethod.ContainingType?.SpecialType == SpecialType.System_Object) return true; diff --git a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBlankLineAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBlankLineAnalyzer.cs index cc4c95a73a..9f3cc0b8d0 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBlankLineAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBlankLineAnalyzer.cs @@ -182,7 +182,7 @@ private static void AnalyzeTryStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = tryStatement.Block; - if (block != null) + if (block is not null) { SyntaxList catches = tryStatement.Catches; @@ -199,7 +199,7 @@ private static void AnalyzeTryStatement(SyntaxNodeAnalysisContext context) FinallyClauseSyntax finallyClause = tryStatement.Finally; - if (finallyClause != null) + if (finallyClause is not null) Analyze(context, previousNode, finallyClause); } } @@ -215,12 +215,12 @@ private static void AnalyzeElseClause(SyntaxNodeAnalysisContext context) { StatementSyntax statement = ifStatement.Statement; - if (statement != null) + if (statement is not null) Analyze(context, statement, elseClause); statement = elseClause.Statement; - if (statement != null) + if (statement is not null) Analyze(context, elseClause.ElseKeyword, statement); } } @@ -465,7 +465,7 @@ private static void AnalyzeInitializer(SyntaxNodeAnalysisContext context) ExpressionSyntax first = expressions.FirstOrDefault(); - if (first == null) + if (first is null) return; if (IsExpectedTrailingTrivia(initializer.OpenBraceToken.TrailingTrivia)) @@ -476,7 +476,7 @@ private static void AnalyzeInitializer(SyntaxNodeAnalysisContext context) { TextSpan? span = GetEmptyLineSpan(leading, isEnd: false); - if (span != null) + if (span is not null) ReportDiagnostic(context, span.Value); } } @@ -489,7 +489,7 @@ private static void AnalyzeInitializer(SyntaxNodeAnalysisContext context) { TextSpan? span = GetEmptyLineSpan(leading, isEnd: true); - if (span != null) + if (span is not null) ReportDiagnostic(context, span.Value); } } @@ -584,7 +584,7 @@ private void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) TextSpan? span = GetEmptyLineSpan(node.GetLeadingTrivia(), isEnd: false); - if (span == null) + if (span is null) return; DiagnosticHelpers.ReportDiagnostic( @@ -609,7 +609,7 @@ private void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) TextSpan? span = GetEmptyLineSpan(brace.LeadingTrivia, isEnd: true); - if (span == null) + if (span is null) return; DiagnosticHelpers.ReportDiagnostic( @@ -636,7 +636,7 @@ private void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) TextSpan? span = GetEmptyLineSpan(closeBrace.LeadingTrivia, isEnd: true); - if (span == null) + if (span is null) return; DiagnosticHelpers.ReportDiagnostic( diff --git a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBracesAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBracesAnalyzer.cs index 6f8d47c42a..a11c87cc87 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBracesAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBracesAnalyzer.cs @@ -36,7 +36,7 @@ private static void AnalyzeRecordDeclaration(SyntaxNodeAnalysisContext context) var recordDeclaration = (RecordDeclarationSyntax)context.Node; if (!recordDeclaration.Members.Any() - && recordDeclaration.ParameterList != null) + && recordDeclaration.ParameterList is not null) { SyntaxToken openBrace = recordDeclaration.OpenBraceToken; diff --git a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryElseAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryElseAnalyzer.cs index b82c55d1e0..d27ddde0b6 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryElseAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryElseAnalyzer.cs @@ -61,7 +61,7 @@ public static bool IsFixable(ElseClauseSyntax elseClause) if (statement is BlockSyntax block) statement = block.Statements.LastOrDefault(); - return statement != null + return statement is not null && CSharpFacts.IsJumpStatement(statement.Kind()); } } diff --git a/src/Analyzers/CSharp/Analysis/ReturnCompletedTaskInsteadOfNullAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ReturnCompletedTaskInsteadOfNullAnalyzer.cs index ee604054f2..2234b6251d 100644 --- a/src/Analyzers/CSharp/Analysis/ReturnCompletedTaskInsteadOfNullAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ReturnCompletedTaskInsteadOfNullAnalyzer.cs @@ -50,7 +50,7 @@ private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) ArrowExpressionClauseSyntax expressionBody = methodDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { ExpressionSyntax expression = expressionBody.Expression?.WalkDownParentheses(); @@ -72,7 +72,7 @@ private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) { BlockSyntax body = methodDeclaration.Body; - if (body == null) + if (body is null) return; if (!ReturnsTaskOrTaskOfT()) @@ -98,7 +98,7 @@ private static void AnalyzeLocalFunction(SyntaxNodeAnalysisContext context) ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { ExpressionSyntax expression = expressionBody.Expression?.WalkDownParentheses(); @@ -120,7 +120,7 @@ private static void AnalyzeLocalFunction(SyntaxNodeAnalysisContext context) { BlockSyntax body = localFunction.Body; - if (body == null) + if (body is null) return; if (!ReturnsTaskOrTaskOfT()) @@ -143,7 +143,7 @@ private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { ExpressionSyntax expression = expressionBody.Expression?.WalkDownParentheses(); @@ -165,7 +165,7 @@ private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context { AccessorDeclarationSyntax getter = propertyDeclaration.Getter(); - if (getter == null) + if (getter is null) return; if (!ReturnsTaskOrTaskOfT()) @@ -188,7 +188,7 @@ private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { ExpressionSyntax expression = expressionBody.Expression?.WalkDownParentheses(); @@ -210,7 +210,7 @@ private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) { AccessorDeclarationSyntax getter = indexerDeclaration.Getter(); - if (getter == null) + if (getter is null) return; if (!ReturnsTaskOrTaskOfT()) @@ -294,7 +294,7 @@ private static void AnalyzeGetAccessor(SyntaxNodeAnalysisContext context, Access { ArrowExpressionClauseSyntax expressionBody = getter.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { ExpressionSyntax expression = expressionBody.Expression?.WalkDownParentheses(); @@ -315,7 +315,7 @@ private static void AnalyzeGetAccessor(SyntaxNodeAnalysisContext context, Access private static void AnalyzeBlock(SyntaxNodeAnalysisContext context, BlockSyntax body) { - if (body == null) + if (body is null) return; SyntaxWalker walker = SyntaxWalker.GetInstance(); @@ -333,12 +333,12 @@ private static void AnalyzeBlock(SyntaxNodeAnalysisContext context, BlockSyntax public static bool IsTaskOrTaskOfT(ITypeSymbol typeSymbol) { - if (typeSymbol == null) + if (typeSymbol is null) return false; INamedTypeSymbol namedTypeSymbol = SymbolUtility.GetPossiblyAwaitableType(typeSymbol); - if (namedTypeSymbol == null) + if (namedTypeSymbol is null) return false; return namedTypeSymbol.HasMetadataName(MetadataNames.System_Threading_Tasks_Task) @@ -382,9 +382,9 @@ public static SyntaxWalker GetInstance() { SyntaxWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { - Debug.Assert(walker.Expressions == null || walker.Expressions.Count == 0); + Debug.Assert(walker.Expressions is null || walker.Expressions.Count == 0); _cachedInstance = null; return walker; diff --git a/src/Analyzers/CSharp/Analysis/SimplifyCoalesceExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyCoalesceExpressionAnalyzer.cs index a088dadec9..23b186bf22 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyCoalesceExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyCoalesceExpressionAnalyzer.cs @@ -113,7 +113,7 @@ private static void AnalyzeCoalesceExpression(SyntaxNodeAnalysisContext context) { object value = optional.Value; - if (value != null) + if (value is not null) { return BinaryExpressionPart.Right; } @@ -160,7 +160,7 @@ private static bool IsDefaultOfReferenceOrNullableType(DefaultExpressionSyntax d { TypeSyntax type = defaultExpression.Type; - if (type != null) + if (type is not null) { if (type.IsKind(SyntaxKind.NullableType)) return true; diff --git a/src/Analyzers/CSharp/Analysis/SimplifyCodeBranchingAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyCodeBranchingAnalyzer.cs index 186217732e..95c30b3bb5 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyCodeBranchingAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyCodeBranchingAnalyzer.cs @@ -39,7 +39,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) SimplifyCodeBranchingKind? kind = GetKind(ifStatement, context.SemanticModel, context.CancellationToken); - if (kind == null) + if (kind is null) return; DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.SimplifyCodeBranching, ifStatement.IfKeyword); @@ -54,12 +54,12 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) StatementSyntax ifStatementStatement = ifStatement.Statement; - if (ifStatementStatement == null) + if (ifStatementStatement is null) return null; ElseClauseSyntax elseClause = ifStatement.Else; - if (elseClause != null) + if (elseClause is not null) { if (IsFixableIfElseInsideWhile(ifStatement, elseClause)) { @@ -103,7 +103,7 @@ private static bool IsFixableIfElseWithEmptyIf(IfStatementSyntax ifStatement, El StatementSyntax whenFalse = elseClause.Statement; - if (whenFalse == null) + if (whenFalse is null) return false; SyntaxKind kind = whenFalse.Kind(); @@ -112,7 +112,7 @@ private static bool IsFixableIfElseWithEmptyIf(IfStatementSyntax ifStatement, El { var nestedIf = (IfStatementSyntax)whenFalse; - if (nestedIf.Else != null) + if (nestedIf.Else is not null) return false; if (nestedIf.Condition?.WalkDownParentheses().IsMissing != false) @@ -120,7 +120,7 @@ private static bool IsFixableIfElseWithEmptyIf(IfStatementSyntax ifStatement, El StatementSyntax statement = nestedIf.Statement; - if (statement == null) + if (statement is null) return false; if ((statement as BlockSyntax)?.Statements.Any() == false) @@ -197,7 +197,7 @@ private static bool IsFixableIfElseWithReturnOrContinueInsideIf(IfStatementSynta // } return ifStatement.SingleNonBlockStatementOrDefault() is ReturnStatementSyntax returnStatement - && returnStatement.Expression == null; + && returnStatement.Expression is null; } case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: @@ -229,12 +229,12 @@ private static bool IsFixableIfElseWithReturnOrContinueInsideIf(IfStatementSynta { StatementSyntax ifStatementStatement = ifStatement.Statement; - if (ifStatementStatement == null) + if (ifStatementStatement is null) return false; StatementSyntax elseClauseStatement = elseClause.Statement; - if (elseClauseStatement == null) + if (elseClauseStatement is null) return false; if (elseClauseStatement.SingleNonBlockStatementOrDefault()?.Kind() != SyntaxKind.BreakStatement diff --git a/src/Analyzers/CSharp/Analysis/SimplifyLazyInitializationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyLazyInitializationAnalyzer.cs index 938b0af90c..34e9f38c6d 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyLazyInitializationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyLazyInitializationAnalyzer.cs @@ -52,7 +52,7 @@ private static void AnalyzeGetAccessorDeclaration(SyntaxNodeAnalysisContext cont private static void Analyze(SyntaxNodeAnalysisContext context, SyntaxNode node, BlockSyntax body) { - if (body == null) + if (body is null) return; if (body.ContainsDiagnostics) @@ -87,7 +87,7 @@ private static void Analyze(SyntaxNodeAnalysisContext context, SyntaxNode node, StatementSyntax statement = simpleIf.IfStatement.SingleNonBlockStatementOrDefault(); - if (statement == null) + if (statement is null) return; SimpleAssignmentStatementInfo assignmentInfo = SyntaxInfo.SimpleAssignmentStatementInfo(statement); diff --git a/src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs index 56f2f2cb97..a971603195 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs @@ -181,7 +181,7 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv IMethodSymbol methodSymbol = context.SemanticModel.GetReducedExtensionMethodInfo(invocationInfo.InvocationExpression, context.CancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithPredicate(methodSymbol)) diff --git a/src/Analyzers/CSharp/Analysis/SimplifyNestedUsingStatementAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyNestedUsingStatementAnalyzer.cs index de7e9adf3e..7ca7752cad 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyNestedUsingStatementAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyNestedUsingStatementAnalyzer.cs @@ -51,7 +51,7 @@ private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) if (!ContainsEmbeddableUsingStatement(usingStatement)) return; - for (SyntaxNode parent = usingStatement.Parent; parent != null; parent = parent.Parent) + for (SyntaxNode parent = usingStatement.Parent; parent is not null; parent = parent.Parent) { if (parent.IsKind(SyntaxKind.UsingStatement) && ContainsEmbeddableUsingStatement((UsingStatementSyntax)parent)) diff --git a/src/Analyzers/CSharp/Analysis/SimplifyNullCheckAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyNullCheckAnalyzer.cs index be1cb9646f..2cea29c2dc 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyNullCheckAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyNullCheckAnalyzer.cs @@ -88,12 +88,12 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte semanticModel, cancellationToken); - if (expression == null) + if (expression is null) return; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(nullCheck.Expression, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; if (typeSymbol.IsReferenceType) @@ -144,7 +144,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte semanticModel, cancellationToken); - if (expression != null) + if (expression is not null) { ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(nullCheck.Expression, cancellationToken); diff --git a/src/Analyzers/CSharp/Analysis/SimplifyNullableOfTAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyNullableOfTAnalyzer.cs index dcb7714e69..c6744109d7 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyNullableOfTAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyNullableOfTAnalyzer.cs @@ -108,7 +108,7 @@ private static void AnalyzeQualifiedName(SyntaxNodeAnalysisContext context) SemanticModel semanticModel, CancellationToken cancellationToken = default) { - for (node = node.Parent; node != null; node = node.Parent) + for (node = node.Parent; node is not null; node = node.Parent) { SyntaxKind kind = node.Kind(); diff --git a/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs index e416b5b760..8d12a1d60b 100644 --- a/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs @@ -247,7 +247,7 @@ private static bool IsMissing(DocumentationCommentTriviaSyntax documentationComm string value = element.GetAttributeValue("name"); - if (value != null + if (value is not null && string.Equals(parameter.Identifier.ValueText, value, StringComparison.Ordinal)) { return false; @@ -272,7 +272,7 @@ private static bool IsMissing(DocumentationCommentTriviaSyntax documentationComm string value = element.GetAttributeValue("name"); - if (value != null + if (value is not null && string.Equals(typeParameter.Identifier.ValueText, value, StringComparison.Ordinal)) { return false; @@ -313,7 +313,7 @@ private static bool IsMissing(DocumentationCommentTriviaSyntax documentationComm ? ((XmlElementSyntax)element).GetAttributeValue("name") : ((XmlEmptyElementSyntax)element).GetAttributeValue("name"); - if (name == null) + if (name is null) { firstIndex = -1; continue; diff --git a/src/Analyzers/CSharp/Analysis/StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer.cs b/src/Analyzers/CSharp/Analysis/StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer.cs index 377fb3648d..72be63cdae 100644 --- a/src/Analyzers/CSharp/Analysis/StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer.cs @@ -7,213 +7,214 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.StaticMemberInGenericTypeShouldUseTypeParameter); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.StaticMemberInGenericTypeShouldUseTypeParameter); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterSymbolAction(f => AnalyzeNamedType(f), SymbolKind.NamedType); - } - - private static void AnalyzeNamedType(SymbolAnalysisContext context) - { - var namedType = (INamedTypeSymbol)context.Symbol; - if (!namedType.TypeKind.Is(TypeKind.Class, TypeKind.Struct)) - return; + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - if (namedType.Arity == 0) - return; + context.RegisterSymbolAction(f => AnalyzeNamedType(f), SymbolKind.NamedType); + } - if (namedType.IsStatic) - return; + private static void AnalyzeNamedType(SymbolAnalysisContext context) + { + var namedType = (INamedTypeSymbol)context.Symbol; - if (namedType.IsImplicitClass) - return; + if (!namedType.TypeKind.Is(TypeKind.Class, TypeKind.Struct)) + return; - if (namedType.IsImplicitlyDeclared) - return; + if (namedType.Arity == 0) + return; - var typeParameters = default(ImmutableArray); + if (namedType.IsStatic) + return; - foreach (ISymbol member in namedType.GetMembers()) - { - if (member.IsImplicitlyDeclared) - continue; + if (namedType.IsImplicitClass) + return; - if (!member.IsStatic) - continue; + if (namedType.IsImplicitlyDeclared) + return; - if (!member.DeclaredAccessibility.Is(Accessibility.Public, Accessibility.Internal, Accessibility.ProtectedOrInternal)) - continue; + var typeParameters = default(ImmutableArray); - switch (member.Kind) + foreach (ISymbol member in namedType.GetMembers()) { - case SymbolKind.Event: - { - var eventSymbol = (IEventSymbol)member; + if (member.IsImplicitlyDeclared) + continue; - if (typeParameters.IsDefault) - typeParameters = namedType.TypeParameters; + if (!member.IsStatic) + continue; - if (!ContainsAnyTypeParameter(typeParameters, eventSymbol.Type)) - ReportDiagnostic(context, eventSymbol); + if (!member.DeclaredAccessibility.Is(Accessibility.Public, Accessibility.Internal, Accessibility.ProtectedOrInternal)) + continue; - break; - } - case SymbolKind.Field: - { - var fieldSymbol = (IFieldSymbol)member; - - if (typeParameters.IsDefault) - typeParameters = namedType.TypeParameters; + switch (member.Kind) + { + case SymbolKind.Event: + { + var eventSymbol = (IEventSymbol)member; - if (!ContainsAnyTypeParameter(typeParameters, fieldSymbol.Type)) - ReportDiagnostic(context, fieldSymbol); + if (typeParameters.IsDefault) + typeParameters = namedType.TypeParameters; - break; - } - case SymbolKind.Method: - { - var methodsymbol = (IMethodSymbol)member; + if (!ContainsAnyTypeParameter(typeParameters, eventSymbol.Type)) + ReportDiagnostic(context, eventSymbol); - if (methodsymbol.MethodKind == MethodKind.Ordinary) + break; + } + case SymbolKind.Field: { + var fieldSymbol = (IFieldSymbol)member; + if (typeParameters.IsDefault) typeParameters = namedType.TypeParameters; - if (!ContainsAnyTypeParameter(typeParameters, methodsymbol.ReturnType) - && !ContainsAnyTypeParameter(typeParameters, methodsymbol.Parameters)) + if (!ContainsAnyTypeParameter(typeParameters, fieldSymbol.Type)) + ReportDiagnostic(context, fieldSymbol); + + break; + } + case SymbolKind.Method: + { + var methodsymbol = (IMethodSymbol)member; + + if (methodsymbol.MethodKind == MethodKind.Ordinary) { - ReportDiagnostic(context, methodsymbol); + if (typeParameters.IsDefault) + typeParameters = namedType.TypeParameters; + + if (!ContainsAnyTypeParameter(typeParameters, methodsymbol.ReturnType) + && !ContainsAnyTypeParameter(typeParameters, methodsymbol.Parameters)) + { + ReportDiagnostic(context, methodsymbol); + } } + + break; } + case SymbolKind.Property: + { + var propertySymbol = (IPropertySymbol)member; - break; - } - case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)member; + if (!propertySymbol.IsIndexer) + { + if (typeParameters.IsDefault) + typeParameters = namedType.TypeParameters; - if (!propertySymbol.IsIndexer) - { - if (typeParameters.IsDefault) - typeParameters = namedType.TypeParameters; + if (!ContainsAnyTypeParameter(typeParameters, propertySymbol.Type)) + ReportDiagnostic(context, propertySymbol); + } - if (!ContainsAnyTypeParameter(typeParameters, propertySymbol.Type)) - ReportDiagnostic(context, propertySymbol); + break; } - - break; - } + } } } - } - private static bool ContainsAnyTypeParameter(ImmutableArray typeParameters, ImmutableArray parameters) - { - foreach (IParameterSymbol parameter in parameters) + private static bool ContainsAnyTypeParameter(ImmutableArray typeParameters, ImmutableArray parameters) { - if (ContainsAnyTypeParameter(typeParameters, parameter.Type)) - return true; - } + foreach (IParameterSymbol parameter in parameters) + { + if (ContainsAnyTypeParameter(typeParameters, parameter.Type)) + return true; + } - return false; - } + return false; + } - private static bool ContainsAnyTypeParameter( - ImmutableArray typeParameters, - ITypeSymbol typeSymbol) - { - switch (typeSymbol.Kind) + private static bool ContainsAnyTypeParameter( + ImmutableArray typeParameters, + ITypeSymbol typeSymbol) { - case SymbolKind.TypeParameter: - { - foreach (ITypeParameterSymbol typeParameter in typeParameters) + switch (typeSymbol.Kind) + { + case SymbolKind.TypeParameter: { - if (SymbolEqualityComparer.Default.Equals(typeParameter, typeSymbol)) - return true; - } + foreach (ITypeParameterSymbol typeParameter in typeParameters) + { + if (SymbolEqualityComparer.Default.Equals(typeParameter, typeSymbol)) + return true; + } - return false; - } - case SymbolKind.ArrayType: - { - return ContainsAnyTypeParameter(typeParameters, ((IArrayTypeSymbol)typeSymbol).ElementType); - } - case SymbolKind.NamedType: - { - return ContainsAnyTypeParameter(typeParameters, ((INamedTypeSymbol)typeSymbol).TypeArguments); - } - } + return false; + } + case SymbolKind.ArrayType: + { + return ContainsAnyTypeParameter(typeParameters, ((IArrayTypeSymbol)typeSymbol).ElementType); + } + case SymbolKind.NamedType: + { + return ContainsAnyTypeParameter(typeParameters, ((INamedTypeSymbol)typeSymbol).TypeArguments); + } + } - Debug.Assert(typeSymbol.Kind == SymbolKind.ErrorType, typeSymbol.Kind.ToString()); + Debug.Assert(typeSymbol.Kind == SymbolKind.ErrorType, typeSymbol.Kind.ToString()); - return true; - } + return true; + } - private static bool ContainsAnyTypeParameter( - ImmutableArray typeParameters, - ImmutableArray typeArguments) - { - foreach (ITypeSymbol typeArgument in typeArguments) + private static bool ContainsAnyTypeParameter( + ImmutableArray typeParameters, + ImmutableArray typeArguments) { - SymbolKind kind = typeArgument.Kind; - - if (kind == SymbolKind.TypeParameter) + foreach (ITypeSymbol typeArgument in typeArguments) { - foreach (ITypeParameterSymbol typeParameter in typeParameters) + SymbolKind kind = typeArgument.Kind; + + if (kind == SymbolKind.TypeParameter) { - if (SymbolEqualityComparer.Default.Equals(typeParameter, typeArgument)) + foreach (ITypeParameterSymbol typeParameter in typeParameters) + { + if (SymbolEqualityComparer.Default.Equals(typeParameter, typeArgument)) + return true; + } + } + else if (kind == SymbolKind.NamedType) + { + if (ContainsAnyTypeParameter(typeParameters, ((INamedTypeSymbol)typeArgument).TypeArguments)) return true; } } - else if (kind == SymbolKind.NamedType) - { - if (ContainsAnyTypeParameter(typeParameters, ((INamedTypeSymbol)typeArgument).TypeArguments)) - return true; - } - } - return false; - } + return false; + } - private static void ReportDiagnostic(SymbolAnalysisContext context, ISymbol member) - { - SyntaxNode node = member.GetSyntaxOrDefault(context.CancellationToken); + private static void ReportDiagnostic(SymbolAnalysisContext context, ISymbol member) + { + SyntaxNode node = member.GetSyntaxOrDefault(context.CancellationToken); - Debug.Assert(node != null, member.ToString()); + Debug.Assert(node is not null, member.ToString()); - if (node == null) - return; + if (node is null) + return; - SyntaxToken identifier = CSharpUtility.GetIdentifier(node); + SyntaxToken identifier = CSharpUtility.GetIdentifier(node); - SyntaxDebug.Assert(!identifier.IsKind(SyntaxKind.None), node); + SyntaxDebug.Assert(!identifier.IsKind(SyntaxKind.None), node); - if (identifier.IsKind(SyntaxKind.None)) - return; + if (identifier.IsKind(SyntaxKind.None)) + return; - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.StaticMemberInGenericTypeShouldUseTypeParameter, - identifier); + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.StaticMemberInGenericTypeShouldUseTypeParameter, + identifier); + } } } diff --git a/src/Analyzers/CSharp/Analysis/ThrowingOfNewNotImplementedExceptionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ThrowingOfNewNotImplementedExceptionAnalyzer.cs index 90d21beb98..23112d7866 100644 --- a/src/Analyzers/CSharp/Analysis/ThrowingOfNewNotImplementedExceptionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ThrowingOfNewNotImplementedExceptionAnalyzer.cs @@ -7,72 +7,73 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class ThrowingOfNewNotImplementedExceptionAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class ThrowingOfNewNotImplementedExceptionAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.ThrowingOfNewNotImplementedException); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.ThrowingOfNewNotImplementedException); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - INamedTypeSymbol exceptionSymbol = startContext.Compilation.GetTypeByMetadataName("System.NotImplementedException"); + base.Initialize(context); - if (exceptionSymbol == null) - return; + context.RegisterCompilationStartAction(startContext => + { + INamedTypeSymbol exceptionSymbol = startContext.Compilation.GetTypeByMetadataName("System.NotImplementedException"); - startContext.RegisterSyntaxNodeAction(f => AnalyzeThrowStatement(f, exceptionSymbol), SyntaxKind.ThrowStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeThrowExpression(f, exceptionSymbol), SyntaxKind.ThrowExpression); - }); - } + if (exceptionSymbol is null) + return; - private static void AnalyzeThrowStatement(SyntaxNodeAnalysisContext context, INamedTypeSymbol exceptionSymbol) - { - var throwStatement = (ThrowStatementSyntax)context.Node; + startContext.RegisterSyntaxNodeAction(f => AnalyzeThrowStatement(f, exceptionSymbol), SyntaxKind.ThrowStatement); + startContext.RegisterSyntaxNodeAction(f => AnalyzeThrowExpression(f, exceptionSymbol), SyntaxKind.ThrowExpression); + }); + } - Analyze(context, throwStatement.Expression, exceptionSymbol); - } + private static void AnalyzeThrowStatement(SyntaxNodeAnalysisContext context, INamedTypeSymbol exceptionSymbol) + { + var throwStatement = (ThrowStatementSyntax)context.Node; - private static void AnalyzeThrowExpression(SyntaxNodeAnalysisContext context, INamedTypeSymbol exceptionSymbol) - { - var throwExpression = (ThrowExpressionSyntax)context.Node; + Analyze(context, throwStatement.Expression, exceptionSymbol); + } - Analyze(context, throwExpression.Expression, exceptionSymbol); - } + private static void AnalyzeThrowExpression(SyntaxNodeAnalysisContext context, INamedTypeSymbol exceptionSymbol) + { + var throwExpression = (ThrowExpressionSyntax)context.Node; - private static void Analyze(SyntaxNodeAnalysisContext context, ExpressionSyntax expression, INamedTypeSymbol exceptionSymbol) - { - if (expression?.Kind() != SyntaxKind.ObjectCreationExpression) - return; + Analyze(context, throwExpression.Expression, exceptionSymbol); + } - var objectCreationExpression = (ObjectCreationExpressionSyntax)expression; + private static void Analyze(SyntaxNodeAnalysisContext context, ExpressionSyntax expression, INamedTypeSymbol exceptionSymbol) + { + if (expression?.Kind() != SyntaxKind.ObjectCreationExpression) + return; + + var objectCreationExpression = (ObjectCreationExpressionSyntax)expression; - ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(objectCreationExpression, context.CancellationToken); + ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(objectCreationExpression, context.CancellationToken); - if (typeSymbol == null) - return; + if (typeSymbol is null) + return; - if (!SymbolEqualityComparer.Default.Equals(typeSymbol, exceptionSymbol)) - return; + if (!SymbolEqualityComparer.Default.Equals(typeSymbol, exceptionSymbol)) + return; - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.ThrowingOfNewNotImplementedException, - expression); + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.ThrowingOfNewNotImplementedException, + expression); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnconstrainedTypeParameterCheckedForNullAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnconstrainedTypeParameterCheckedForNullAnalyzer.cs index e8ab53b8e1..a5dfb2d68a 100644 --- a/src/Analyzers/CSharp/Analysis/UnconstrainedTypeParameterCheckedForNullAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnconstrainedTypeParameterCheckedForNullAnalyzer.cs @@ -11,143 +11,144 @@ using Roslynator.CSharp; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnconstrainedTypeParameterCheckedForNullAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnconstrainedTypeParameterCheckedForNullAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnconstrainedTypeParameterCheckedForNull); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnconstrainedTypeParameterCheckedForNull); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterSyntaxNodeAction(f => AnalyzeEqualsExpression(f), SyntaxKind.EqualsExpression); - context.RegisterSyntaxNodeAction(f => AnalyzeNotEqualsExpression(f), SyntaxKind.NotEqualsExpression); - } + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - private static void AnalyzeEqualsExpression(SyntaxNodeAnalysisContext context) - { - if (context.Node.ContainsDiagnostics) - return; + context.RegisterSyntaxNodeAction(f => AnalyzeEqualsExpression(f), SyntaxKind.EqualsExpression); + context.RegisterSyntaxNodeAction(f => AnalyzeNotEqualsExpression(f), SyntaxKind.NotEqualsExpression); + } - Analyze(context, (BinaryExpressionSyntax)context.Node, NullCheckStyles.EqualsToNull); - } + private static void AnalyzeEqualsExpression(SyntaxNodeAnalysisContext context) + { + if (context.Node.ContainsDiagnostics) + return; - private static void AnalyzeNotEqualsExpression(SyntaxNodeAnalysisContext context) - { - if (context.Node.ContainsDiagnostics) - return; + Analyze(context, (BinaryExpressionSyntax)context.Node, NullCheckStyles.EqualsToNull); + } - Analyze(context, (BinaryExpressionSyntax)context.Node, NullCheckStyles.NotEqualsToNull); - } + private static void AnalyzeNotEqualsExpression(SyntaxNodeAnalysisContext context) + { + if (context.Node.ContainsDiagnostics) + return; - private static void Analyze(SyntaxNodeAnalysisContext context, BinaryExpressionSyntax binaryExpression, NullCheckStyles allowedStyles) - { - NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(binaryExpression, allowedStyles: allowedStyles); + Analyze(context, (BinaryExpressionSyntax)context.Node, NullCheckStyles.NotEqualsToNull); + } - if (nullCheck.Success - && IsUnconstrainedTypeParameter(context.SemanticModel.GetTypeSymbol(nullCheck.Expression, context.CancellationToken)) - && !binaryExpression.SpanContainsDirectives()) + private static void Analyze(SyntaxNodeAnalysisContext context, BinaryExpressionSyntax binaryExpression, NullCheckStyles allowedStyles) { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnconstrainedTypeParameterCheckedForNull, binaryExpression); - } - } + NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(binaryExpression, allowedStyles: allowedStyles); - private static bool IsUnconstrainedTypeParameter(ITypeSymbol typeSymbol) - { - return typeSymbol?.Kind == SymbolKind.TypeParameter - && VerifyConstraint((ITypeParameterSymbol)typeSymbol, allowReference: false, allowValueType: false, allowConstructor: true); - } + if (nullCheck.Success + && IsUnconstrainedTypeParameter(context.SemanticModel.GetTypeSymbol(nullCheck.Expression, context.CancellationToken)) + && !binaryExpression.SpanContainsDirectives()) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnconstrainedTypeParameterCheckedForNull, binaryExpression); + } + } - private static bool VerifyConstraint( - ITypeParameterSymbol typeParameterSymbol, - bool allowReference, - bool allowValueType, - bool allowConstructor) - { - if (typeParameterSymbol == null) - throw new ArgumentNullException(nameof(typeParameterSymbol)); + private static bool IsUnconstrainedTypeParameter(ITypeSymbol typeSymbol) + { + return typeSymbol?.Kind == SymbolKind.TypeParameter + && VerifyConstraint((ITypeParameterSymbol)typeSymbol, allowReference: false, allowValueType: false, allowConstructor: true); + } - if (!CheckConstraint(typeParameterSymbol, allowReference, allowValueType, allowConstructor)) - return false; + private static bool VerifyConstraint( + ITypeParameterSymbol typeParameterSymbol, + bool allowReference, + bool allowValueType, + bool allowConstructor) + { + if (typeParameterSymbol is null) + throw new ArgumentNullException(nameof(typeParameterSymbol)); - return VerifyConstraint(typeParameterSymbol.ConstraintTypes, allowReference, allowValueType, allowConstructor); - } + if (!CheckConstraint(typeParameterSymbol, allowReference, allowValueType, allowConstructor)) + return false; - private static bool VerifyConstraint(ImmutableArray constraintTypes, bool allowReference, bool allowValueType, bool allowConstructor) - { - if (!constraintTypes.Any()) - return true; + return VerifyConstraint(typeParameterSymbol.ConstraintTypes, allowReference, allowValueType, allowConstructor); + } - foreach (ITypeSymbol type in constraintTypes) + private static bool VerifyConstraint(ImmutableArray constraintTypes, bool allowReference, bool allowValueType, bool allowConstructor) { - switch (type.TypeKind) - { - case TypeKind.Class: - { - if (!allowReference) - return false; + if (!constraintTypes.Any()) + return true; - break; - } - case TypeKind.Struct: - { - if (allowValueType) - return false; - - break; - } - case TypeKind.Interface: - { - break; - } - case TypeKind.TypeParameter: - { - var typeParameterSymbol = (ITypeParameterSymbol)type; - - if (!CheckConstraint(typeParameterSymbol, allowReference, allowValueType, allowConstructor)) + foreach (ITypeSymbol type in constraintTypes) + { + switch (type.TypeKind) + { + case TypeKind.Class: + { + if (!allowReference) + return false; + + break; + } + case TypeKind.Struct: + { + if (allowValueType) + return false; + + break; + } + case TypeKind.Interface: + { + break; + } + case TypeKind.TypeParameter: + { + var typeParameterSymbol = (ITypeParameterSymbol)type; + + if (!CheckConstraint(typeParameterSymbol, allowReference, allowValueType, allowConstructor)) + return false; + + if (!VerifyConstraint(typeParameterSymbol.ConstraintTypes, allowReference, allowValueType, allowConstructor)) + return false; + + break; + } + case TypeKind.Error: + { return false; - - if (!VerifyConstraint(typeParameterSymbol.ConstraintTypes, allowReference, allowValueType, allowConstructor)) + } + default: + { + Debug.Fail(type.TypeKind.ToString()); return false; - - break; - } - case TypeKind.Error: - { - return false; - } - default: - { - Debug.Fail(type.TypeKind.ToString()); - return false; - } + } + } } - } - return true; - } + return true; + } - private static bool CheckConstraint( - ITypeParameterSymbol typeParameterSymbol, - bool allowReference, - bool allowValueType, - bool allowConstructor) - { - return (allowReference || !typeParameterSymbol.HasReferenceTypeConstraint) - && (allowValueType || !typeParameterSymbol.HasValueTypeConstraint) - && (allowConstructor || !typeParameterSymbol.HasConstructorConstraint); + private static bool CheckConstraint( + ITypeParameterSymbol typeParameterSymbol, + bool allowReference, + bool allowValueType, + bool allowConstructor) + { + return (allowReference || !typeParameterSymbol.HasReferenceTypeConstraint) + && (allowValueType || !typeParameterSymbol.HasValueTypeConstraint) + && (allowConstructor || !typeParameterSymbol.HasConstructorConstraint); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryAssignmentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryAssignmentAnalyzer.cs index 89201ec82d..068f782ec5 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryAssignmentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryAssignmentAnalyzer.cs @@ -8,207 +8,208 @@ using Microsoft.CodeAnalysis.Diagnostics; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnnecessaryAssignmentAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnnecessaryAssignmentAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryAssignment); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryAssignment); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - context.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement); - context.RegisterSyntaxNodeAction(f => AnalyzeSwitchStatement(f), SyntaxKind.SwitchStatement); - } + context.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement); + context.RegisterSyntaxNodeAction(f => AnalyzeSwitchStatement(f), SyntaxKind.SwitchStatement); + } - private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) - { - var ifStatement = (IfStatementSyntax)context.Node; + private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) + { + var ifStatement = (IfStatementSyntax)context.Node; - if (ifStatement.IsSimpleIf()) - return; + if (ifStatement.IsSimpleIf()) + return; - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement); + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement); - if (!statementsInfo.Success) - return; + if (!statementsInfo.Success) + return; - ReturnStatementSyntax returnStatement = FindReturnStatementBelow(statementsInfo.Statements, ifStatement); + ReturnStatementSyntax returnStatement = FindReturnStatementBelow(statementsInfo.Statements, ifStatement); - ExpressionSyntax expression = returnStatement?.Expression; + ExpressionSyntax expression = returnStatement?.Expression; - if (expression == null) - return; + if (expression is null) + return; - if (ifStatement.SpanOrTrailingTriviaContainsDirectives()) - return; + if (ifStatement.SpanOrTrailingTriviaContainsDirectives()) + return; - if (returnStatement.SpanOrLeadingTriviaContainsDirectives()) - return; + if (returnStatement.SpanOrLeadingTriviaContainsDirectives()) + return; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); + ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); - if (symbol == null) - return; + if (symbol is null) + return; - if (!IsLocalDeclaredInScopeOrNonRefOrOutParameterOfEnclosingSymbol(symbol, statementsInfo.Parent, semanticModel, cancellationToken)) - return; + if (!IsLocalDeclaredInScopeOrNonRefOrOutParameterOfEnclosingSymbol(symbol, statementsInfo.Parent, semanticModel, cancellationToken)) + return; - foreach (IfStatementOrElseClause ifOrElse in ifStatement.AsCascade()) - { - StatementSyntax statement = ifOrElse.Statement; + foreach (IfStatementOrElseClause ifOrElse in ifStatement.AsCascade()) + { + StatementSyntax statement = ifOrElse.Statement; - if (statement.IsKind(SyntaxKind.Block)) - statement = ((BlockSyntax)statement).Statements.LastOrDefault(); + if (statement.IsKind(SyntaxKind.Block)) + statement = ((BlockSyntax)statement).Statements.LastOrDefault(); - if (!statement.IsKind(SyntaxKind.ThrowStatement) - && !IsSymbolAssignedInStatement(symbol, statement, semanticModel, cancellationToken)) - { - return; + if (!statement.IsKind(SyntaxKind.ThrowStatement) + && !IsSymbolAssignedInStatement(symbol, statement, semanticModel, cancellationToken)) + { + return; + } } + + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryAssignment, ifStatement); } - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryAssignment, ifStatement); - } + private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) + { + var switchStatement = (SwitchStatementSyntax)context.Node; - private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) - { - var switchStatement = (SwitchStatementSyntax)context.Node; + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(switchStatement); - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(switchStatement); + if (!statementsInfo.Success) + return; - if (!statementsInfo.Success) - return; + ReturnStatementSyntax returnStatement = FindReturnStatementBelow(statementsInfo.Statements, switchStatement); - ReturnStatementSyntax returnStatement = FindReturnStatementBelow(statementsInfo.Statements, switchStatement); + ExpressionSyntax expression = returnStatement?.Expression; - ExpressionSyntax expression = returnStatement?.Expression; + if (expression is null) + return; - if (expression == null) - return; + if (switchStatement.SpanOrTrailingTriviaContainsDirectives()) + return; - if (switchStatement.SpanOrTrailingTriviaContainsDirectives()) - return; + if (returnStatement.SpanOrLeadingTriviaContainsDirectives()) + return; - if (returnStatement.SpanOrLeadingTriviaContainsDirectives()) - return; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); - ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); + if (symbol is null) + return; - if (symbol == null) - return; + if (!IsLocalDeclaredInScopeOrNonRefOrOutParameterOfEnclosingSymbol(symbol, statementsInfo.Parent, semanticModel, cancellationToken)) + return; - if (!IsLocalDeclaredInScopeOrNonRefOrOutParameterOfEnclosingSymbol(symbol, statementsInfo.Parent, semanticModel, cancellationToken)) - return; + foreach (SwitchSectionSyntax section in switchStatement.Sections) + { + SyntaxList statements = section.GetStatements(); - foreach (SwitchSectionSyntax section in switchStatement.Sections) - { - SyntaxList statements = section.GetStatements(); + if (!statements.Any()) + return; - if (!statements.Any()) - return; + switch (statements.Last().Kind()) + { + case SyntaxKind.ThrowStatement: + { + continue; + } + case SyntaxKind.BreakStatement: + { + if (statements.Count == 1 + || !IsSymbolAssignedInStatement(symbol, statements.LastButOne(), semanticModel, cancellationToken)) + { + return; + } - switch (statements.Last().Kind()) - { - case SyntaxKind.ThrowStatement: - { - continue; - } - case SyntaxKind.BreakStatement: - { - if (statements.Count == 1 - || !IsSymbolAssignedInStatement(symbol, statements.LastButOne(), semanticModel, cancellationToken)) + break; + } + default: { return; } - - break; - } - default: - { - return; - } + } } + + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryAssignment, switchStatement); } - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryAssignment, switchStatement); - } + internal static ReturnStatementSyntax FindReturnStatementBelow(SyntaxList statements, StatementSyntax statement) + { + int index = statements.IndexOf(statement); - internal static ReturnStatementSyntax FindReturnStatementBelow(SyntaxList statements, StatementSyntax statement) - { - int index = statements.IndexOf(statement); + if (index < statements.Count - 1) + { + StatementSyntax nextStatement = statements[index + 1]; - if (index < statements.Count - 1) - { - StatementSyntax nextStatement = statements[index + 1]; + if (nextStatement.IsKind(SyntaxKind.ReturnStatement)) + return (ReturnStatementSyntax)nextStatement; + } - if (nextStatement.IsKind(SyntaxKind.ReturnStatement)) - return (ReturnStatementSyntax)nextStatement; + return null; } - return null; - } - - private static bool IsLocalDeclaredInScopeOrNonRefOrOutParameterOfEnclosingSymbol(ISymbol symbol, SyntaxNode containingNode, SemanticModel semanticModel, CancellationToken cancellationToken) - { - switch (symbol.Kind) + private static bool IsLocalDeclaredInScopeOrNonRefOrOutParameterOfEnclosingSymbol(ISymbol symbol, SyntaxNode containingNode, SemanticModel semanticModel, CancellationToken cancellationToken) { - case SymbolKind.Local: - { - var localSymbol = (ILocalSymbol)symbol; - - var localDeclarationStatement = localSymbol.GetSyntax(cancellationToken).Parent.Parent as LocalDeclarationStatementSyntax; + switch (symbol.Kind) + { + case SymbolKind.Local: + { + var localSymbol = (ILocalSymbol)symbol; - return localDeclarationStatement?.Parent == containingNode; - } - case SymbolKind.Parameter: - { - var parameterSymbol = (IParameterSymbol)symbol; + var localDeclarationStatement = localSymbol.GetSyntax(cancellationToken).Parent.Parent as LocalDeclarationStatementSyntax; - if (parameterSymbol.RefKind == RefKind.None) + return localDeclarationStatement?.Parent == containingNode; + } + case SymbolKind.Parameter: { - ISymbol enclosingSymbol = semanticModel.GetEnclosingSymbol(containingNode.SpanStart, cancellationToken); + var parameterSymbol = (IParameterSymbol)symbol; - if (enclosingSymbol != null) + if (parameterSymbol.RefKind == RefKind.None) { - ImmutableArray parameters = enclosingSymbol.ParametersOrDefault(); + ISymbol enclosingSymbol = semanticModel.GetEnclosingSymbol(containingNode.SpanStart, cancellationToken); - return !parameters.IsDefault - && parameters.Contains(parameterSymbol); + if (enclosingSymbol is not null) + { + ImmutableArray parameters = enclosingSymbol.ParametersOrDefault(); + + return !parameters.IsDefault + && parameters.Contains(parameterSymbol); + } } + + break; } + } - break; - } + return false; } - return false; - } - - private static bool IsSymbolAssignedInStatement(ISymbol symbol, StatementSyntax statement, SemanticModel semanticModel, CancellationToken cancellationToken) - { - SimpleAssignmentStatementInfo assignmentInfo = SyntaxInfo.SimpleAssignmentStatementInfo(statement); + private static bool IsSymbolAssignedInStatement(ISymbol symbol, StatementSyntax statement, SemanticModel semanticModel, CancellationToken cancellationToken) + { + SimpleAssignmentStatementInfo assignmentInfo = SyntaxInfo.SimpleAssignmentStatementInfo(statement); - return assignmentInfo.Success - && SymbolEqualityComparer.Default.Equals(semanticModel.GetSymbol(assignmentInfo.Left, cancellationToken), symbol); + return assignmentInfo.Success + && SymbolEqualityComparer.Default.Equals(semanticModel.GetSymbol(assignmentInfo.Left, cancellationToken), symbol); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryExplicitUseOfEnumeratorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryExplicitUseOfEnumeratorAnalyzer.cs index 4bf6b15bc4..833071d6c0 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryExplicitUseOfEnumeratorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryExplicitUseOfEnumeratorAnalyzer.cs @@ -8,90 +8,91 @@ using Microsoft.CodeAnalysis.Diagnostics; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnnecessaryExplicitUseOfEnumeratorAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnnecessaryExplicitUseOfEnumeratorAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryExplicitUseOfEnumerator); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryExplicitUseOfEnumerator); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - context.RegisterSyntaxNodeAction(f => AnalyzeUsingStatement(f), SyntaxKind.UsingStatement); - } + context.RegisterSyntaxNodeAction(f => AnalyzeUsingStatement(f), SyntaxKind.UsingStatement); + } - private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) - { - var usingStatement = (UsingStatementSyntax)context.Node; + private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) + { + var usingStatement = (UsingStatementSyntax)context.Node; - VariableDeclaratorSyntax declarator = usingStatement.Declaration?.Variables.SingleOrDefault(shouldThrow: false); + VariableDeclaratorSyntax declarator = usingStatement.Declaration?.Variables.SingleOrDefault(shouldThrow: false); - if (declarator == null) - return; + if (declarator is null) + return; - if (usingStatement.Statement?.SingleNonBlockStatementOrDefault() is not WhileStatementSyntax whileStatement) - return; + if (usingStatement.Statement?.SingleNonBlockStatementOrDefault() is not WhileStatementSyntax whileStatement) + return; - SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(whileStatement.Condition); + SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(whileStatement.Condition); - if (!invocationInfo.Success) - return; + if (!invocationInfo.Success) + return; - if (invocationInfo.Arguments.Any()) - return; + if (invocationInfo.Arguments.Any()) + return; - if (!string.Equals(invocationInfo.NameText, WellKnownMemberNames.MoveNextMethodName, StringComparison.Ordinal)) - return; + if (!string.Equals(invocationInfo.NameText, WellKnownMemberNames.MoveNextMethodName, StringComparison.Ordinal)) + return; - if (!string.Equals((invocationInfo.Expression as IdentifierNameSyntax)?.Identifier.ValueText, declarator.Identifier.ValueText, StringComparison.Ordinal)) - return; + if (!string.Equals((invocationInfo.Expression as IdentifierNameSyntax)?.Identifier.ValueText, declarator.Identifier.ValueText, StringComparison.Ordinal)) + return; - SimpleMemberInvocationExpressionInfo invocationInfo2 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(declarator.Initializer.Value); + SimpleMemberInvocationExpressionInfo invocationInfo2 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(declarator.Initializer.Value); - if (!invocationInfo2.Success) - return; + if (!invocationInfo2.Success) + return; - if (invocationInfo2.Arguments.Any()) - return; + if (invocationInfo2.Arguments.Any()) + return; - if (!string.Equals(invocationInfo2.NameText, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.Ordinal)) - return; + if (!string.Equals(invocationInfo2.NameText, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.Ordinal)) + return; - bool? isFixable; - UnnecessaryUsageOfEnumeratorWalker walker = null; + bool? isFixable; + UnnecessaryUsageOfEnumeratorWalker walker = null; - try - { - walker = UnnecessaryUsageOfEnumeratorWalker.GetInstance(); + try + { + walker = UnnecessaryUsageOfEnumeratorWalker.GetInstance(); - walker.SetValues(declarator, context.SemanticModel, context.CancellationToken); + walker.SetValues(declarator, context.SemanticModel, context.CancellationToken); - walker.Visit(whileStatement.Statement); + walker.Visit(whileStatement.Statement); - isFixable = walker.IsFixable; - } - finally - { - if (walker != null) - UnnecessaryUsageOfEnumeratorWalker.Free(walker); - } + isFixable = walker.IsFixable; + } + finally + { + if (walker is not null) + UnnecessaryUsageOfEnumeratorWalker.Free(walker); + } - if (isFixable == true) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryExplicitUseOfEnumerator, usingStatement.UsingKeyword); + if (isFixable == true) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryExplicitUseOfEnumerator, usingStatement.UsingKeyword); + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolatedStringAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolatedStringAnalyzer.cs index 54000b8a7c..4eafbc208d 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolatedStringAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolatedStringAnalyzer.cs @@ -8,122 +8,123 @@ using Microsoft.CodeAnalysis.Text; using static Roslynator.DiagnosticHelpers; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnnecessaryInterpolatedStringAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnnecessaryInterpolatedStringAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize( - ref _supportedDiagnostics, - DiagnosticRules.UnnecessaryInterpolatedString, - DiagnosticRules.UnnecessaryInterpolatedStringFadeOut); + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize( + ref _supportedDiagnostics, + DiagnosticRules.UnnecessaryInterpolatedString, + DiagnosticRules.UnnecessaryInterpolatedStringFadeOut); + } + + return _supportedDiagnostics; } + } - return _supportedDiagnostics; + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticRules.UnnecessaryInterpolatedString.IsEffective(c)) + AnalyzeInterpolatedStringExpression(c); + }, + SyntaxKind.InterpolatedStringExpression); } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); + private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContext context) + { + SyntaxNode node = context.Node; - context.RegisterSyntaxNodeAction( - c => - { - if (DiagnosticRules.UnnecessaryInterpolatedString.IsEffective(c)) - AnalyzeInterpolatedStringExpression(c); - }, - SyntaxKind.InterpolatedStringExpression); - } + if (node.ContainsDiagnostics) + return; - private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContext context) - { - SyntaxNode node = context.Node; + if (node.ContainsDirectives) + return; - if (node.ContainsDiagnostics) - return; + var interpolatedString = (InterpolatedStringExpressionSyntax)node; - if (node.ContainsDirectives) - return; + SyntaxList contents = interpolatedString.Contents; - var interpolatedString = (InterpolatedStringExpressionSyntax)node; + if (ConvertInterpolatedStringToStringLiteralAnalysis.IsFixable(contents)) + { + if (IsFormattableString(context)) + return; - SyntaxList contents = interpolatedString.Contents; + ReportDiagnostic( + context, + DiagnosticRules.UnnecessaryInterpolatedString, + Location.Create(interpolatedString.SyntaxTree, GetDollarSpan(interpolatedString))); + } + else + { + if (contents.SingleOrDefault(shouldThrow: false) is not InterpolationSyntax interpolation) + return; - if (ConvertInterpolatedStringToStringLiteralAnalysis.IsFixable(contents)) - { - if (IsFormattableString(context)) - return; + if (interpolation.AlignmentClause is not null) + return; - ReportDiagnostic( - context, - DiagnosticRules.UnnecessaryInterpolatedString, - Location.Create(interpolatedString.SyntaxTree, GetDollarSpan(interpolatedString))); - } - else - { - if (contents.SingleOrDefault(shouldThrow: false) is not InterpolationSyntax interpolation) - return; + if (interpolation.FormatClause is not null) + return; - if (interpolation.AlignmentClause != null) - return; - - if (interpolation.FormatClause != null) - return; + ExpressionSyntax expression = interpolation.Expression?.WalkDownParentheses(); - ExpressionSyntax expression = interpolation.Expression?.WalkDownParentheses(); + if (expression is null) + return; - if (expression == null) - return; + if (!IsNonNullStringExpression(expression)) + return; - if (!IsNonNullStringExpression(expression)) - return; + if (IsFormattableString(context)) + return; - if (IsFormattableString(context)) - return; + ReportDiagnostic(context, DiagnosticRules.UnnecessaryInterpolatedString, interpolatedString); - ReportDiagnostic(context, DiagnosticRules.UnnecessaryInterpolatedString, interpolatedString); + ReportToken(context, DiagnosticRules.UnnecessaryInterpolatedStringFadeOut, interpolatedString.StringStartToken); + ReportToken(context, DiagnosticRules.UnnecessaryInterpolatedStringFadeOut, interpolation.OpenBraceToken); + ReportToken(context, DiagnosticRules.UnnecessaryInterpolatedStringFadeOut, interpolation.CloseBraceToken); + ReportToken(context, DiagnosticRules.UnnecessaryInterpolatedStringFadeOut, interpolatedString.StringEndToken); + } - ReportToken(context, DiagnosticRules.UnnecessaryInterpolatedStringFadeOut, interpolatedString.StringStartToken); - ReportToken(context, DiagnosticRules.UnnecessaryInterpolatedStringFadeOut, interpolation.OpenBraceToken); - ReportToken(context, DiagnosticRules.UnnecessaryInterpolatedStringFadeOut, interpolation.CloseBraceToken); - ReportToken(context, DiagnosticRules.UnnecessaryInterpolatedStringFadeOut, interpolatedString.StringEndToken); - } + bool IsNonNullStringExpression(ExpressionSyntax expression) + { + if (expression.IsKind(SyntaxKind.StringLiteralExpression, SyntaxKind.InterpolatedStringExpression)) + return true; - bool IsNonNullStringExpression(ExpressionSyntax expression) - { - if (expression.IsKind(SyntaxKind.StringLiteralExpression, SyntaxKind.InterpolatedStringExpression)) - return true; + Optional constantValue = context.SemanticModel.GetConstantValue(expression, context.CancellationToken); - Optional constantValue = context.SemanticModel.GetConstantValue(expression, context.CancellationToken); + return constantValue.HasValue + && constantValue.Value is string value + && value is not null; + } - return constantValue.HasValue - && constantValue.Value is string value - && value != null; + static bool IsFormattableString(SyntaxNodeAnalysisContext context) + { + return context + .SemanticModel + .GetTypeInfo(context.Node, context.CancellationToken) + .ConvertedType? + .HasMetadataName(MetadataNames.System_FormattableString) == true; + } } - static bool IsFormattableString(SyntaxNodeAnalysisContext context) + private static TextSpan GetDollarSpan(InterpolatedStringExpressionSyntax interpolatedString) { - return context - .SemanticModel - .GetTypeInfo(context.Node, context.CancellationToken) - .ConvertedType? - .HasMetadataName(MetadataNames.System_FormattableString) == true; - } - } + SyntaxToken token = interpolatedString.StringStartToken; - private static TextSpan GetDollarSpan(InterpolatedStringExpressionSyntax interpolatedString) - { - SyntaxToken token = interpolatedString.StringStartToken; - - return new TextSpan(token.SpanStart + token.Text.IndexOf('$'), 1); + return new TextSpan(token.SpanStart + token.Text.IndexOf('$'), 1); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolationAnalyzer.cs index eb3f12a910..a1b1ff6d63 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolationAnalyzer.cs @@ -8,52 +8,53 @@ using Microsoft.CodeAnalysis.Diagnostics; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnnecessaryInterpolationAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnnecessaryInterpolationAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryInterpolation); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryInterpolation); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - context.RegisterSyntaxNodeAction(f => AnalyzeInterpolation(f), SyntaxKind.Interpolation); - } + context.RegisterSyntaxNodeAction(f => AnalyzeInterpolation(f), SyntaxKind.Interpolation); + } - private static void AnalyzeInterpolation(SyntaxNodeAnalysisContext context) - { - var interpolation = (InterpolationSyntax)context.Node; + private static void AnalyzeInterpolation(SyntaxNodeAnalysisContext context) + { + var interpolation = (InterpolationSyntax)context.Node; - if (interpolation.AlignmentClause != null) - return; + if (interpolation.AlignmentClause is not null) + return; - if (interpolation.FormatClause != null) - return; + if (interpolation.FormatClause is not null) + return; - StringLiteralExpressionInfo stringLiteralInfo = SyntaxInfo.StringLiteralExpressionInfo(interpolation.Expression); + StringLiteralExpressionInfo stringLiteralInfo = SyntaxInfo.StringLiteralExpressionInfo(interpolation.Expression); - if (!stringLiteralInfo.Success) - return; + if (!stringLiteralInfo.Success) + return; - if (interpolation.Parent is not InterpolatedStringExpressionSyntax interpolatedString) - return; + if (interpolation.Parent is not InterpolatedStringExpressionSyntax interpolatedString) + return; - if (interpolatedString.StringStartToken.ValueText.Contains("@") != stringLiteralInfo.IsVerbatim) - return; + if (interpolatedString.StringStartToken.ValueText.Contains("@") != stringLiteralInfo.IsVerbatim) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryInterpolation, interpolation); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryInterpolation, interpolation); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryNullCheckAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryNullCheckAnalyzer.cs index b59ebf0587..f274bf717b 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryNullCheckAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryNullCheckAnalyzer.cs @@ -9,134 +9,135 @@ using Roslynator.CSharp.Syntax; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnnecessaryNullCheckAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnnecessaryNullCheckAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryNullCheck); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryNullCheck); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterSyntaxNodeAction(f => AnalyzeLogicalAndExpression(f), SyntaxKind.LogicalAndExpression); - } + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - private static void AnalyzeLogicalAndExpression(SyntaxNodeAnalysisContext context) - { - var logicalAnd = (BinaryExpressionSyntax)context.Node; + context.RegisterSyntaxNodeAction(f => AnalyzeLogicalAndExpression(f), SyntaxKind.LogicalAndExpression); + } - if (logicalAnd.SpanContainsDirectives()) - return; + private static void AnalyzeLogicalAndExpression(SyntaxNodeAnalysisContext context) + { + var logicalAnd = (BinaryExpressionSyntax)context.Node; - BinaryExpressionInfo logicalAndInfo = SyntaxInfo.BinaryExpressionInfo(logicalAnd); + if (logicalAnd.SpanContainsDirectives()) + return; - if (!logicalAndInfo.Success) - return; + BinaryExpressionInfo logicalAndInfo = SyntaxInfo.BinaryExpressionInfo(logicalAnd); - NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo( - logicalAndInfo.Left, - context.SemanticModel, - NullCheckStyles.NotEqualsToNull | NullCheckStyles.HasValue, - cancellationToken: context.CancellationToken); + if (!logicalAndInfo.Success) + return; - if (!nullCheck.Success) - return; + NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo( + logicalAndInfo.Left, + context.SemanticModel, + NullCheckStyles.NotEqualsToNull | NullCheckStyles.HasValue, + cancellationToken: context.CancellationToken); - ExpressionSyntax right = logicalAndInfo.Right; + if (!nullCheck.Success) + return; - switch (right.Kind()) - { - case SyntaxKind.LogicalNotExpression: - { - var logicalNot = (PrefixUnaryExpressionSyntax)right; + ExpressionSyntax right = logicalAndInfo.Right; - 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); + switch (right.Kind()) + { + case SyntaxKind.LogicalNotExpression: + { + var logicalNot = (PrefixUnaryExpressionSyntax)right; - if (!binaryExpressionInfo.Success) + 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); + + if (!binaryExpressionInfo.Success) + break; - ExpressionSyntax left = binaryExpressionInfo.Left; - - Analyze(nullCheck.Expression, left, binaryExpressionInfo.Right); - break; - } - case SyntaxKind.SimpleMemberAccessExpression: - { - AnalyzeSimpleMemberAccessExpression(nullCheck.Expression, (MemberAccessExpressionSyntax)right, null); - break; - } - } + ExpressionSyntax left = binaryExpressionInfo.Left; - void Analyze(ExpressionSyntax expression1, ExpressionSyntax expression2, ExpressionSyntax expression3) - { - if (expression2.IsKind(SyntaxKind.SimpleMemberAccessExpression)) - AnalyzeSimpleMemberAccessExpression(expression1, (MemberAccessExpressionSyntax)expression2, expression3); - } + Analyze(nullCheck.Expression, left, binaryExpressionInfo.Right); + break; + } + case SyntaxKind.SimpleMemberAccessExpression: + { + AnalyzeSimpleMemberAccessExpression(nullCheck.Expression, (MemberAccessExpressionSyntax)right, null); + break; + } + } - void AnalyzeSimpleMemberAccessExpression(ExpressionSyntax expression, MemberAccessExpressionSyntax memberAccessExpression, ExpressionSyntax expression3) - { - if (memberAccessExpression.Name is not IdentifierNameSyntax identifierName - || !string.Equals(identifierName.Identifier.ValueText, "Value", StringComparison.Ordinal)) + void Analyze(ExpressionSyntax expression1, ExpressionSyntax expression2, ExpressionSyntax expression3) { - return; + if (expression2.IsKind(SyntaxKind.SimpleMemberAccessExpression)) + AnalyzeSimpleMemberAccessExpression(expression1, (MemberAccessExpressionSyntax)expression2, expression3); } - if (!SyntaxUtility.IsPropertyOfNullableOfT(memberAccessExpression, "Value", context.SemanticModel, context.CancellationToken)) - return; + void AnalyzeSimpleMemberAccessExpression(ExpressionSyntax expression, MemberAccessExpressionSyntax memberAccessExpression, ExpressionSyntax expression3) + { + if (memberAccessExpression.Name is not IdentifierNameSyntax identifierName + || !string.Equals(identifierName.Identifier.ValueText, "Value", StringComparison.Ordinal)) + { + return; + } - if (!AreEquivalent(expression, memberAccessExpression.Expression)) - return; + if (!SyntaxUtility.IsPropertyOfNullableOfT(memberAccessExpression, "Value", context.SemanticModel, context.CancellationToken)) + return; - if (expression3 != null) - { - switch (expression3.Kind()) + if (!AreEquivalent(expression, memberAccessExpression.Expression)) + return; + + if (expression3 is not null) { - case SyntaxKind.NumericLiteralExpression: - case SyntaxKind.StringLiteralExpression: - case SyntaxKind.CharacterLiteralExpression: - case SyntaxKind.TrueLiteralExpression: - case SyntaxKind.FalseLiteralExpression: - { - break; - } - case SyntaxKind.NullLiteralExpression: - case SyntaxKind.DefaultLiteralExpression: - { - return; - } - default: - { - if (context.SemanticModel.GetTypeSymbol(expression3, context.CancellationToken).IsNullableType()) + switch (expression3.Kind()) + { + case SyntaxKind.NumericLiteralExpression: + case SyntaxKind.StringLiteralExpression: + case SyntaxKind.CharacterLiteralExpression: + case SyntaxKind.TrueLiteralExpression: + case SyntaxKind.FalseLiteralExpression: + { + break; + } + case SyntaxKind.NullLiteralExpression: + case SyntaxKind.DefaultLiteralExpression: + { return; - - break; - } + } + default: + { + if (context.SemanticModel.GetTypeSymbol(expression3, context.CancellationToken).IsNullableType()) + return; + + break; + } + } } - } - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryNullCheck, logicalAnd); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryNullCheck, logicalAnd); + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryUnsafeContextAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryUnsafeContextAnalyzer.cs index bb03ee9a63..8178a0a682 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryUnsafeContextAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryUnsafeContextAnalyzer.cs @@ -8,273 +8,274 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnnecessaryUnsafeContextAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnnecessaryUnsafeContextAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryUnsafeContext); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UnnecessaryUnsafeContext); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterSyntaxNodeAction( - f => AnalyzeTypeDeclaration(f), - SyntaxKind.ClassDeclaration, - SyntaxKind.StructDeclaration, - SyntaxKind.RecordStructDeclaration, - SyntaxKind.InterfaceDeclaration); - - context.RegisterSyntaxNodeAction(f => AnalyzeUnsafeStatement(f), SyntaxKind.UnsafeStatement); - context.RegisterSyntaxNodeAction(f => AnalyzeDelegateDeclaration(f), SyntaxKind.DelegateDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); - context.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeOperatorDeclaration(f), SyntaxKind.OperatorDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeConversionOperatorDeclaration(f), SyntaxKind.ConversionOperatorDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeConstructorDeclaration(f), SyntaxKind.ConstructorDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeDestructorDeclaration(f), SyntaxKind.DestructorDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzePropertyDeclaration(f), SyntaxKind.PropertyDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeIndexerDeclaration(f), SyntaxKind.IndexerDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeEventDeclaration(f), SyntaxKind.EventDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeEventFieldDeclaration(f), SyntaxKind.EventFieldDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeFieldDeclaration(f), SyntaxKind.FieldDeclaration); - } - - private static void AnalyzeUnsafeStatement(SyntaxNodeAnalysisContext context) - { - var unsafeStatement = (UnsafeStatementSyntax)context.Node; + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); + + context.RegisterSyntaxNodeAction( + f => AnalyzeTypeDeclaration(f), + SyntaxKind.ClassDeclaration, + SyntaxKind.StructDeclaration, + SyntaxKind.RecordStructDeclaration, + SyntaxKind.InterfaceDeclaration); + + context.RegisterSyntaxNodeAction(f => AnalyzeUnsafeStatement(f), SyntaxKind.UnsafeStatement); + context.RegisterSyntaxNodeAction(f => AnalyzeDelegateDeclaration(f), SyntaxKind.DelegateDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); + context.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeOperatorDeclaration(f), SyntaxKind.OperatorDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeConversionOperatorDeclaration(f), SyntaxKind.ConversionOperatorDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeConstructorDeclaration(f), SyntaxKind.ConstructorDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeDestructorDeclaration(f), SyntaxKind.DestructorDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzePropertyDeclaration(f), SyntaxKind.PropertyDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeIndexerDeclaration(f), SyntaxKind.IndexerDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeEventDeclaration(f), SyntaxKind.EventDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeEventFieldDeclaration(f), SyntaxKind.EventFieldDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeFieldDeclaration(f), SyntaxKind.FieldDeclaration); + } - if (!unsafeStatement.Block.Statements.Any()) - return; + private static void AnalyzeUnsafeStatement(SyntaxNodeAnalysisContext context) + { + var unsafeStatement = (UnsafeStatementSyntax)context.Node; - if (!ParentDeclarationsContainsUnsafeModifier(unsafeStatement)) - return; + if (!unsafeStatement.Block.Statements.Any()) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryUnsafeContext, unsafeStatement.UnsafeKeyword); - } + if (!ParentDeclarationsContainsUnsafeModifier(unsafeStatement)) + return; - private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) - { - var localFunctionStatement = (LocalFunctionStatementSyntax)context.Node; + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryUnsafeContext, unsafeStatement.UnsafeKeyword); + } - SyntaxTokenList modifiers = localFunctionStatement.Modifiers; + private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) + { + var localFunctionStatement = (LocalFunctionStatementSyntax)context.Node; - int index = modifiers.IndexOf(SyntaxKind.UnsafeKeyword); + SyntaxTokenList modifiers = localFunctionStatement.Modifiers; - if (index == -1) - return; + int index = modifiers.IndexOf(SyntaxKind.UnsafeKeyword); - SyntaxNode parent = localFunctionStatement.Parent; + if (index == -1) + return; - SyntaxDebug.Assert(parent.IsKind(SyntaxKind.Block), parent); + SyntaxNode parent = localFunctionStatement.Parent; - if (parent is not BlockSyntax) - return; + SyntaxDebug.Assert(parent.IsKind(SyntaxKind.Block), parent); - parent = parent.Parent; + if (parent is not BlockSyntax) + return; - if (!ParentDeclarationsContainsUnsafeModifier(parent)) - return; + parent = parent.Parent; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryUnsafeContext, modifiers[index]); - } + if (!ParentDeclarationsContainsUnsafeModifier(parent)) + return; - private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) - { - var typeDeclaration = (TypeDeclarationSyntax)context.Node; + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryUnsafeContext, modifiers[index]); + } - AnalyzeMemberDeclaration(context, typeDeclaration, typeDeclaration.Modifiers); - } + private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) + { + var typeDeclaration = (TypeDeclarationSyntax)context.Node; - private static void AnalyzeDelegateDeclaration(SyntaxNodeAnalysisContext context) - { - var delegateDeclaration = (DelegateDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, typeDeclaration, typeDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, delegateDeclaration, delegateDeclaration.Modifiers); - } + private static void AnalyzeDelegateDeclaration(SyntaxNodeAnalysisContext context) + { + var delegateDeclaration = (DelegateDeclarationSyntax)context.Node; - private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) - { - var methodDeclaration = (MethodDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, delegateDeclaration, delegateDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, methodDeclaration, methodDeclaration.Modifiers); - } + private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) + { + var methodDeclaration = (MethodDeclarationSyntax)context.Node; - private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context) - { - var operatorDeclaration = (OperatorDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, methodDeclaration, methodDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, operatorDeclaration, operatorDeclaration.Modifiers); - } + private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context) + { + var operatorDeclaration = (OperatorDeclarationSyntax)context.Node; - private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisContext context) - { - var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, operatorDeclaration, operatorDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, conversionOperatorDeclaration, conversionOperatorDeclaration.Modifiers); - } + private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisContext context) + { + var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)context.Node; - private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext context) - { - var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, conversionOperatorDeclaration, conversionOperatorDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, constructorDeclaration, constructorDeclaration.Modifiers); - } + private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext context) + { + var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node; - private static void AnalyzeDestructorDeclaration(SyntaxNodeAnalysisContext context) - { - var destructorDeclaration = (DestructorDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, constructorDeclaration, constructorDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, destructorDeclaration, destructorDeclaration.Modifiers); - } + private static void AnalyzeDestructorDeclaration(SyntaxNodeAnalysisContext context) + { + var destructorDeclaration = (DestructorDeclarationSyntax)context.Node; - private static void AnalyzeEventDeclaration(SyntaxNodeAnalysisContext context) - { - var eventDeclaration = (EventDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, destructorDeclaration, destructorDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, eventDeclaration, eventDeclaration.Modifiers); - } + private static void AnalyzeEventDeclaration(SyntaxNodeAnalysisContext context) + { + var eventDeclaration = (EventDeclarationSyntax)context.Node; - private static void AnalyzeEventFieldDeclaration(SyntaxNodeAnalysisContext context) - { - var eventFieldDeclaration = (EventFieldDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, eventDeclaration, eventDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, eventFieldDeclaration, eventFieldDeclaration.Modifiers); - } + private static void AnalyzeEventFieldDeclaration(SyntaxNodeAnalysisContext context) + { + var eventFieldDeclaration = (EventFieldDeclarationSyntax)context.Node; - private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) - { - var fieldDeclaration = (FieldDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, eventFieldDeclaration, eventFieldDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, fieldDeclaration, fieldDeclaration.Modifiers); - } + private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) + { + var fieldDeclaration = (FieldDeclarationSyntax)context.Node; - private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) - { - var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, fieldDeclaration, fieldDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, propertyDeclaration, propertyDeclaration.Modifiers); - } + private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) + { + var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; - private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) - { - var indexerDeclaration = (IndexerDeclarationSyntax)context.Node; + AnalyzeMemberDeclaration(context, propertyDeclaration, propertyDeclaration.Modifiers); + } - AnalyzeMemberDeclaration(context, indexerDeclaration, indexerDeclaration.Modifiers); - } + private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) + { + var indexerDeclaration = (IndexerDeclarationSyntax)context.Node; - private static void AnalyzeMemberDeclaration( - SyntaxNodeAnalysisContext context, - MemberDeclarationSyntax memberDeclaration, - SyntaxTokenList modifiers) - { - int index = modifiers.IndexOf(SyntaxKind.UnsafeKeyword); + AnalyzeMemberDeclaration(context, indexerDeclaration, indexerDeclaration.Modifiers); + } - if (index == -1) - return; + private static void AnalyzeMemberDeclaration( + SyntaxNodeAnalysisContext context, + MemberDeclarationSyntax memberDeclaration, + SyntaxTokenList modifiers) + { + int index = modifiers.IndexOf(SyntaxKind.UnsafeKeyword); - if (!ParentTypeDeclarationsContainsUnsafeModifier(memberDeclaration)) - return; + if (index == -1) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryUnsafeContext, modifiers[index]); - } + if (!ParentTypeDeclarationsContainsUnsafeModifier(memberDeclaration)) + return; - private static bool ParentDeclarationsContainsUnsafeModifier(UnsafeStatementSyntax unsafeStatement) - { - SyntaxNode parent = unsafeStatement.Parent; + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnnecessaryUnsafeContext, modifiers[index]); + } - while (parent != null) + private static bool ParentDeclarationsContainsUnsafeModifier(UnsafeStatementSyntax unsafeStatement) { - SyntaxKind kind = parent.Kind(); + SyntaxNode parent = unsafeStatement.Parent; - if (kind == SyntaxKind.UnsafeStatement) - { - return true; - } - else if (kind == SyntaxKind.LocalFunctionStatement) + while (parent is not null) { - break; - } + SyntaxKind kind = parent.Kind(); + + if (kind == SyntaxKind.UnsafeStatement) + { + return true; + } + else if (kind == SyntaxKind.LocalFunctionStatement) + { + break; + } + + if (parent is AccessorDeclarationSyntax) + { + parent = parent.Parent; - if (parent is AccessorDeclarationSyntax) - { - parent = parent.Parent; + if (parent is AccessorListSyntax) + parent = parent.Parent; - if (parent is AccessorListSyntax) - parent = parent.Parent; + break; + } - break; - } + if (parent is MemberDeclarationSyntax) + break; - if (parent is MemberDeclarationSyntax) - break; + parent = parent.Parent; + } - parent = parent.Parent; + return ParentDeclarationsContainsUnsafeModifier(parent); } - return ParentDeclarationsContainsUnsafeModifier(parent); - } - - private static bool ParentDeclarationsContainsUnsafeModifier(SyntaxNode node) - { - while (node.IsKind(SyntaxKind.LocalFunctionStatement)) + private static bool ParentDeclarationsContainsUnsafeModifier(SyntaxNode node) { - var localFunction = (LocalFunctionStatementSyntax)node; + while (node.IsKind(SyntaxKind.LocalFunctionStatement)) + { + var localFunction = (LocalFunctionStatementSyntax)node; - if (localFunction.Modifiers.Contains(SyntaxKind.UnsafeKeyword)) - return true; + if (localFunction.Modifiers.Contains(SyntaxKind.UnsafeKeyword)) + return true; - node = node.Parent; + node = node.Parent; - SyntaxDebug.Assert(node.IsKind(SyntaxKind.Block), node); + SyntaxDebug.Assert(node.IsKind(SyntaxKind.Block), node); - if (!node.IsKind(SyntaxKind.Block)) - break; + if (!node.IsKind(SyntaxKind.Block)) + break; - node = node.Parent; - } + node = node.Parent; + } - SyntaxDebug.Assert(node is MemberDeclarationSyntax, node); + SyntaxDebug.Assert(node is MemberDeclarationSyntax, node); - if (node is MemberDeclarationSyntax memberDeclaration) - { - if (SyntaxInfo.ModifierListInfo(memberDeclaration).IsUnsafe) - return true; + if (node is MemberDeclarationSyntax memberDeclaration) + { + if (SyntaxInfo.ModifierListInfo(memberDeclaration).IsUnsafe) + return true; + + return ParentTypeDeclarationsContainsUnsafeModifier(memberDeclaration); + } - return ParentTypeDeclarationsContainsUnsafeModifier(memberDeclaration); + return false; } - return false; - } + private static bool ParentTypeDeclarationsContainsUnsafeModifier(MemberDeclarationSyntax memberDeclaration) + { + SyntaxNode parent = memberDeclaration.Parent; - private static bool ParentTypeDeclarationsContainsUnsafeModifier(MemberDeclarationSyntax memberDeclaration) - { - SyntaxNode parent = memberDeclaration.Parent; + while (parent.IsKind( + SyntaxKind.ClassDeclaration, + SyntaxKind.StructDeclaration, + SyntaxKind.RecordStructDeclaration, + SyntaxKind.InterfaceDeclaration)) + { + if (((TypeDeclarationSyntax)parent).Modifiers.Contains(SyntaxKind.UnsafeKeyword)) + return true; - while (parent.IsKind( - SyntaxKind.ClassDeclaration, - SyntaxKind.StructDeclaration, - SyntaxKind.RecordStructDeclaration, - SyntaxKind.InterfaceDeclaration)) - { - if (((TypeDeclarationSyntax)parent).Modifiers.Contains(SyntaxKind.UnsafeKeyword)) - return true; + parent = parent.Parent; + } - parent = parent.Parent; + return false; } - - return false; } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryUsageOfEnumeratorWalker.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryUsageOfEnumeratorWalker.cs index 5903e89d2f..588570bd9d 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryUsageOfEnumeratorWalker.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryUsageOfEnumeratorWalker.cs @@ -8,107 +8,108 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis; - -internal class UnnecessaryUsageOfEnumeratorWalker : CSharpSyntaxNodeWalker +namespace Roslynator.CSharp.Analysis { - [ThreadStatic] - private static UnnecessaryUsageOfEnumeratorWalker _cachedInstance; - - private ISymbol _symbol; - private VariableDeclaratorSyntax _variableDeclarator; - private string _name; - private SemanticModel _semanticModel; - private CancellationToken _cancellationToken; + internal class UnnecessaryUsageOfEnumeratorWalker : CSharpSyntaxNodeWalker + { + [ThreadStatic] + private static UnnecessaryUsageOfEnumeratorWalker _cachedInstance; - public bool? IsFixable { get; private set; } + private ISymbol _symbol; + private VariableDeclaratorSyntax _variableDeclarator; + private string _name; + private SemanticModel _semanticModel; + private CancellationToken _cancellationToken; - public void SetValues( - VariableDeclaratorSyntax variableDeclarator, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - IsFixable = null; + public bool? IsFixable { get; private set; } - _symbol = null; - _name = variableDeclarator?.Identifier.ValueText; - _variableDeclarator = variableDeclarator; - _semanticModel = semanticModel; - _cancellationToken = cancellationToken; - } + public void SetValues( + VariableDeclaratorSyntax variableDeclarator, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + IsFixable = null; - protected override bool ShouldVisit => IsFixable != false; + _symbol = null; + _name = variableDeclarator?.Identifier.ValueText; + _variableDeclarator = variableDeclarator; + _semanticModel = semanticModel; + _cancellationToken = cancellationToken; + } - public override void VisitIdentifierName(IdentifierNameSyntax node) - { - if (!string.Equals(node.Identifier.ValueText, _name)) - return; + protected override bool ShouldVisit => IsFixable != false; - if (_symbol == null) + public override void VisitIdentifierName(IdentifierNameSyntax node) { - _symbol = _semanticModel.GetDeclaredSymbol(_variableDeclarator, _cancellationToken); + if (!string.Equals(node.Identifier.ValueText, _name)) + return; - if (_symbol?.IsErrorType() != false) + if (_symbol is null) + { + _symbol = _semanticModel.GetDeclaredSymbol(_variableDeclarator, _cancellationToken); + + if (_symbol?.IsErrorType() != false) + { + IsFixable = false; + return; + } + } + + if (!SymbolEqualityComparer.Default.Equals(_symbol, _semanticModel.GetSymbol(node, _cancellationToken))) + return; + + if (!node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) { IsFixable = false; return; } - } - if (!SymbolEqualityComparer.Default.Equals(_symbol, _semanticModel.GetSymbol(node, _cancellationToken))) - return; + var memberAccessExpression = (MemberAccessExpressionSyntax)node.Parent; - if (!node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) - { - IsFixable = false; - return; - } + if (memberAccessExpression.Expression != node) + { + IsFixable = false; + return; + } - var memberAccessExpression = (MemberAccessExpressionSyntax)node.Parent; + if (memberAccessExpression.Name is not IdentifierNameSyntax identifierName) + { + IsFixable = false; + return; + } - if (memberAccessExpression.Expression != node) - { - IsFixable = false; - return; - } + if (!string.Equals(identifierName.Identifier.ValueText, WellKnownMemberNames.CurrentPropertyName, StringComparison.Ordinal)) + { + IsFixable = false; + return; + } - if (memberAccessExpression.Name is not IdentifierNameSyntax identifierName) - { - IsFixable = false; - return; + IsFixable = true; } - if (!string.Equals(identifierName.Identifier.ValueText, WellKnownMemberNames.CurrentPropertyName, StringComparison.Ordinal)) + public static UnnecessaryUsageOfEnumeratorWalker GetInstance() { - IsFixable = false; - return; - } + UnnecessaryUsageOfEnumeratorWalker walker = _cachedInstance; - IsFixable = true; - } - - public static UnnecessaryUsageOfEnumeratorWalker GetInstance() - { - UnnecessaryUsageOfEnumeratorWalker walker = _cachedInstance; + if (walker is not null) + { + Debug.Assert(walker._symbol is null); + Debug.Assert(walker._variableDeclarator is null); + Debug.Assert(walker._semanticModel is null); + Debug.Assert(walker._cancellationToken == default); - if (walker != null) - { - Debug.Assert(walker._symbol == null); - Debug.Assert(walker._variableDeclarator == null); - Debug.Assert(walker._semanticModel == null); - Debug.Assert(walker._cancellationToken == default); + _cachedInstance = null; + return walker; + } - _cachedInstance = null; - return walker; + return new UnnecessaryUsageOfEnumeratorWalker(); } - return new UnnecessaryUsageOfEnumeratorWalker(); - } - - public static void Free(UnnecessaryUsageOfEnumeratorWalker walker) - { - walker.SetValues(default(VariableDeclaratorSyntax), default(SemanticModel), default(CancellationToken)); + public static void Free(UnnecessaryUsageOfEnumeratorWalker walker) + { + walker.SetValues(default(VariableDeclaratorSyntax), default(SemanticModel), default(CancellationToken)); - _cachedInstance = walker; + _cachedInstance = walker; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnusedMember/UnityScriptMethods.cs b/src/Analyzers/CSharp/Analysis/UnusedMember/UnityScriptMethods.cs index ea0afe054d..3704def101 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedMember/UnityScriptMethods.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedMember/UnityScriptMethods.cs @@ -3,93 +3,94 @@ using System.Collections.Immutable; using System.Threading; -namespace Roslynator.CSharp.Analysis.UnusedMember; - -internal static class UnityScriptMethods +namespace Roslynator.CSharp.Analysis.UnusedMember { - private static ImmutableHashSet _methodNames; + internal static class UnityScriptMethods + { + private static ImmutableHashSet _methodNames; - public static MetadataName MonoBehaviourClassName { get; } = MetadataName.Parse("UnityEngine.MonoBehaviour"); + public static MetadataName MonoBehaviourClassName { get; } = MetadataName.Parse("UnityEngine.MonoBehaviour"); - public static ImmutableHashSet MethodNames - { - get + public static ImmutableHashSet MethodNames { - if (_methodNames == null) - Interlocked.CompareExchange(ref _methodNames, LoadMethodNames(), null); + get + { + if (_methodNames is null) + Interlocked.CompareExchange(ref _methodNames, LoadMethodNames(), null); - return _methodNames; + return _methodNames; + } } - } - private static ImmutableHashSet LoadMethodNames() - { - return ImmutableHashSet.CreateRange(new[] { - "Awake", - "FixedUpdate", - "LateUpdate", - "OnAnimatorIK", - "OnAnimatorMove", - "OnApplicationFocus", - "OnApplicationPause", - "OnApplicationQuit", - "OnAudioFilterRead", - "OnBecameInvisible", - "OnBecameVisible", - "OnCollisionEnter", - "OnCollisionEnter2D", - "OnCollisionExit", - "OnCollisionExit2D", - "OnCollisionStay", - "OnCollisionStay2D", - "OnConnectedToServer", - "OnControllerColliderHit", - "OnDestroy", - "OnDisable", - "OnDisconnectedFromServer", - "OnDrawGizmos", - "OnDrawGizmosSelected", - "OnEnable", - "OnFailedToConnect", - "OnFailedToConnectToMasterServer", - "OnGUI", - "OnJointBreak", - "OnJointBreak2D", - "OnMasterServerEvent", - "OnMouseDown", - "OnMouseDrag", - "OnMouseEnter", - "OnMouseExit", - "OnMouseOver", - "OnMouseUp", - "OnMouseUpAsButton", - "OnNetworkInstantiate", - "OnParticleCollision", - "OnParticleSystemStopped", - "OnParticleTrigger", - "OnParticleUpdateJobScheduled", - "OnPlayerConnected", - "OnPlayerDisconnected", - "OnPostRender", - "OnPreCull", - "OnPreRender", - "OnRenderImage", - "OnRenderObject", - "OnSerializeNetworkView", - "OnServerInitialized", - "OnTransformChildrenChanged", - "OnTransformParentChanged", - "OnTriggerEnter", - "OnTriggerEnter2D", - "OnTriggerExit", - "OnTriggerExit2D", - "OnTriggerStay", - "OnTriggerStay2D", - "OnValidate", - "OnWillRenderObject", - "Reset", - "Start", - "Update", - }); + private static ImmutableHashSet LoadMethodNames() + { + return ImmutableHashSet.CreateRange(new[] { + "Awake", + "FixedUpdate", + "LateUpdate", + "OnAnimatorIK", + "OnAnimatorMove", + "OnApplicationFocus", + "OnApplicationPause", + "OnApplicationQuit", + "OnAudioFilterRead", + "OnBecameInvisible", + "OnBecameVisible", + "OnCollisionEnter", + "OnCollisionEnter2D", + "OnCollisionExit", + "OnCollisionExit2D", + "OnCollisionStay", + "OnCollisionStay2D", + "OnConnectedToServer", + "OnControllerColliderHit", + "OnDestroy", + "OnDisable", + "OnDisconnectedFromServer", + "OnDrawGizmos", + "OnDrawGizmosSelected", + "OnEnable", + "OnFailedToConnect", + "OnFailedToConnectToMasterServer", + "OnGUI", + "OnJointBreak", + "OnJointBreak2D", + "OnMasterServerEvent", + "OnMouseDown", + "OnMouseDrag", + "OnMouseEnter", + "OnMouseExit", + "OnMouseOver", + "OnMouseUp", + "OnMouseUpAsButton", + "OnNetworkInstantiate", + "OnParticleCollision", + "OnParticleSystemStopped", + "OnParticleTrigger", + "OnParticleUpdateJobScheduled", + "OnPlayerConnected", + "OnPlayerDisconnected", + "OnPostRender", + "OnPreCull", + "OnPreRender", + "OnRenderImage", + "OnRenderObject", + "OnSerializeNetworkView", + "OnServerInitialized", + "OnTransformChildrenChanged", + "OnTransformParentChanged", + "OnTriggerEnter", + "OnTriggerEnter2D", + "OnTriggerExit", + "OnTriggerExit2D", + "OnTriggerStay", + "OnTriggerStay2D", + "OnValidate", + "OnWillRenderObject", + "Reset", + "Start", + "Update", + }); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs index 7d663bc002..c770fb431a 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs @@ -11,360 +11,361 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis.UnusedMember; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnusedMemberAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis.UnusedMember { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnusedMemberAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.RemoveUnusedMemberDeclaration); - } + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.RemoveUnusedMemberDeclaration); + } - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterSyntaxNodeAction( - f => AnalyzeTypeDeclaration(f), - SyntaxKind.ClassDeclaration, - SyntaxKind.StructDeclaration, - SyntaxKind.RecordStructDeclaration); - } - - [SuppressMessage("Simplification", "RCS1180:Inline lazy initialization.")] - private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) - { - var typeDeclaration = (TypeDeclarationSyntax)context.Node; - - if (typeDeclaration.Modifiers.Contains(SyntaxKind.PartialKeyword)) - return; - - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - INamedTypeSymbol declarationSymbol = null; - ImmutableArray attributes = default; + context.RegisterSyntaxNodeAction( + f => AnalyzeTypeDeclaration(f), + SyntaxKind.ClassDeclaration, + SyntaxKind.StructDeclaration, + SyntaxKind.RecordStructDeclaration); + } - if (typeDeclaration.IsKind(SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration)) + [SuppressMessage("Simplification", "RCS1180:Inline lazy initialization.")] + private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) { - declarationSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); - - attributes = declarationSymbol.GetAttributes(); + var typeDeclaration = (TypeDeclarationSyntax)context.Node; - if (attributes.Any(f => f.AttributeClass.HasMetadataName(MetadataNames.System_Runtime_InteropServices_StructLayoutAttribute))) + if (typeDeclaration.Modifiers.Contains(SyntaxKind.PartialKeyword)) return; - } - bool? canContainUnityScriptMethods = null; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; + + INamedTypeSymbol declarationSymbol = null; + ImmutableArray attributes = default; - SyntaxList members = typeDeclaration.Members; + if (typeDeclaration.IsKind(SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration)) + { + declarationSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); - UnusedMemberWalker walker = null; + attributes = declarationSymbol.GetAttributes(); - foreach (MemberDeclarationSyntax member in members) - { - if (member.ContainsDiagnostics) - continue; + if (attributes.Any(f => f.AttributeClass.HasMetadataName(MetadataNames.System_Runtime_InteropServices_StructLayoutAttribute))) + return; + } - if (member.ContainsUnbalancedIfElseDirectives(member.Span)) - continue; + bool? canContainUnityScriptMethods = null; - switch (member.Kind()) - { - case SyntaxKind.DelegateDeclaration: - { - var declaration = (DelegateDeclarationSyntax)member; + SyntaxList members = typeDeclaration.Members; - if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker == null) - walker = UnusedMemberWalker.GetInstance(); + UnusedMemberWalker walker = null; - walker.AddDelegate(declaration.Identifier.ValueText, declaration); - } + foreach (MemberDeclarationSyntax member in members) + { + if (member.ContainsDiagnostics) + continue; - break; - } - case SyntaxKind.EventDeclaration: - { - var declaration = (EventDeclarationSyntax)member; + if (member.ContainsUnbalancedIfElseDirectives(member.Span)) + continue; - if (declaration.ExplicitInterfaceSpecifier == null - && SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) + switch (member.Kind()) + { + case SyntaxKind.DelegateDeclaration: { - if (walker == null) - walker = UnusedMemberWalker.GetInstance(); - - walker.AddNode(declaration.Identifier.ValueText, declaration); - } + var declaration = (DelegateDeclarationSyntax)member; - break; - } - case SyntaxKind.EventFieldDeclaration: - { - var declaration = (EventFieldDeclarationSyntax)member; + if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) + { + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker == null) - walker = UnusedMemberWalker.GetInstance(); + walker.AddDelegate(declaration.Identifier.ValueText, declaration); + } - walker.AddNodes(declaration.Declaration); + break; } + case SyntaxKind.EventDeclaration: + { + var declaration = (EventDeclarationSyntax)member; - break; - } - case SyntaxKind.FieldDeclaration: - { - var declaration = (FieldDeclarationSyntax)member; - SyntaxTokenList modifiers = declaration.Modifiers; + if (declaration.ExplicitInterfaceSpecifier is null + && SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) + { + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker == null) - walker = UnusedMemberWalker.GetInstance(); + walker.AddNode(declaration.Identifier.ValueText, declaration); + } - walker.AddNodes(declaration.Declaration, isConst: modifiers.Contains(SyntaxKind.ConstKeyword)); + break; } + case SyntaxKind.EventFieldDeclaration: + { + var declaration = (EventFieldDeclarationSyntax)member; - break; - } - case SyntaxKind.MethodDeclaration: - { - var declaration = (MethodDeclarationSyntax)member; + if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) + { + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - SyntaxTokenList modifiers = declaration.Modifiers; + walker.AddNodes(declaration.Declaration); + } - if (declaration.ExplicitInterfaceSpecifier != null - || declaration.AttributeLists.Any() - || SyntaxAccessibility.Instance.GetAccessibility(declaration) != Accessibility.Private) - { break; } + case SyntaxKind.FieldDeclaration: + { + var declaration = (FieldDeclarationSyntax)member; + SyntaxTokenList modifiers = declaration.Modifiers; - string methodName = declaration.Identifier.ValueText; + if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) + { + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - if (IsMainMethod(declaration, modifiers, methodName)) - break; + walker.AddNodes(declaration.Declaration, isConst: modifiers.Contains(SyntaxKind.ConstKeyword)); + } - if (declaration.ReturnsVoid() - && context.GetSuppressUnityScriptMethods() == true) + break; + } + case SyntaxKind.MethodDeclaration: { - if (canContainUnityScriptMethods == null) - { - if (declarationSymbol == null) - declarationSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, context.CancellationToken); + var declaration = (MethodDeclarationSyntax)member; - canContainUnityScriptMethods = declarationSymbol.InheritsFrom(UnityScriptMethods.MonoBehaviourClassName); - } + SyntaxTokenList modifiers = declaration.Modifiers; - if (canContainUnityScriptMethods == true - && UnityScriptMethods.MethodNames.Contains(methodName)) + if (declaration.ExplicitInterfaceSpecifier is not null + || declaration.AttributeLists.Any() + || SyntaxAccessibility.Instance.GetAccessibility(declaration) != Accessibility.Private) { break; } - } - if (walker == null) - walker = UnusedMemberWalker.GetInstance(); + string methodName = declaration.Identifier.ValueText; - walker.AddNode(methodName, declaration); + if (IsMainMethod(declaration, modifiers, methodName)) + break; - break; - } - case SyntaxKind.PropertyDeclaration: - { - var declaration = (PropertyDeclarationSyntax)member; + if (declaration.ReturnsVoid() + && context.GetSuppressUnityScriptMethods() == true) + { + if (canContainUnityScriptMethods is null) + { + if (declarationSymbol is null) + declarationSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, context.CancellationToken); - if (declaration.ExplicitInterfaceSpecifier == null - && SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker == null) + canContainUnityScriptMethods = declarationSymbol.InheritsFrom(UnityScriptMethods.MonoBehaviourClassName); + } + + if (canContainUnityScriptMethods == true + && UnityScriptMethods.MethodNames.Contains(methodName)) + { + break; + } + } + + if (walker is null) walker = UnusedMemberWalker.GetInstance(); - walker.AddNode(declaration.Identifier.ValueText, declaration); - } + walker.AddNode(methodName, declaration); - break; - } - } - } + break; + } + case SyntaxKind.PropertyDeclaration: + { + var declaration = (PropertyDeclarationSyntax)member; - if (walker == null) - return; + if (declaration.ExplicitInterfaceSpecifier is null + && SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) + { + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - try - { - Collection nodes = walker.Nodes; + walker.AddNode(declaration.Identifier.ValueText, declaration); + } - if (ShouldAnalyzeDebuggerDisplayAttribute() - && nodes.Any(f => f.CanBeInDebuggerDisplayAttribute)) - { - if (attributes.IsDefault) - attributes = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken).GetAttributes(); - - string value = attributes - .FirstOrDefault(f => f.AttributeClass.HasMetadataName(MetadataNames.System_Diagnostics_DebuggerDisplayAttribute))? - .ConstructorArguments - .SingleOrDefault(shouldThrow: false) - .Value? - .ToString(); - - if (value != null) - RemoveMethodsAndPropertiesThatAreInDebuggerDisplayAttributeValue(value, ref nodes); + break; + } + } } - if (nodes.Count > 0) + if (walker is null) + return; + + try { - walker.SemanticModel = semanticModel; - walker.CancellationToken = cancellationToken; + Collection nodes = walker.Nodes; + + if (ShouldAnalyzeDebuggerDisplayAttribute() + && nodes.Any(f => f.CanBeInDebuggerDisplayAttribute)) + { + if (attributes.IsDefault) + attributes = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken).GetAttributes(); + + string value = attributes + .FirstOrDefault(f => f.AttributeClass.HasMetadataName(MetadataNames.System_Diagnostics_DebuggerDisplayAttribute))? + .ConstructorArguments + .SingleOrDefault(shouldThrow: false) + .Value? + .ToString(); + + if (value is not null) + RemoveMethodsAndPropertiesThatAreInDebuggerDisplayAttributeValue(value, ref nodes); + } + + if (nodes.Count > 0) + { + walker.SemanticModel = semanticModel; + walker.CancellationToken = cancellationToken; - walker.Visit(typeDeclaration); + walker.Visit(typeDeclaration); - foreach (NodeSymbolInfo node in nodes) - ReportDiagnostic(context, node.Node); + foreach (NodeSymbolInfo node in nodes) + ReportDiagnostic(context, node.Node); + } + } + finally + { + UnusedMemberWalker.Free(walker); } - } - finally - { - UnusedMemberWalker.Free(walker); - } - bool ShouldAnalyzeDebuggerDisplayAttribute() - { - foreach (AttributeListSyntax attributeList in typeDeclaration.AttributeLists) + bool ShouldAnalyzeDebuggerDisplayAttribute() { - foreach (AttributeSyntax attribute in attributeList.Attributes) + foreach (AttributeListSyntax attributeList in typeDeclaration.AttributeLists) { - if (attribute.ArgumentList?.Arguments.Count(f => f.NameEquals == null) == 1) - return true; + foreach (AttributeSyntax attribute in attributeList.Attributes) + { + if (attribute.ArgumentList?.Arguments.Count(f => f.NameEquals is null) == 1) + return true; + } } - } - return false; + return false; + } } - } - private static bool IsMainMethod(MethodDeclarationSyntax methodDeclaration, SyntaxTokenList modifiers, string methodName) - { - return string.Equals(methodName, "Main", StringComparison.Ordinal) - && modifiers.Contains(SyntaxKind.StaticKeyword) - && methodDeclaration.TypeParameterList == null - && methodDeclaration.ParameterList?.Parameters.Count <= 1; - } - - private static void RemoveMethodsAndPropertiesThatAreInDebuggerDisplayAttributeValue( - string value, - ref Collection nodes) - { - int length = value.Length; - - if (length == 0) - return; + private static bool IsMainMethod(MethodDeclarationSyntax methodDeclaration, SyntaxTokenList modifiers, string methodName) + { + return string.Equals(methodName, "Main", StringComparison.Ordinal) + && modifiers.Contains(SyntaxKind.StaticKeyword) + && methodDeclaration.TypeParameterList is null + && methodDeclaration.ParameterList?.Parameters.Count <= 1; + } - for (int i = 0; i < length; i++) + private static void RemoveMethodsAndPropertiesThatAreInDebuggerDisplayAttributeValue( + string value, + ref Collection nodes) { - switch (value[i]) - { - case '{': - { - i++; + int length = value.Length; - int startIndex = i; + if (length == 0) + return; - while (i < length) + for (int i = 0; i < length; i++) + { + switch (value[i]) + { + case '{': { - char ch = value[i]; + i++; - if (ch == '}' - || ch == ',' - || ch == '(') + int startIndex = i; + + while (i < length) { - int nameLength = i - startIndex; + char ch = value[i]; - if (nameLength > 0) + if (ch == '}' + || ch == ',' + || ch == '(') { - for (int j = nodes.Count - 1; j >= 0; j--) - { - NodeSymbolInfo nodeSymbolInfo = nodes[j]; + int nameLength = i - startIndex; - if (nodeSymbolInfo.CanBeInDebuggerDisplayAttribute - && string.CompareOrdinal(nodeSymbolInfo.Name, 0, value, startIndex, nameLength) == 0) + if (nameLength > 0) + { + for (int j = nodes.Count - 1; j >= 0; j--) { - nodes.RemoveAt(j); + NodeSymbolInfo nodeSymbolInfo = nodes[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 != '}') - { - i++; - while (i < length - && value[i] != '}') + if (ch != '}') { i++; + + while (i < length + && value[i] != '}') + { + i++; + } } + + break; } - break; + i++; } + break; + } + case '}': + { + return; + } + case '\\': + { i++; + break; } - - break; - } - case '}': - { - return; - } - case '\\': - { - i++; - break; - } + } } } - } - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node) - { - if (node is VariableDeclaratorSyntax variableDeclarator) + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node) { - var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent; - - if (variableDeclaration.Variables.Count == 1) + if (node is VariableDeclaratorSyntax variableDeclarator) { - ReportDiagnostic(context, variableDeclaration.Parent, CSharpFacts.GetTitle(variableDeclaration.Parent)); + var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent; + + if (variableDeclaration.Variables.Count == 1) + { + ReportDiagnostic(context, variableDeclaration.Parent, CSharpFacts.GetTitle(variableDeclaration.Parent)); + } + else + { + ReportDiagnostic(context, variableDeclarator, CSharpFacts.GetTitle(variableDeclaration.Parent)); + } } else { - ReportDiagnostic(context, variableDeclarator, CSharpFacts.GetTitle(variableDeclaration.Parent)); + ReportDiagnostic(context, node, CSharpFacts.GetTitle(node)); } } - else + + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node, string declarationName) { - ReportDiagnostic(context, node, CSharpFacts.GetTitle(node)); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.RemoveUnusedMemberDeclaration, CSharpUtility.GetIdentifier(node), declarationName); } } - - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node, string declarationName) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.RemoveUnusedMemberDeclaration, CSharpUtility.GetIdentifier(node), declarationName); - } } diff --git a/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberWalker.cs b/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberWalker.cs index 37587a1898..88d131af47 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberWalker.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberWalker.cs @@ -10,526 +10,527 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis.UnusedMember; - -internal class UnusedMemberWalker : CSharpSyntaxNodeWalker +namespace Roslynator.CSharp.Analysis.UnusedMember { - [ThreadStatic] - private static UnusedMemberWalker _cachedInstance; + internal class UnusedMemberWalker : CSharpSyntaxNodeWalker + { + [ThreadStatic] + private static UnusedMemberWalker _cachedInstance; - private bool _isEmpty; + private bool _isEmpty; - private IMethodSymbol _containingMethodSymbol; + private IMethodSymbol _containingMethodSymbol; - public Collection Nodes { get; } = new(); + public Collection Nodes { get; } = new(); - public SemanticModel SemanticModel { get; set; } + public SemanticModel SemanticModel { get; set; } - public CancellationToken CancellationToken { get; set; } + public CancellationToken CancellationToken { get; set; } - public bool IsAnyNodeConst { get; private set; } + public bool IsAnyNodeConst { get; private set; } - public bool IsAnyNodeDelegate { get; private set; } + public bool IsAnyNodeDelegate { get; private set; } - protected override bool ShouldVisit - { - get { return !_isEmpty; } - } + protected override bool ShouldVisit + { + get { return !_isEmpty; } + } - public void Reset() - { - _isEmpty = false; - _containingMethodSymbol = null; - - Nodes.Clear(); - SemanticModel = null; - CancellationToken = default; - IsAnyNodeConst = false; - IsAnyNodeDelegate = false; - } + public void Reset() + { + _isEmpty = false; + _containingMethodSymbol = null; + + Nodes.Clear(); + SemanticModel = null; + CancellationToken = default; + IsAnyNodeConst = false; + IsAnyNodeDelegate = false; + } - public void AddDelegate(string name, SyntaxNode node) - { - AddNode(name, node); + public void AddDelegate(string name, SyntaxNode node) + { + AddNode(name, node); - IsAnyNodeDelegate = true; - } + IsAnyNodeDelegate = true; + } - public void AddNode(string name, SyntaxNode node) - { - Nodes.Add(new NodeSymbolInfo(name, node)); - } + public void AddNode(string name, SyntaxNode node) + { + Nodes.Add(new NodeSymbolInfo(name, node)); + } - public void AddNodes(VariableDeclarationSyntax declaration, bool isConst = false) - { - foreach (VariableDeclaratorSyntax declarator in declaration.Variables) - AddNode(declarator.Identifier.ValueText, declarator); + public void AddNodes(VariableDeclarationSyntax declaration, bool isConst = false) + { + foreach (VariableDeclaratorSyntax declarator in declaration.Variables) + AddNode(declarator.Identifier.ValueText, declarator); - if (isConst) - IsAnyNodeConst = true; - } + if (isConst) + IsAnyNodeConst = true; + } - private void RemoveNodeAt(int index) - { - Nodes.RemoveAt(index); + private void RemoveNodeAt(int index) + { + Nodes.RemoveAt(index); - if (Nodes.Count == 0) - _isEmpty = true; - } + if (Nodes.Count == 0) + _isEmpty = true; + } - private void VisitSimpleName(SimpleNameSyntax node, string name) - { - for (int i = Nodes.Count - 1; i >= 0; i--) + private void VisitSimpleName(SimpleNameSyntax node, string name) { - NodeSymbolInfo info = Nodes[i]; - - if (info.Name == name) + for (int i = Nodes.Count - 1; i >= 0; i--) { - if (info.Symbol == null) - { - ISymbol declaredSymbol = SemanticModel.GetDeclaredSymbol(info.Node, CancellationToken); - - Debug.Assert(declaredSymbol != null, ""); + NodeSymbolInfo info = Nodes[i]; - if (declaredSymbol == null) + if (info.Name == name) + { + if (info.Symbol is null) { - RemoveNodeAt(i); - continue; - } + ISymbol declaredSymbol = SemanticModel.GetDeclaredSymbol(info.Node, CancellationToken); - info = new NodeSymbolInfo(info.Name, info.Node, declaredSymbol); + Debug.Assert(declaredSymbol is not null, ""); - Nodes[i] = info; - } + if (declaredSymbol is null) + { + RemoveNodeAt(i); + continue; + } - SymbolInfo symbolInfo = SemanticModel.GetSymbolInfo(node, CancellationToken); + info = new NodeSymbolInfo(info.Name, info.Node, declaredSymbol); - if (symbolInfo.Symbol != null) - { - ISymbol symbol = symbolInfo.Symbol; + Nodes[i] = info; + } - if (symbol.Kind == SymbolKind.Method) + SymbolInfo symbolInfo = SemanticModel.GetSymbolInfo(node, CancellationToken); + + if (symbolInfo.Symbol is not null) { - var methodSymbol = ((IMethodSymbol)symbol); + ISymbol symbol = symbolInfo.Symbol; - if (methodSymbol.MethodKind == MethodKind.ReducedExtension) - symbol = methodSymbol.ReducedFrom; - } + if (symbol.Kind == SymbolKind.Method) + { + var methodSymbol = ((IMethodSymbol)symbol); + + if (methodSymbol.MethodKind == MethodKind.ReducedExtension) + symbol = methodSymbol.ReducedFrom; + } - symbol = symbol.OriginalDefinition; + symbol = symbol.OriginalDefinition; - if (SymbolEqualityComparer.Default.Equals(info.Symbol, symbol) - && !SymbolEqualityComparer.Default.Equals(_containingMethodSymbol, symbol)) + if (SymbolEqualityComparer.Default.Equals(info.Symbol, symbol) + && !SymbolEqualityComparer.Default.Equals(_containingMethodSymbol, symbol)) + { + RemoveNodeAt(i); + } + } + else if (symbolInfo.CandidateReason == CandidateReason.LateBound) { RemoveNodeAt(i); } - } - else if (symbolInfo.CandidateReason == CandidateReason.LateBound) - { - RemoveNodeAt(i); - } - else if (symbolInfo.CandidateReason == CandidateReason.MemberGroup - || symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure) - { - ImmutableArray candidateSymbols = symbolInfo.CandidateSymbols; - - for (int j = 0; j < candidateSymbols.Length; j++) + else if (symbolInfo.CandidateReason == CandidateReason.MemberGroup + || symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure) { - ISymbol symbol = candidateSymbols[j].OriginalDefinition; + ImmutableArray candidateSymbols = symbolInfo.CandidateSymbols; - if (SymbolEqualityComparer.Default.Equals(info.Symbol, symbol) - && !SymbolEqualityComparer.Default.Equals(_containingMethodSymbol, symbol)) + for (int j = 0; j < candidateSymbols.Length; j++) { - RemoveNodeAt(i); + ISymbol symbol = candidateSymbols[j].OriginalDefinition; + + if (SymbolEqualityComparer.Default.Equals(info.Symbol, symbol) + && !SymbolEqualityComparer.Default.Equals(_containingMethodSymbol, symbol)) + { + RemoveNodeAt(i); + } } } } } } - } - public override void VisitGenericName(GenericNameSyntax node) - { - VisitSimpleName(node, node.Identifier.ValueText); + public override void VisitGenericName(GenericNameSyntax node) + { + VisitSimpleName(node, node.Identifier.ValueText); - if (IsAnyNodeDelegate) - VisitTypeArgumentList(node.TypeArgumentList); - } + if (IsAnyNodeDelegate) + VisitTypeArgumentList(node.TypeArgumentList); + } - public override void VisitIdentifierName(IdentifierNameSyntax node) - { - VisitSimpleName(node, node.Identifier.ValueText); - } + public override void VisitIdentifierName(IdentifierNameSyntax node) + { + VisitSimpleName(node, node.Identifier.ValueText); + } - public override void VisitTypeArgumentList(TypeArgumentListSyntax node) - { - foreach (TypeSyntax type in node.Arguments) + public override void VisitTypeArgumentList(TypeArgumentListSyntax node) { - if (!ShouldVisit) - return; + foreach (TypeSyntax type in node.Arguments) + { + if (!ShouldVisit) + return; - VisitType(type); + VisitType(type); + } } - } - - protected override void VisitType(TypeSyntax node) - { - if (IsAnyNodeDelegate) - base.VisitType(node); - } - public override void VisitGotoStatement(GotoStatementSyntax node) - { - } + protected override void VisitType(TypeSyntax node) + { + if (IsAnyNodeDelegate) + base.VisitType(node); + } - public override void VisitLiteralExpression(LiteralExpressionSyntax node) - { - } + public override void VisitGotoStatement(GotoStatementSyntax node) + { + } - public override void VisitNameColon(NameColonSyntax node) - { - } + public override void VisitLiteralExpression(LiteralExpressionSyntax node) + { + } - public override void VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) - { - Debug.Fail($"{nameof(UnusedMemberWalker)}.{nameof(VisitExplicitInterfaceSpecifier)}"); - } + public override void VisitNameColon(NameColonSyntax node) + { + } - public override void VisitTypeParameterList(TypeParameterListSyntax node) - { - Debug.Fail($"{nameof(UnusedMemberWalker)}.{nameof(VisitTypeParameterList)}"); - } + public override void VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) + { + Debug.Fail($"{nameof(UnusedMemberWalker)}.{nameof(VisitExplicitInterfaceSpecifier)}"); + } - public override void VisitBaseList(BaseListSyntax node) - { - Debug.Fail($"{nameof(UnusedMemberWalker)}.{nameof(VisitBaseList)}"); - } + public override void VisitTypeParameterList(TypeParameterListSyntax node) + { + Debug.Fail($"{nameof(UnusedMemberWalker)}.{nameof(VisitTypeParameterList)}"); + } - public override void VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) - { - Debug.Fail($"{nameof(UnusedMemberWalker)}.{nameof(VisitTypeParameterConstraintClause)}"); - } + public override void VisitBaseList(BaseListSyntax node) + { + Debug.Fail($"{nameof(UnusedMemberWalker)}.{nameof(VisitBaseList)}"); + } - public override void VisitParameterList(ParameterListSyntax node) - { - if (node != null) - base.VisitParameterList(node); - } + public override void VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) + { + Debug.Fail($"{nameof(UnusedMemberWalker)}.{nameof(VisitTypeParameterConstraintClause)}"); + } - public override void VisitCompilationUnit(CompilationUnitSyntax node) - { - VisitMembers(node.Members); - } + public override void VisitParameterList(ParameterListSyntax node) + { + if (node is not null) + base.VisitParameterList(node); + } - public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) - { - VisitMembers(node.Members); - } + public override void VisitCompilationUnit(CompilationUnitSyntax node) + { + VisitMembers(node.Members); + } - public override void VisitClassDeclaration(ClassDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); - VisitMembers(node.Members); - } + public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + VisitMembers(node.Members); + } - public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); - VisitMembers(node.Members); - } + public override void VisitClassDeclaration(ClassDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); + VisitMembers(node.Members); + } - public override void VisitStructDeclaration(StructDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); - VisitMembers(node.Members); - } + public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); + VisitMembers(node.Members); + } - public override void VisitRecordDeclaration(RecordDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); - VisitMembers(node.Members); - } + public override void VisitStructDeclaration(StructDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); + VisitMembers(node.Members); + } - public override void VisitDelegateDeclaration(DelegateDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); + public override void VisitRecordDeclaration(RecordDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); + VisitMembers(node.Members); + } - if (!ShouldVisit) - return; + public override void VisitDelegateDeclaration(DelegateDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); - TypeSyntax returnType = node.ReturnType; + if (!ShouldVisit) + return; - if (returnType != null) - VisitType(returnType); + TypeSyntax returnType = node.ReturnType; - if (!ShouldVisit) - return; + if (returnType is not null) + VisitType(returnType); - VisitParameterList(node.ParameterList); - } + if (!ShouldVisit) + return; - public override void VisitEventDeclaration(EventDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); + VisitParameterList(node.ParameterList); + } - if (!ShouldVisit) - return; + public override void VisitEventDeclaration(EventDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); - TypeSyntax type = node.Type; + if (!ShouldVisit) + return; - if (type != null) - VisitType(type); + TypeSyntax type = node.Type; - if (!ShouldVisit) - return; + if (type is not null) + VisitType(type); - AccessorListSyntax accessorList = node.AccessorList; + if (!ShouldVisit) + return; - if (accessorList != null) - VisitAccessorList(accessorList); - } + AccessorListSyntax accessorList = node.AccessorList; - public override void VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); - } + if (accessorList is not null) + VisitAccessorList(accessorList); + } - public override void VisitEnumDeclaration(EnumDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); + public override void VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); + } - if (IsAnyNodeConst) + public override void VisitEnumDeclaration(EnumDeclarationSyntax node) { - foreach (EnumMemberDeclarationSyntax member in node.Members) + VisitAttributeLists(node.AttributeLists); + + if (IsAnyNodeConst) { - if (!ShouldVisit) - return; + foreach (EnumMemberDeclarationSyntax member in node.Members) + { + if (!ShouldVisit) + return; - VisitEnumMemberDeclaration(member); + VisitEnumMemberDeclaration(member); + } } } - } - public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); + public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - TypeSyntax type = node.Type; + TypeSyntax type = node.Type; - if (type != null) - VisitType(type); + if (type is not null) + VisitType(type); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - EqualsValueClauseSyntax initializer = node.Initializer; + EqualsValueClauseSyntax initializer = node.Initializer; - if (initializer != null) - VisitEqualsValueClause(initializer); + if (initializer is not null) + VisitEqualsValueClause(initializer); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - AccessorListSyntax accessorList = node.AccessorList; + AccessorListSyntax accessorList = node.AccessorList; - if (accessorList != null) - { - VisitAccessorList(accessorList); - } - else - { - ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; + if (accessorList is not null) + { + VisitAccessorList(accessorList); + } + else + { + ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; - if (expressionBody != null) - VisitArrowExpressionClause(expressionBody); + if (expressionBody is not null) + VisitArrowExpressionClause(expressionBody); + } } - } - public override void VisitIndexerDeclaration(IndexerDeclarationSyntax node) - { - VisitAttributeLists(node.AttributeLists); + public override void VisitIndexerDeclaration(IndexerDeclarationSyntax node) + { + VisitAttributeLists(node.AttributeLists); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - TypeSyntax type = node.Type; + TypeSyntax type = node.Type; - if (type != null) - VisitType(type); + if (type is not null) + VisitType(type); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - BracketedParameterListSyntax parameterList = node.ParameterList; + BracketedParameterListSyntax parameterList = node.ParameterList; - if (node != null) - VisitBracketedParameterList(parameterList); + if (node is not null) + VisitBracketedParameterList(parameterList); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - AccessorListSyntax accessorList = node.AccessorList; + AccessorListSyntax accessorList = node.AccessorList; - if (accessorList != null) - { - VisitAccessorList(accessorList); - } - else - { - ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; + if (accessorList is not null) + { + VisitAccessorList(accessorList); + } + else + { + ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; - if (expressionBody != null) - VisitArrowExpressionClause(expressionBody); + if (expressionBody is not null) + VisitArrowExpressionClause(expressionBody); + } } - } - public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) - { - TypeSyntax returnType = node.ReturnType; - - if (returnType != null) - VisitType(returnType); + public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + TypeSyntax returnType = node.ReturnType; - if (!ShouldVisit) - return; + if (returnType is not null) + VisitType(returnType); - VisitParameterList(node.ParameterList); + if (!ShouldVisit) + return; - if (!ShouldVisit) - return; + VisitParameterList(node.ParameterList); - BlockSyntax body = node.Body; + if (!ShouldVisit) + return; - if (body != null) - { - VisitBlock(body); - } - else - { - ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; + BlockSyntax body = node.Body; - if (expressionBody != null) + if (body is not null) { - VisitArrowExpressionClause(expressionBody); + VisitBlock(body); + } + else + { + ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; + + if (expressionBody is not null) + { + VisitArrowExpressionClause(expressionBody); + } } } - } - public override void VisitMethodDeclaration(MethodDeclarationSyntax node) - { - Debug.Assert(_containingMethodSymbol == null); + public override void VisitMethodDeclaration(MethodDeclarationSyntax node) + { + Debug.Assert(_containingMethodSymbol is null); - _containingMethodSymbol = SemanticModel.GetDeclaredSymbol(node, CancellationToken); + _containingMethodSymbol = SemanticModel.GetDeclaredSymbol(node, CancellationToken); - VisitAttributeLists(node.AttributeLists); + VisitAttributeLists(node.AttributeLists); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - TypeSyntax returnType = node.ReturnType; + TypeSyntax returnType = node.ReturnType; - if (returnType != null) - VisitType(returnType); + if (returnType is not null) + VisitType(returnType); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - VisitParameterList(node.ParameterList); + VisitParameterList(node.ParameterList); - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - BlockSyntax body = node.Body; + BlockSyntax body = node.Body; - if (body != null) - { - VisitBlock(body); - } - else - { - ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; - - if (expressionBody != null) + if (body is not null) { - VisitArrowExpressionClause(expressionBody); + VisitBlock(body); } - } + else + { + ArrowExpressionClauseSyntax expressionBody = node.ExpressionBody; - _containingMethodSymbol = null; - } + if (expressionBody is not null) + { + VisitArrowExpressionClause(expressionBody); + } + } - public override void VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) - { - TypeSyntax type = node.Type; + _containingMethodSymbol = null; + } - if (type != null) + public override void VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) { - if (type.IsKind(SyntaxKind.ArrayType)) - { - VisitArrayType((ArrayTypeSyntax)type); - } - else + TypeSyntax type = node.Type; + + if (type is not null) { - VisitType(type); + if (type.IsKind(SyntaxKind.ArrayType)) + { + VisitArrayType((ArrayTypeSyntax)type); + } + else + { + VisitType(type); + } } - } - if (!ShouldVisit) - return; + if (!ShouldVisit) + return; - InitializerExpressionSyntax initializer = node.Initializer; + InitializerExpressionSyntax initializer = node.Initializer; - if (initializer != null) - VisitInitializerExpression(initializer); - } + if (initializer is not null) + VisitInitializerExpression(initializer); + } - private void VisitMembers(SyntaxList members) - { - foreach (MemberDeclarationSyntax memberDeclaration in members) + private void VisitMembers(SyntaxList members) { - if (!ShouldVisit) - return; + foreach (MemberDeclarationSyntax memberDeclaration in members) + { + if (!ShouldVisit) + return; - VisitMemberDeclaration(memberDeclaration); + VisitMemberDeclaration(memberDeclaration); + } } - } - private void VisitAttributeLists(SyntaxList attributeLists) - { - foreach (AttributeListSyntax attributeList in attributeLists) + private void VisitAttributeLists(SyntaxList attributeLists) { - if (!ShouldVisit) - return; + foreach (AttributeListSyntax attributeList in attributeLists) + { + if (!ShouldVisit) + return; - VisitAttributeList(attributeList); + VisitAttributeList(attributeList); + } } - } - - public static UnusedMemberWalker GetInstance() - { - UnusedMemberWalker walker = _cachedInstance; - if (walker != null) + public static UnusedMemberWalker GetInstance() { - Debug.Assert(walker._containingMethodSymbol == null); - Debug.Assert(walker.Nodes.Count == 0); - Debug.Assert(walker.SemanticModel == null); - Debug.Assert(walker.CancellationToken == default); + UnusedMemberWalker walker = _cachedInstance; - _cachedInstance = null; - return walker; - } + if (walker is not null) + { + Debug.Assert(walker._containingMethodSymbol is null); + Debug.Assert(walker.Nodes.Count == 0); + Debug.Assert(walker.SemanticModel is null); + Debug.Assert(walker.CancellationToken == default); - return new UnusedMemberWalker(); - } + _cachedInstance = null; + return walker; + } - public static void Free(UnusedMemberWalker walker) - { - walker.Reset(); + return new UnusedMemberWalker(); + } + + public static void Free(UnusedMemberWalker walker) + { + walker.Reset(); - _cachedInstance = walker; + _cachedInstance = walker; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterAnalyzer.cs index 7f7d9a9beb..0762246b38 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterAnalyzer.cs @@ -11,452 +11,453 @@ using Roslynator.CSharp.Syntax; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis.UnusedParameter; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UnusedParameterAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis.UnusedParameter { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UnusedParameterAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize( - ref _supportedDiagnostics, - DiagnosticRules.UnusedParameter, - DiagnosticRules.UnusedThisParameter, - DiagnosticRules.UnusedTypeParameter); - } + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize( + ref _supportedDiagnostics, + DiagnosticRules.UnusedParameter, + DiagnosticRules.UnusedThisParameter, + DiagnosticRules.UnusedTypeParameter); + } - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterSyntaxNodeAction(f => AnalyzeConstructorDeclaration(f), SyntaxKind.ConstructorDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeOperatorDeclaration(f), SyntaxKind.OperatorDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeConversionOperatorDeclaration(f), SyntaxKind.ConversionOperatorDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeIndexerDeclaration(f), SyntaxKind.IndexerDeclaration); - - context.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); - context.RegisterSyntaxNodeAction(f => AnalyzeSimpleLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); - context.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); - context.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); - } - - private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext context) - { - var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node; + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); + + context.RegisterSyntaxNodeAction(f => AnalyzeConstructorDeclaration(f), SyntaxKind.ConstructorDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeOperatorDeclaration(f), SyntaxKind.OperatorDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeConversionOperatorDeclaration(f), SyntaxKind.ConversionOperatorDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeIndexerDeclaration(f), SyntaxKind.IndexerDeclaration); + + context.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); + context.RegisterSyntaxNodeAction(f => AnalyzeSimpleLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); + context.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); + context.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); + } - if (constructorDeclaration.ContainsDiagnostics) - return; + private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext context) + { + var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node; - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(constructorDeclaration); + if (constructorDeclaration.ContainsDiagnostics) + return; - if (!parameterInfo.Success) - return; + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(constructorDeclaration); - if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) - return; + if (!parameterInfo.Success) + return; - // Skip a constructor that is required by ISerializable interface - if (parameterInfo.Parameters.Count == 2) - { - IMethodSymbol symbol = context.SemanticModel.GetDeclaredSymbol(constructorDeclaration, context.CancellationToken); + if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) + return; - if (symbol != null) + // Skip a constructor that is required by ISerializable interface + if (parameterInfo.Parameters.Count == 2) { - ImmutableArray parameters = symbol.Parameters; + IMethodSymbol symbol = context.SemanticModel.GetDeclaredSymbol(constructorDeclaration, context.CancellationToken); - if (parameters.Length == 2 - && parameters[0].Type.HasMetadataName(MetadataNames.System_Runtime_Serialization_SerializationInfo) - && parameters[1].Type.HasMetadataName(MetadataNames.System_Runtime_Serialization_StreamingContext)) + if (symbol is not null) { - return; + ImmutableArray parameters = symbol.Parameters; + + if (parameters.Length == 2 + && parameters[0].Type.HasMetadataName(MetadataNames.System_Runtime_Serialization_SerializationInfo) + && parameters[1].Type.HasMetadataName(MetadataNames.System_Runtime_Serialization_StreamingContext)) + { + return; + } } } - } - Analyze(context, parameterInfo); - } + Analyze(context, parameterInfo); + } - private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) - { - var methodDeclaration = (MethodDeclarationSyntax)context.Node; + private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) + { + var methodDeclaration = (MethodDeclarationSyntax)context.Node; - if (methodDeclaration.ContainsDiagnostics) - return; + if (methodDeclaration.ContainsDiagnostics) + return; - if (!methodDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration)) - return; + if (!methodDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration)) + return; - if (methodDeclaration.Modifiers.ContainsAny( - SyntaxKind.AbstractKeyword, - SyntaxKind.VirtualKeyword, - SyntaxKind.OverrideKeyword, - SyntaxKind.PartialKeyword)) - { - return; - } + if (methodDeclaration.Modifiers.ContainsAny( + SyntaxKind.AbstractKeyword, + SyntaxKind.VirtualKeyword, + SyntaxKind.OverrideKeyword, + SyntaxKind.PartialKeyword)) + { + return; + } - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(methodDeclaration); + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(methodDeclaration); - if (!parameterInfo.Success) - return; + if (!parameterInfo.Success) + return; - if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) - return; + if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) + return; - IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclaration, context.CancellationToken); + IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclaration, context.CancellationToken); - if (methodSymbol == null) - return; + if (methodSymbol is null) + return; - if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) - return; + if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) + return; - if (!methodSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty) - return; + if (!methodSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty) + return; - if (methodSymbol.ImplementsInterfaceMember(allInterfaces: true)) - return; + if (methodSymbol.ImplementsInterfaceMember(allInterfaces: true)) + return; - UnusedParameterWalker walker = null; + UnusedParameterWalker walker = null; - try - { - walker = UnusedParameterWalker.GetInstance(); + try + { + walker = UnusedParameterWalker.GetInstance(); - walker.SetValues(context.SemanticModel, context.CancellationToken); + walker.SetValues(context.SemanticModel, context.CancellationToken); - FindUnusedNodes(parameterInfo, walker); + FindUnusedNodes(parameterInfo, walker); - if (walker.Nodes.Count > 0 - && !MethodReferencedAsMethodGroupWalker.IsReferencedAsMethodGroup(methodDeclaration, methodSymbol, context.SemanticModel, context.CancellationToken)) + if (walker.Nodes.Count > 0 + && !MethodReferencedAsMethodGroupWalker.IsReferencedAsMethodGroup(methodDeclaration, methodSymbol, context.SemanticModel, context.CancellationToken)) + { + foreach (KeyValuePair kvp in walker.Nodes) + ReportDiagnostic(context, kvp.Value.Node); + } + } + finally { - foreach (KeyValuePair kvp in walker.Nodes) - ReportDiagnostic(context, kvp.Value.Node); + if (walker is not null) + UnusedParameterWalker.Free(walker); } } - finally - { - if (walker != null) - UnusedParameterWalker.Free(walker); - } - } - - private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context) - { - var operatorDeclaration = (OperatorDeclarationSyntax)context.Node; - if (operatorDeclaration.ContainsDiagnostics) - return; + private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context) + { + var operatorDeclaration = (OperatorDeclarationSyntax)context.Node; - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(operatorDeclaration); + if (operatorDeclaration.ContainsDiagnostics) + return; - if (!parameterInfo.Success) - return; + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(operatorDeclaration); - if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) - return; + if (!parameterInfo.Success) + return; - Analyze(context, parameterInfo); - } + if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) + return; - private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisContext context) - { - var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)context.Node; + Analyze(context, parameterInfo); + } - if (conversionOperatorDeclaration.ContainsDiagnostics) - return; + private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisContext context) + { + var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)context.Node; - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(conversionOperatorDeclaration); + if (conversionOperatorDeclaration.ContainsDiagnostics) + return; - if (!parameterInfo.Success) - return; + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(conversionOperatorDeclaration); - if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) - return; + if (!parameterInfo.Success) + return; - Analyze(context, parameterInfo); - } + if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) + return; - private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) - { - var indexerDeclaration = (IndexerDeclarationSyntax)context.Node; + Analyze(context, parameterInfo); + } - if (indexerDeclaration.ContainsDiagnostics) - return; + private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) + { + var indexerDeclaration = (IndexerDeclarationSyntax)context.Node; - if (!indexerDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration)) - return; + if (indexerDeclaration.ContainsDiagnostics) + return; - if (indexerDeclaration.Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) - return; + if (!indexerDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration)) + return; - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(indexerDeclaration); + if (indexerDeclaration.Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) + return; - if (!parameterInfo.Success) - return; + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(indexerDeclaration); - if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) - return; + if (!parameterInfo.Success) + return; - IPropertySymbol propertySymbol = context.SemanticModel.GetDeclaredSymbol(indexerDeclaration, context.CancellationToken); + if (ContainsOnlyThrowNewExpression(parameterInfo.Body)) + return; - if (propertySymbol?.ExplicitInterfaceImplementations.IsDefaultOrEmpty != true) - return; + IPropertySymbol propertySymbol = context.SemanticModel.GetDeclaredSymbol(indexerDeclaration, context.CancellationToken); - if (propertySymbol.ImplementsInterfaceMember(allInterfaces: true)) - return; + if (propertySymbol?.ExplicitInterfaceImplementations.IsDefaultOrEmpty != true) + return; - Analyze(context, parameterInfo, isIndexer: true); - } + if (propertySymbol.ImplementsInterfaceMember(allInterfaces: true)) + return; - private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) - { - var localFunctionStatement = (LocalFunctionStatementSyntax)context.Node; + Analyze(context, parameterInfo, isIndexer: true); + } - if (localFunctionStatement.ContainsDiagnostics) - return; + private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) + { + var localFunctionStatement = (LocalFunctionStatementSyntax)context.Node; - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(localFunctionStatement); + if (localFunctionStatement.ContainsDiagnostics) + return; - if (!parameterInfo.Success) - return; + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(localFunctionStatement); - IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(localFunctionStatement, context.CancellationToken); + if (!parameterInfo.Success) + return; - if (methodSymbol == null) - return; + IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(localFunctionStatement, context.CancellationToken); - if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) - return; + if (methodSymbol is null) + return; - Analyze(context, parameterInfo); - } + if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) + return; - private static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) - { - var lambda = (SimpleLambdaExpressionSyntax)context.Node; + Analyze(context, parameterInfo); + } - if (lambda.ContainsDiagnostics) - return; + private static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) + { + var lambda = (SimpleLambdaExpressionSyntax)context.Node; - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(lambda); + if (lambda.ContainsDiagnostics) + return; - if (!parameterInfo.Success) - return; + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(lambda); - var methodSymbol = (IMethodSymbol)context.SemanticModel.GetSymbol(lambda, context.CancellationToken); + if (!parameterInfo.Success) + return; - if (methodSymbol == null) - return; + var methodSymbol = (IMethodSymbol)context.SemanticModel.GetSymbol(lambda, context.CancellationToken); - if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) - return; + if (methodSymbol is null) + return; - Analyze(context, parameterInfo); - } + if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) + return; - private static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisContext context) - { - var lambda = (ParenthesizedLambdaExpressionSyntax)context.Node; + Analyze(context, parameterInfo); + } - if (lambda.ContainsDiagnostics) - return; + private static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisContext context) + { + var lambda = (ParenthesizedLambdaExpressionSyntax)context.Node; - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(lambda); + if (lambda.ContainsDiagnostics) + return; - if (!parameterInfo.Success) - return; + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(lambda); - var methodSymbol = (IMethodSymbol)context.SemanticModel.GetSymbol(lambda, context.CancellationToken); + if (!parameterInfo.Success) + return; - if (methodSymbol == null) - return; + var methodSymbol = (IMethodSymbol)context.SemanticModel.GetSymbol(lambda, context.CancellationToken); - if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) - return; + if (methodSymbol is null) + return; - Analyze(context, parameterInfo); - } + if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) + return; - private static void AnalyzeAnonymousMethodExpression(SyntaxNodeAnalysisContext context) - { - var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node; + Analyze(context, parameterInfo); + } - if (anonymousMethod.ContainsDiagnostics) - return; + private static void AnalyzeAnonymousMethodExpression(SyntaxNodeAnalysisContext context) + { + var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node; - ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(anonymousMethod); + if (anonymousMethod.ContainsDiagnostics) + return; - if (!parameterInfo.Success) - return; + ParameterInfo parameterInfo = SyntaxInfo.ParameterInfo(anonymousMethod); - var methodSymbol = (IMethodSymbol)context.SemanticModel.GetSymbol(anonymousMethod, context.CancellationToken); + if (!parameterInfo.Success) + return; - if (methodSymbol == null) - return; + var methodSymbol = (IMethodSymbol)context.SemanticModel.GetSymbol(anonymousMethod, context.CancellationToken); - if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) - return; + if (methodSymbol is null) + return; - Analyze(context, parameterInfo); - } + if (SymbolUtility.IsEventHandlerMethod(methodSymbol)) + return; - private static void Analyze(SyntaxNodeAnalysisContext context, in ParameterInfo parameterInfo, bool isIndexer = false) - { - UnusedParameterWalker walker = null; + Analyze(context, parameterInfo); + } - try + private static void Analyze(SyntaxNodeAnalysisContext context, in ParameterInfo parameterInfo, bool isIndexer = false) { - walker = UnusedParameterWalker.GetInstance(); - walker.SetValues(context.SemanticModel, context.CancellationToken, isIndexer); + UnusedParameterWalker walker = null; - FindUnusedNodes(parameterInfo, walker); + try + { + walker = UnusedParameterWalker.GetInstance(); + walker.SetValues(context.SemanticModel, context.CancellationToken, isIndexer); - foreach (KeyValuePair kvp in walker.Nodes) - ReportDiagnostic(context, kvp.Value.Node); - } - finally - { - if (walker != null) - UnusedParameterWalker.Free(walker); - } - } + FindUnusedNodes(parameterInfo, walker); - private static void FindUnusedNodes(in ParameterInfo parameterInfo, UnusedParameterWalker walker) - { - if (parameterInfo.Parameter != null - && !IsArgListOrDiscard(parameterInfo.Parameter)) - { - walker.AddParameter(parameterInfo.Parameter); - } - else - { - foreach (ParameterSyntax parameter in parameterInfo.Parameters) + foreach (KeyValuePair kvp in walker.Nodes) + ReportDiagnostic(context, kvp.Value.Node); + } + finally { - if (!IsArgListOrDiscard(parameter)) - walker.AddParameter(parameter); + if (walker is not null) + UnusedParameterWalker.Free(walker); } } - foreach (TypeParameterSyntax typeParameter in parameterInfo.TypeParameters) + private static void FindUnusedNodes(in ParameterInfo parameterInfo, UnusedParameterWalker walker) { - walker.AddTypeParameter(typeParameter); - walker.IsAnyTypeParameter = true; - } + if (parameterInfo.Parameter is not null + && !IsArgListOrDiscard(parameterInfo.Parameter)) + { + walker.AddParameter(parameterInfo.Parameter); + } + else + { + foreach (ParameterSyntax parameter in parameterInfo.Parameters) + { + if (!IsArgListOrDiscard(parameter)) + walker.AddParameter(parameter); + } + } - if (walker.Nodes.Count > 0) - walker.Visit(parameterInfo.Node); - } + foreach (TypeParameterSyntax typeParameter in parameterInfo.TypeParameters) + { + walker.AddTypeParameter(typeParameter); + walker.IsAnyTypeParameter = true; + } - private static bool IsArgListOrDiscard(ParameterSyntax parameter) - { - return parameter.Identifier.IsKind(SyntaxKind.ArgListKeyword) - || IsDiscardName(parameter.Identifier.ValueText); - } + if (walker.Nodes.Count > 0) + walker.Visit(parameterInfo.Node); + } - private static bool IsDiscardName(string value) - { - if (value.Length > 0 - && value[0] == '_') + private static bool IsArgListOrDiscard(ParameterSyntax parameter) { - if (value.Length == 1) - return true; + return parameter.Identifier.IsKind(SyntaxKind.ArgListKeyword) + || IsDiscardName(parameter.Identifier.ValueText); + } - if (value[1] == '_') + private static bool IsDiscardName(string value) + { + if (value.Length > 0 + && value[0] == '_') { - for (int i = 2; i < value.Length; i++) + if (value.Length == 1) + return true; + + if (value[1] == '_') { - if (value[i] != '_') - return false; + for (int i = 2; i < value.Length; i++) + { + if (value[i] != '_') + return false; + } + + return true; } - return true; + return uint.TryParse(value.Substring(1), out _); } - return uint.TryParse(value.Substring(1), out _); + return false; } - return false; - } - - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node) - { - if (node is ParameterSyntax parameter) + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node) { - if (parameter.Modifiers.Contains(SyntaxKind.ThisKeyword)) + if (node is ParameterSyntax parameter) + { + if (parameter.Modifiers.Contains(SyntaxKind.ThisKeyword)) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnusedThisParameter, parameter, parameter.Identifier.ValueText); + } + else + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnusedParameter, parameter, parameter.Identifier.ValueText); + } + } + else if (node is TypeParameterSyntax typeParameter) { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnusedThisParameter, parameter, parameter.Identifier.ValueText); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnusedTypeParameter, typeParameter, typeParameter.Identifier.ValueText); } else { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnusedParameter, parameter, parameter.Identifier.ValueText); + SyntaxDebug.Fail(node); } } - else if (node is TypeParameterSyntax typeParameter) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UnusedTypeParameter, typeParameter, typeParameter.Identifier.ValueText); - } - else - { - SyntaxDebug.Fail(node); - } - } - private static bool ContainsOnlyThrowNewExpression(CSharpSyntaxNode node) - { - switch (node?.Kind()) + private static bool ContainsOnlyThrowNewExpression(CSharpSyntaxNode node) { - case SyntaxKind.Block: - return ContainsOnlyThrowNewExpression((BlockSyntax)node); - case SyntaxKind.ArrowExpressionClause: - return ContainsOnlyThrowNewExpression((ArrowExpressionClauseSyntax)node); - case SyntaxKind.AccessorList: - { - return ((AccessorListSyntax)node) - .Accessors - .All(f => ContainsOnlyThrowNewExpression(f.BodyOrExpressionBody())); - } + switch (node?.Kind()) + { + case SyntaxKind.Block: + return ContainsOnlyThrowNewExpression((BlockSyntax)node); + case SyntaxKind.ArrowExpressionClause: + return ContainsOnlyThrowNewExpression((ArrowExpressionClauseSyntax)node); + case SyntaxKind.AccessorList: + { + return ((AccessorListSyntax)node) + .Accessors + .All(f => ContainsOnlyThrowNewExpression(f.BodyOrExpressionBody())); + } + } + + return false; } - return false; - } + private static bool ContainsOnlyThrowNewExpression(BlockSyntax body) + { + StatementSyntax statement = body?.Statements.SingleOrDefault(shouldThrow: false); - private static bool ContainsOnlyThrowNewExpression(BlockSyntax body) - { - StatementSyntax statement = body?.Statements.SingleOrDefault(shouldThrow: false); + if (statement?.Kind() == SyntaxKind.ThrowStatement) + { + var throwStatement = (ThrowStatementSyntax)statement; - if (statement?.Kind() == SyntaxKind.ThrowStatement) - { - var throwStatement = (ThrowStatementSyntax)statement; + return throwStatement.Expression?.Kind() == SyntaxKind.ObjectCreationExpression; + } - return throwStatement.Expression?.Kind() == SyntaxKind.ObjectCreationExpression; + return false; } - return false; - } + private static bool ContainsOnlyThrowNewExpression(ArrowExpressionClauseSyntax expressionBody) + { + ExpressionSyntax expression = expressionBody?.Expression; - private static bool ContainsOnlyThrowNewExpression(ArrowExpressionClauseSyntax expressionBody) - { - ExpressionSyntax expression = expressionBody?.Expression; + if (expression?.Kind() == SyntaxKind.ThrowExpression) + { + var throwExpression = (ThrowExpressionSyntax)expression; - if (expression?.Kind() == SyntaxKind.ThrowExpression) - { - var throwExpression = (ThrowExpressionSyntax)expression; + return throwExpression.Expression?.Kind() == SyntaxKind.ObjectCreationExpression; + } - return throwExpression.Expression?.Kind() == SyntaxKind.ObjectCreationExpression; + return false; } - - return false; } } diff --git a/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterWalker.cs b/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterWalker.cs index e08db7f127..3c3eef895d 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterWalker.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterWalker.cs @@ -9,213 +9,214 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis.UnusedParameter; - -internal class UnusedParameterWalker : CSharpSyntaxNodeWalker +namespace Roslynator.CSharp.Analysis.UnusedParameter { - [ThreadStatic] - private static UnusedParameterWalker _cachedInstance; + internal class UnusedParameterWalker : CSharpSyntaxNodeWalker + { + [ThreadStatic] + private static UnusedParameterWalker _cachedInstance; - private static readonly StringComparer _ordinalComparer = StringComparer.Ordinal; + private static readonly StringComparer _ordinalComparer = StringComparer.Ordinal; - private bool _isEmpty; + private bool _isEmpty; - public Dictionary Nodes { get; } = new(_ordinalComparer); + public Dictionary Nodes { get; } = new(_ordinalComparer); - public SemanticModel SemanticModel { get; set; } + public SemanticModel SemanticModel { get; set; } - public CancellationToken CancellationToken { get; set; } + public CancellationToken CancellationToken { get; set; } - public bool IsIndexer { get; set; } + public bool IsIndexer { get; set; } - public bool IsAnyTypeParameter { get; set; } + public bool IsAnyTypeParameter { get; set; } - protected override bool ShouldVisit => !_isEmpty; + protected override bool ShouldVisit => !_isEmpty; - public void SetValues(SemanticModel semanticModel, CancellationToken cancellationToken, bool isIndexer = false) - { - _isEmpty = false; + public void SetValues(SemanticModel semanticModel, CancellationToken cancellationToken, bool isIndexer = false) + { + _isEmpty = false; - Nodes.Clear(); - SemanticModel = semanticModel; - CancellationToken = cancellationToken; - IsIndexer = isIndexer; - IsAnyTypeParameter = false; - } + Nodes.Clear(); + SemanticModel = semanticModel; + CancellationToken = cancellationToken; + IsIndexer = isIndexer; + IsAnyTypeParameter = false; + } - public void AddParameter(ParameterSyntax parameter) - { - AddNode(parameter.Identifier.ValueText, parameter); - } + public void AddParameter(ParameterSyntax parameter) + { + AddNode(parameter.Identifier.ValueText, parameter); + } - public void AddTypeParameter(TypeParameterSyntax typeParameter) - { - AddNode(typeParameter.Identifier.ValueText, typeParameter); - } + public void AddTypeParameter(TypeParameterSyntax typeParameter) + { + AddNode(typeParameter.Identifier.ValueText, typeParameter); + } - private void AddNode(string name, SyntaxNode node) - { - Nodes[name] = new NodeSymbolInfo(name, node); - } + private void AddNode(string name, SyntaxNode node) + { + Nodes[name] = new NodeSymbolInfo(name, node); + } - private void RemoveNode(string name) - { - Nodes.Remove(name); + private void RemoveNode(string name) + { + Nodes.Remove(name); - if (Nodes.Count == 0) - _isEmpty = true; - } + if (Nodes.Count == 0) + _isEmpty = true; + } - protected override void VisitType(TypeSyntax node) - { - switch (node.Kind()) + protected override void VisitType(TypeSyntax node) { - case SyntaxKind.ArrayType: - { - VisitArrayType((ArrayTypeSyntax)node); - break; - } - case SyntaxKind.AliasQualifiedName: - case SyntaxKind.GenericName: - case SyntaxKind.IdentifierName: - case SyntaxKind.NullableType: - case SyntaxKind.OmittedTypeArgument: - case SyntaxKind.PointerType: - case SyntaxKind.PredefinedType: - case SyntaxKind.QualifiedName: - case SyntaxKind.RefType: - case SyntaxKind.TupleType: - { - if (IsAnyTypeParameter) + switch (node.Kind()) + { + case SyntaxKind.ArrayType: + { + VisitArrayType((ArrayTypeSyntax)node); + break; + } + case SyntaxKind.AliasQualifiedName: + case SyntaxKind.GenericName: + case SyntaxKind.IdentifierName: + case SyntaxKind.NullableType: + case SyntaxKind.OmittedTypeArgument: + case SyntaxKind.PointerType: + case SyntaxKind.PredefinedType: + case SyntaxKind.QualifiedName: + case SyntaxKind.RefType: + case SyntaxKind.TupleType: + { + if (IsAnyTypeParameter) + base.VisitType(node); + + break; + } + default: + { base.VisitType(node); - - break; - } - default: - { - base.VisitType(node); - break; - } + break; + } + } } - } - public override void VisitIdentifierName(IdentifierNameSyntax node) - { - string name = node.Identifier.ValueText; - - if (Nodes.TryGetValue(name, out NodeSymbolInfo info)) + public override void VisitIdentifierName(IdentifierNameSyntax node) { - if (info.Symbol == null) - { - ISymbol declaredSymbol = SemanticModel.GetDeclaredSymbol(info.Node, CancellationToken); + string name = node.Identifier.ValueText; - if (declaredSymbol == null) + if (Nodes.TryGetValue(name, out NodeSymbolInfo info)) + { + if (info.Symbol is null) { - RemoveNode(name); - return; + ISymbol declaredSymbol = SemanticModel.GetDeclaredSymbol(info.Node, CancellationToken); + + if (declaredSymbol is null) + { + RemoveNode(name); + return; + } + + info = new NodeSymbolInfo(info.Name, info.Node, declaredSymbol); + + Nodes[name] = info; } - info = new NodeSymbolInfo(info.Name, info.Node, declaredSymbol); + ISymbol symbol = SemanticModel.GetSymbol(node, CancellationToken); + + if (IsIndexer) + symbol = GetIndexerParameterSymbol(node, symbol); - Nodes[name] = info; + if (SymbolEqualityComparer.Default.Equals(info.Symbol, symbol)) + RemoveNode(name); } + } - ISymbol symbol = SemanticModel.GetSymbol(node, CancellationToken); + private static ISymbol GetIndexerParameterSymbol(IdentifierNameSyntax identifierName, ISymbol symbol) + { + if (symbol?.ContainingSymbol is not IMethodSymbol methodSymbol) + return null; - if (IsIndexer) - symbol = GetIndexerParameterSymbol(node, symbol); + if (methodSymbol.AssociatedSymbol is not IPropertySymbol propertySymbol) + return null; - if (SymbolEqualityComparer.Default.Equals(info.Symbol, symbol)) - RemoveNode(name); - } - } + if (!propertySymbol.IsIndexer) + return null; - private static ISymbol GetIndexerParameterSymbol(IdentifierNameSyntax identifierName, ISymbol symbol) - { - if (symbol?.ContainingSymbol is not IMethodSymbol methodSymbol) - return null; + string name = identifierName.Identifier.ValueText; - if (methodSymbol.AssociatedSymbol is not IPropertySymbol propertySymbol) - return null; + foreach (IParameterSymbol parameterSymbol in propertySymbol.Parameters) + { + if (string.Equals(name, parameterSymbol.Name, StringComparison.Ordinal)) + return parameterSymbol; + } - if (!propertySymbol.IsIndexer) return null; + } - string name = identifierName.Identifier.ValueText; - - foreach (IParameterSymbol parameterSymbol in propertySymbol.Parameters) + public override void VisitAttributeList(AttributeListSyntax node) { - if (string.Equals(name, parameterSymbol.Name, StringComparison.Ordinal)) - return parameterSymbol; } - return null; - } - - public override void VisitAttributeList(AttributeListSyntax node) - { - } - - public override void VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) - { - } - - public override void VisitGotoStatement(GotoStatementSyntax node) - { - } + public override void VisitExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax node) + { + } - public override void VisitLiteralExpression(LiteralExpressionSyntax node) - { - } + public override void VisitGotoStatement(GotoStatementSyntax node) + { + } - public override void VisitNameColon(NameColonSyntax node) - { - } + public override void VisitLiteralExpression(LiteralExpressionSyntax node) + { + } - public override void VisitTypeParameterList(TypeParameterListSyntax node) - { - } + public override void VisitNameColon(NameColonSyntax node) + { + } - public override void VisitBracketedParameterList(BracketedParameterListSyntax node) - { - } + public override void VisitTypeParameterList(TypeParameterListSyntax node) + { + } - public override void VisitParameterList(ParameterListSyntax node) - { - if (node.IsParentKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement)) - base.VisitParameterList(node); - } + public override void VisitBracketedParameterList(BracketedParameterListSyntax node) + { + } - public override void VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) - { - if (IsAnyTypeParameter - && node.IsParentKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement)) + public override void VisitParameterList(ParameterListSyntax node) { - base.VisitTypeParameterConstraintClause(node); + if (node.IsParentKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement)) + base.VisitParameterList(node); } - } - public static UnusedParameterWalker GetInstance() - { - UnusedParameterWalker walker = _cachedInstance; + public override void VisitTypeParameterConstraintClause(TypeParameterConstraintClauseSyntax node) + { + if (IsAnyTypeParameter + && node.IsParentKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement)) + { + base.VisitTypeParameterConstraintClause(node); + } + } - if (walker != null) + public static UnusedParameterWalker GetInstance() { - Debug.Assert(walker.Nodes.Count == 0); - Debug.Assert(walker.SemanticModel == null); - Debug.Assert(walker.CancellationToken == default); + UnusedParameterWalker walker = _cachedInstance; - _cachedInstance = null; - return walker; - } + if (walker is not null) + { + Debug.Assert(walker.Nodes.Count == 0); + Debug.Assert(walker.SemanticModel is null); + Debug.Assert(walker.CancellationToken == default); - return new UnusedParameterWalker(); - } + _cachedInstance = null; + return walker; + } - public static void Free(UnusedParameterWalker walker) - { - walker.SetValues(default(SemanticModel), default(CancellationToken)); + return new UnusedParameterWalker(); + } - _cachedInstance = walker; + public static void Free(UnusedParameterWalker walker) + { + walker.SetValues(default(SemanticModel), default(CancellationToken)); + + _cachedInstance = walker; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseAnonymousFunctionOrMethodGroupAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseAnonymousFunctionOrMethodGroupAnalyzer.cs index 1054b951e5..741552e8db 100644 --- a/src/Analyzers/CSharp/Analysis/UseAnonymousFunctionOrMethodGroupAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseAnonymousFunctionOrMethodGroupAnalyzer.cs @@ -8,729 +8,730 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseAnonymousFunctionOrMethodGroupAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseAnonymousFunctionOrMethodGroupAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseAnonymousFunctionOrMethodGroup); - } + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseAnonymousFunctionOrMethodGroup); + } - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); - - startContext.RegisterSyntaxNodeAction(f => AnalyzeArgument(f), SyntaxKind.Argument); - startContext.RegisterSyntaxNodeAction(f => AnalyzeEqualsValueClause(f), SyntaxKind.EqualsValueClause); - startContext.RegisterSyntaxNodeAction(f => AnalyzeAssignment(f), SyntaxKind.SimpleAssignmentExpression, SyntaxKind.AddAssignmentExpression, SyntaxKind.SubtractAssignmentExpression, SyntaxKind.CoalesceAssignmentExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeReturnStatement(f), SyntaxKind.ReturnStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeYieldReturnStatement(f), SyntaxKind.YieldReturnStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeArrowExpressionClause(f), SyntaxKind.ArrowExpressionClause); - startContext.RegisterSyntaxNodeAction(f => AnalyzeSwitchExpressionArm(f), SyntaxKind.SwitchExpressionArm); - startContext.RegisterSyntaxNodeAction(f => AnalyzeArrayInitializer(f), SyntaxKind.ArrayInitializerExpression, SyntaxKind.CollectionInitializerExpression); + base.Initialize(context); + + context.RegisterCompilationStartAction(startContext => + { + startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); + + startContext.RegisterSyntaxNodeAction(f => AnalyzeArgument(f), SyntaxKind.Argument); + startContext.RegisterSyntaxNodeAction(f => AnalyzeEqualsValueClause(f), SyntaxKind.EqualsValueClause); + startContext.RegisterSyntaxNodeAction(f => AnalyzeAssignment(f), SyntaxKind.SimpleAssignmentExpression, SyntaxKind.AddAssignmentExpression, SyntaxKind.SubtractAssignmentExpression, SyntaxKind.CoalesceAssignmentExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeReturnStatement(f), SyntaxKind.ReturnStatement); + startContext.RegisterSyntaxNodeAction(f => AnalyzeYieldReturnStatement(f), SyntaxKind.YieldReturnStatement); + startContext.RegisterSyntaxNodeAction(f => AnalyzeArrowExpressionClause(f), SyntaxKind.ArrowExpressionClause); + startContext.RegisterSyntaxNodeAction(f => AnalyzeSwitchExpressionArm(f), SyntaxKind.SwitchExpressionArm); + startContext.RegisterSyntaxNodeAction(f => AnalyzeArrayInitializer(f), SyntaxKind.ArrayInitializerExpression, SyntaxKind.CollectionInitializerExpression); #if DEBUG - startContext.RegisterSyntaxNodeAction(f => AnalyzeIdentifierName(f), SyntaxKind.IdentifierName); - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleMemberAccessExpression(f), SyntaxKind.SimpleMemberAccessExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeIdentifierName(f), SyntaxKind.IdentifierName); + startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleMemberAccessExpression(f), SyntaxKind.SimpleMemberAccessExpression); #endif - }); - } + }); + } - private static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) - { - if (!ConvertToMethodGroup(context)) - return; + private static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) + { + if (!ConvertToMethodGroup(context)) + return; - if (context.Node.SpanContainsDirectives()) - return; + if (context.Node.SpanContainsDirectives()) + return; - var lambda = (SimpleLambdaExpressionSyntax)context.Node; + var lambda = (SimpleLambdaExpressionSyntax)context.Node; - InvocationExpressionSyntax invocationExpression = GetInvocationExpression(lambda.Body); + InvocationExpressionSyntax invocationExpression = GetInvocationExpression(lambda.Body); - if (invocationExpression == null) - return; + if (invocationExpression is null) + return; - ExpressionSyntax expression = invocationExpression.Expression; + ExpressionSyntax expression = invocationExpression.Expression; - if (!IsSimpleInvocation(expression)) - return; + if (!IsSimpleInvocation(expression)) + return; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (semanticModel.GetSymbol(invocationExpression, cancellationToken) is not IMethodSymbol methodSymbol) - return; + if (semanticModel.GetSymbol(invocationExpression, cancellationToken) is not IMethodSymbol methodSymbol) + return; - if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) - return; + if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) + return; - bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; + bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; - if (!methodSymbol.IsStatic - && expression.Kind() != SyntaxKind.IdentifierName) - { - if (!ExpressionIsParameter(expression, lambda.Parameter)) + if (!methodSymbol.IsStatic + && expression.Kind() != SyntaxKind.IdentifierName) { - return; - } - else if (isReduced - && !SymbolEqualityComparer.Default.Equals(context.ContainingSymbol.ContainingType, methodSymbol.ContainingType)) - { - return; + if (!ExpressionIsParameter(expression, lambda.Parameter)) + { + return; + } + else if (isReduced + && !SymbolEqualityComparer.Default.Equals(context.ContainingSymbol.ContainingType, methodSymbol.ContainingType)) + { + return; + } } - } - ImmutableArray parameterSymbols = (isReduced) ? methodSymbol.ReducedFrom.Parameters : methodSymbol.Parameters; + ImmutableArray parameterSymbols = (isReduced) ? methodSymbol.ReducedFrom.Parameters : methodSymbol.Parameters; - if (parameterSymbols.Length != 1) - return; - - ArgumentListSyntax argumentList = invocationExpression.ArgumentList; + if (parameterSymbols.Length != 1) + return; - SeparatedSyntaxList arguments = argumentList.Arguments; + ArgumentListSyntax argumentList = invocationExpression.ArgumentList; - if (arguments.Count != ((isReduced) ? 0 : 1)) - return; + SeparatedSyntaxList arguments = argumentList.Arguments; - ParameterSyntax parameter = lambda.Parameter; + if (arguments.Count != ((isReduced) ? 0 : 1)) + return; - MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; + ParameterSyntax parameter = lambda.Parameter; - if (!CheckParameter( - parameter, - (isReduced) ? memberAccessExpression.Expression : arguments[0].Expression, - parameterSymbols[0])) - { - return; - } + MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; - methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; + if (!CheckParameter( + parameter, + (isReduced) ? memberAccessExpression.Expression : arguments[0].Expression, + parameterSymbols[0])) + { + return; + } - if (!CheckInvokeMethod(lambda, methodSymbol, semanticModel, context.CancellationToken)) - return; + methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; - if (!CheckSpeculativeSymbol( - lambda, - (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, - methodSymbol, - semanticModel, - cancellationToken)) - { - return; - } + if (!CheckInvokeMethod(lambda, methodSymbol, semanticModel, context.CancellationToken)) + return; - ReportAnonymousFunction(context, lambda); - } + if (!CheckSpeculativeSymbol( + lambda, + (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, + methodSymbol, + semanticModel, + cancellationToken)) + { + return; + } - private static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisContext context) - { - if (!ConvertToMethodGroup(context)) - return; + ReportAnonymousFunction(context, lambda); + } - if (context.Node.SpanContainsDirectives()) - return; + private static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisContext context) + { + if (!ConvertToMethodGroup(context)) + return; - var lambda = (ParenthesizedLambdaExpressionSyntax)context.Node; + if (context.Node.SpanContainsDirectives()) + return; - InvocationExpressionSyntax invocationExpression = GetInvocationExpression(lambda.Body); + var lambda = (ParenthesizedLambdaExpressionSyntax)context.Node; - if (invocationExpression == null) - return; + InvocationExpressionSyntax invocationExpression = GetInvocationExpression(lambda.Body); - ExpressionSyntax expression = invocationExpression.Expression; + if (invocationExpression is null) + return; - if (!IsSimpleInvocation(expression)) - return; + ExpressionSyntax expression = invocationExpression.Expression; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + if (!IsSimpleInvocation(expression)) + return; - if (semanticModel.GetSymbol(invocationExpression, cancellationToken) is not IMethodSymbol methodSymbol) - return; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) - return; + if (semanticModel.GetSymbol(invocationExpression, cancellationToken) is not IMethodSymbol methodSymbol) + return; - if (!methodSymbol.IsStatic - && expression.Kind() != SyntaxKind.IdentifierName) - { - if (!ExpressionIsParameter(expression, lambda.ParameterList)) - { + if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) return; - } - else if (methodSymbol.MethodKind == MethodKind.ReducedExtension - && !SymbolEqualityComparer.Default.Equals(context.ContainingSymbol.ContainingType, methodSymbol.ContainingType)) + + if (!methodSymbol.IsStatic + && expression.Kind() != SyntaxKind.IdentifierName) { - return; + if (!ExpressionIsParameter(expression, lambda.ParameterList)) + { + return; + } + else if (methodSymbol.MethodKind == MethodKind.ReducedExtension + && !SymbolEqualityComparer.Default.Equals(context.ContainingSymbol.ContainingType, methodSymbol.ContainingType)) + { + return; + } } - } - ImmutableArray parameterSymbols = methodSymbol.Parameters; + ImmutableArray parameterSymbols = methodSymbol.Parameters; - ArgumentListSyntax argumentList = invocationExpression.ArgumentList; + ArgumentListSyntax argumentList = invocationExpression.ArgumentList; - SeparatedSyntaxList arguments = argumentList.Arguments; + SeparatedSyntaxList arguments = argumentList.Arguments; - if (arguments.Count != parameterSymbols.Length) - return; + if (arguments.Count != parameterSymbols.Length) + return; - ParameterListSyntax parameterList = lambda.ParameterList; + ParameterListSyntax parameterList = lambda.ParameterList; - SeparatedSyntaxList parameters = parameterList.Parameters; + SeparatedSyntaxList parameters = parameterList.Parameters; - bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; + bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; - if (parameters.Count != ((isReduced) ? arguments.Count + 1 : arguments.Count)) - return; + if (parameters.Count != ((isReduced) ? arguments.Count + 1 : arguments.Count)) + return; - MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; + MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; - if (isReduced) - { - if (!CheckParameter( - parameters[0], - memberAccessExpression.Expression, - methodSymbol.ReducedFrom.Parameters[0])) + if (isReduced) { - return; + if (!CheckParameter( + parameters[0], + memberAccessExpression.Expression, + methodSymbol.ReducedFrom.Parameters[0])) + { + return; + } + + parameters = parameters.RemoveAt(0); } - parameters = parameters.RemoveAt(0); - } + if (!CheckParameters(parameters, arguments, parameterSymbols)) + return; - if (!CheckParameters(parameters, arguments, parameterSymbols)) - return; + methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; - methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; + if (!CheckInvokeMethod(lambda, methodSymbol, semanticModel, context.CancellationToken)) + return; - if (!CheckInvokeMethod(lambda, methodSymbol, semanticModel, context.CancellationToken)) - return; + if (!CheckSpeculativeSymbol( + lambda, + (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, + methodSymbol, + semanticModel, + cancellationToken)) + { + return; + } - if (!CheckSpeculativeSymbol( - lambda, - (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, - methodSymbol, - semanticModel, - cancellationToken)) - { - return; + ReportAnonymousFunction(context, lambda); } - ReportAnonymousFunction(context, lambda); - } - - private static void AnalyzeAnonymousMethodExpression(SyntaxNodeAnalysisContext context) - { - if (!ConvertToMethodGroup(context)) - return; - - if (context.Node.SpanContainsDirectives()) - return; + private static void AnalyzeAnonymousMethodExpression(SyntaxNodeAnalysisContext context) + { + if (!ConvertToMethodGroup(context)) + return; - var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node; + if (context.Node.SpanContainsDirectives()) + return; - ParameterListSyntax parameterList = anonymousMethod.ParameterList; + var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node; - if (parameterList == null) - return; + ParameterListSyntax parameterList = anonymousMethod.ParameterList; - InvocationExpressionSyntax invocationExpression = GetInvocationExpression(anonymousMethod.Body); + if (parameterList is null) + return; - if (invocationExpression == null) - return; + InvocationExpressionSyntax invocationExpression = GetInvocationExpression(anonymousMethod.Body); - ExpressionSyntax expression = invocationExpression.Expression; + if (invocationExpression is null) + return; - if (!IsSimpleInvocation(expression)) - return; + ExpressionSyntax expression = invocationExpression.Expression; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + if (!IsSimpleInvocation(expression)) + return; - if (semanticModel.GetSymbol(invocationExpression, cancellationToken) is not IMethodSymbol methodSymbol) - return; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) - return; + if (semanticModel.GetSymbol(invocationExpression, cancellationToken) is not IMethodSymbol methodSymbol) + return; - if (!methodSymbol.IsStatic - && expression.Kind() != SyntaxKind.IdentifierName) - { - if (!ExpressionIsParameter(expression, parameterList)) - { + if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) return; - } - else if (methodSymbol.MethodKind == MethodKind.ReducedExtension - && !SymbolEqualityComparer.Default.Equals(context.ContainingSymbol.ContainingType, methodSymbol.ContainingType)) + + if (!methodSymbol.IsStatic + && expression.Kind() != SyntaxKind.IdentifierName) { - return; + if (!ExpressionIsParameter(expression, parameterList)) + { + return; + } + else if (methodSymbol.MethodKind == MethodKind.ReducedExtension + && !SymbolEqualityComparer.Default.Equals(context.ContainingSymbol.ContainingType, methodSymbol.ContainingType)) + { + return; + } } - } - ImmutableArray parameterSymbols = methodSymbol.Parameters; + ImmutableArray parameterSymbols = methodSymbol.Parameters; - ArgumentListSyntax argumentList = invocationExpression.ArgumentList; + ArgumentListSyntax argumentList = invocationExpression.ArgumentList; - SeparatedSyntaxList arguments = argumentList.Arguments; + SeparatedSyntaxList arguments = argumentList.Arguments; - if (arguments.Count != parameterSymbols.Length) - return; + if (arguments.Count != parameterSymbols.Length) + return; - SeparatedSyntaxList parameters = parameterList.Parameters; + SeparatedSyntaxList parameters = parameterList.Parameters; - bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; + bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; - if (parameters.Count != ((isReduced) ? arguments.Count + 1 : arguments.Count)) - return; + if (parameters.Count != ((isReduced) ? arguments.Count + 1 : arguments.Count)) + return; - MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; + MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; - if (isReduced) - { - if (!CheckParameter( - parameters[0], - ((MemberAccessExpressionSyntax)expression).Expression, - methodSymbol.ReducedFrom.Parameters[0])) + if (isReduced) { - return; + if (!CheckParameter( + parameters[0], + ((MemberAccessExpressionSyntax)expression).Expression, + methodSymbol.ReducedFrom.Parameters[0])) + { + return; + } + + parameters = parameters.RemoveAt(0); } - parameters = parameters.RemoveAt(0); - } + if (!CheckParameters(parameters, arguments, parameterSymbols)) + return; - if (!CheckParameters(parameters, arguments, parameterSymbols)) - return; + methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; - methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; + if (!CheckInvokeMethod(anonymousMethod, methodSymbol, semanticModel, context.CancellationToken)) + return; - if (!CheckInvokeMethod(anonymousMethod, methodSymbol, semanticModel, context.CancellationToken)) - return; + if (!CheckSpeculativeSymbol( + anonymousMethod, + (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, + methodSymbol, + semanticModel, + cancellationToken)) + { + return; + } - if (!CheckSpeculativeSymbol( - anonymousMethod, - (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, - methodSymbol, - semanticModel, - cancellationToken)) - { - return; + ReportAnonymousFunction(context, anonymousMethod); } - ReportAnonymousFunction(context, anonymousMethod); - } - - private static bool ExpressionIsParameter( - ExpressionSyntax expression, - ParameterSyntax parameter) - { - return expression.Kind() == SyntaxKind.SimpleMemberAccessExpression - && ((MemberAccessExpressionSyntax)expression).Expression is IdentifierNameSyntax identifierName - && identifierName.Identifier.ValueText == parameter.Identifier.ValueText; - } - - private static bool ExpressionIsParameter( - ExpressionSyntax expression, - ParameterListSyntax parameterList) - { - if (expression.Kind() == SyntaxKind.SimpleMemberAccessExpression) + private static bool ExpressionIsParameter( + ExpressionSyntax expression, + ParameterSyntax parameter) { - var memberAccessExpression = (MemberAccessExpressionSyntax)expression; + return expression.Kind() == SyntaxKind.SimpleMemberAccessExpression + && ((MemberAccessExpressionSyntax)expression).Expression is IdentifierNameSyntax identifierName + && identifierName.Identifier.ValueText == parameter.Identifier.ValueText; + } - if (memberAccessExpression.Expression is IdentifierNameSyntax identifierName) + private static bool ExpressionIsParameter( + ExpressionSyntax expression, + ParameterListSyntax parameterList) + { + if (expression.Kind() == SyntaxKind.SimpleMemberAccessExpression) { - string name = identifierName.Identifier.ValueText; + var memberAccessExpression = (MemberAccessExpressionSyntax)expression; - foreach (ParameterSyntax parameter in parameterList.Parameters) + if (memberAccessExpression.Expression is IdentifierNameSyntax identifierName) { - if (name == parameter.Identifier.ValueText) - return true; + string name = identifierName.Identifier.ValueText; + + foreach (ParameterSyntax parameter in parameterList.Parameters) + { + if (name == parameter.Identifier.ValueText) + return true; + } } } - } - - return false; - } - private static bool CheckInvokeMethod( - AnonymousFunctionExpressionSyntax anonymousFunction, - IMethodSymbol methodSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - var typeSymbol = semanticModel.GetTypeInfo(anonymousFunction, cancellationToken).ConvertedType as INamedTypeSymbol; - - IMethodSymbol invokeMethod = typeSymbol?.DelegateInvokeMethod; - - if (invokeMethod == null) - return false; - - if (invokeMethod.ReturnType.IsVoid() - && !methodSymbol.ReturnType.IsVoid()) - { return false; } - ImmutableArray parameters = methodSymbol.Parameters; + private static bool CheckInvokeMethod( + AnonymousFunctionExpressionSyntax anonymousFunction, + IMethodSymbol methodSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + var typeSymbol = semanticModel.GetTypeInfo(anonymousFunction, cancellationToken).ConvertedType as INamedTypeSymbol; - ImmutableArray parameters2 = invokeMethod.Parameters; + IMethodSymbol invokeMethod = typeSymbol?.DelegateInvokeMethod; - if (parameters.Length != parameters2.Length) - return false; + if (invokeMethod is null) + return false; - for (int i = 0; i < parameters.Length; i++) - { - if (!SymbolEqualityComparer.Default.Equals(parameters[i].Type, parameters2[i].Type)) + if (invokeMethod.ReturnType.IsVoid() + && !methodSymbol.ReturnType.IsVoid()) + { return false; - } + } - return true; - } + ImmutableArray parameters = methodSymbol.Parameters; - private static bool CheckParameters( - SeparatedSyntaxList parameters, - SeparatedSyntaxList arguments, - ImmutableArray parameterSymbols) - { - for (int i = 0; i < parameters.Count; i++) - { - if (!CheckParameter(parameters[i], arguments[i].Expression, parameterSymbols[i])) + ImmutableArray parameters2 = invokeMethod.Parameters; + + if (parameters.Length != parameters2.Length) return false; + + for (int i = 0; i < parameters.Length; i++) + { + if (!SymbolEqualityComparer.Default.Equals(parameters[i].Type, parameters2[i].Type)) + return false; + } + + return true; } - return true; - } + private static bool CheckParameters( + SeparatedSyntaxList parameters, + SeparatedSyntaxList arguments, + ImmutableArray parameterSymbols) + { + for (int i = 0; i < parameters.Count; i++) + { + if (!CheckParameter(parameters[i], arguments[i].Expression, parameterSymbols[i])) + return false; + } - private static bool CheckParameter( - ParameterSyntax parameter, - ExpressionSyntax expression, - IParameterSymbol parameterSymbol) - { - return parameterSymbol.RefKind == RefKind.None - && !parameterSymbol.IsParams - && string.Equals( - parameter.Identifier.ValueText, - (expression as IdentifierNameSyntax)?.Identifier.ValueText, - StringComparison.Ordinal); - } + return true; + } - private static bool CheckSpeculativeSymbol( - AnonymousFunctionExpressionSyntax anonymousFunction, - ExpressionSyntax expression, - IMethodSymbol methodSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - SyntaxNode argumentExpression = anonymousFunction.WalkUpParentheses(); + private static bool CheckParameter( + ParameterSyntax parameter, + ExpressionSyntax expression, + IParameterSymbol parameterSymbol) + { + return parameterSymbol.RefKind == RefKind.None + && !parameterSymbol.IsParams + && string.Equals( + parameter.Identifier.ValueText, + (expression as IdentifierNameSyntax)?.Identifier.ValueText, + StringComparison.Ordinal); + } - if (argumentExpression.Parent is ArgumentSyntax argument) + private static bool CheckSpeculativeSymbol( + AnonymousFunctionExpressionSyntax anonymousFunction, + ExpressionSyntax expression, + IMethodSymbol methodSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - if (argument.Parent is BaseArgumentListSyntax) + SyntaxNode argumentExpression = anonymousFunction.WalkUpParentheses(); + + if (argumentExpression.Parent is ArgumentSyntax argument) { - SyntaxNode node = argument.Parent.Parent; + if (argument.Parent is BaseArgumentListSyntax) + { + SyntaxNode node = argument.Parent.Parent; - // related to https://github.com/dotnet/roslyn/issues/25262 - if (CSharpUtility.IsConditionallyAccessed(node)) - return false; + // related to https://github.com/dotnet/roslyn/issues/25262 + if (CSharpUtility.IsConditionallyAccessed(node)) + return false; - SyntaxNode newNode = node.ReplaceNode(argument.Expression, expression); + SyntaxNode newNode = node.ReplaceNode(argument.Expression, expression); - SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo(node.SpanStart, newNode, SpeculativeBindingOption.BindAsExpression); + SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo(node.SpanStart, newNode, SpeculativeBindingOption.BindAsExpression); - methodSymbol = semanticModel.GetSymbol(node, cancellationToken) as IMethodSymbol; + methodSymbol = semanticModel.GetSymbol(node, cancellationToken) as IMethodSymbol; - return methodSymbol != null - && CheckSpeculativeSymbol(symbolInfo); + return methodSymbol is not null + && CheckSpeculativeSymbol(symbolInfo); + } } - } - else - { - SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo(anonymousFunction.SpanStart, expression, SpeculativeBindingOption.BindAsExpression); + else + { + SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo(anonymousFunction.SpanStart, expression, SpeculativeBindingOption.BindAsExpression); - return CheckSpeculativeSymbol(symbolInfo); - } + return CheckSpeculativeSymbol(symbolInfo); + } - return false; + return false; - bool CheckSpeculativeSymbol(SymbolInfo symbolInfo) - { - return SymbolEqualityComparer.Default.Equals(symbolInfo.Symbol, methodSymbol) - || SymbolEqualityComparer.Default.Equals(symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false), methodSymbol); + bool CheckSpeculativeSymbol(SymbolInfo symbolInfo) + { + return SymbolEqualityComparer.Default.Equals(symbolInfo.Symbol, methodSymbol) + || SymbolEqualityComparer.Default.Equals(symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false), methodSymbol); + } } - } - private static bool IsSimpleInvocation(ExpressionSyntax expression) - { - while (true) + private static bool IsSimpleInvocation(ExpressionSyntax expression) { - switch (expression?.Kind()) + while (true) { - case SyntaxKind.IdentifierName: - { - return true; - } - case SyntaxKind.SimpleMemberAccessExpression: - { - expression = ((MemberAccessExpressionSyntax)expression).Expression; - break; - } - default: - { - return false; - } + switch (expression?.Kind()) + { + case SyntaxKind.IdentifierName: + { + return true; + } + case SyntaxKind.SimpleMemberAccessExpression: + { + expression = ((MemberAccessExpressionSyntax)expression).Expression; + break; + } + default: + { + return false; + } + } } } - } - internal static InvocationExpressionSyntax GetInvocationExpression(SyntaxNode node) - { - ExpressionSyntax expression = GetExpression(node)?.WalkDownParentheses(); + internal static InvocationExpressionSyntax GetInvocationExpression(SyntaxNode node) + { + ExpressionSyntax expression = GetExpression(node)?.WalkDownParentheses(); - if (expression?.Kind() == SyntaxKind.InvocationExpression) - return (InvocationExpressionSyntax)expression; + if (expression?.Kind() == SyntaxKind.InvocationExpression) + return (InvocationExpressionSyntax)expression; - return null; - } + return null; + } - private static ExpressionSyntax GetExpression(SyntaxNode node) - { - if (node is BlockSyntax block) + private static ExpressionSyntax GetExpression(SyntaxNode node) { - StatementSyntax statement = block.Statements.SingleOrDefault(shouldThrow: false); - - switch (statement?.Kind()) + if (node is BlockSyntax block) { - case SyntaxKind.ExpressionStatement: - return ((ExpressionStatementSyntax)statement).Expression; - case SyntaxKind.ReturnStatement: - return ((ReturnStatementSyntax)statement).Expression; - default: - return null; - } - } - - return node as ExpressionSyntax; - } + StatementSyntax statement = block.Statements.SingleOrDefault(shouldThrow: false); - private static void AnalyzeArgument(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + switch (statement?.Kind()) + { + case SyntaxKind.ExpressionStatement: + return ((ExpressionStatementSyntax)statement).Expression; + case SyntaxKind.ReturnStatement: + return ((ReturnStatementSyntax)statement).Expression; + default: + return null; + } + } - var argument = (ArgumentSyntax)context.Node; + return node as ExpressionSyntax; + } - ExpressionSyntax expression = argument.Expression.WalkDownParentheses(); + private static void AnalyzeArgument(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) - return; + var argument = (ArgumentSyntax)context.Node; - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); + ExpressionSyntax expression = argument.Expression.WalkDownParentheses(); - if (methodSymbol == null) - return; + if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + return; - ReportMethodGroup(context, expression); - } + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); - private static void AnalyzeEqualsValueClause(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + if (methodSymbol is null) + return; - var argument = (EqualsValueClauseSyntax)context.Node; + ReportMethodGroup(context, expression); + } - ExpressionSyntax expression = argument.Value.WalkDownParentheses(); + private static void AnalyzeEqualsValueClause(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) - return; + var argument = (EqualsValueClauseSyntax)context.Node; - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); + ExpressionSyntax expression = argument.Value.WalkDownParentheses(); - if (methodSymbol == null) - return; + if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + return; - ReportMethodGroup(context, expression); - } + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); - private static void AnalyzeAssignment(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + if (methodSymbol is null) + return; - var argument = (AssignmentExpressionSyntax)context.Node; + ReportMethodGroup(context, expression); + } - ExpressionSyntax expression = argument.Right.WalkDownParentheses(); + private static void AnalyzeAssignment(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) - return; + var argument = (AssignmentExpressionSyntax)context.Node; - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); + ExpressionSyntax expression = argument.Right.WalkDownParentheses(); - if (methodSymbol == null) - return; + if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + return; - ReportMethodGroup(context, expression); - } + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); - private static void AnalyzeReturnStatement(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + if (methodSymbol is null) + return; - var returnStatement = (ReturnStatementSyntax)context.Node; + ReportMethodGroup(context, expression); + } - ExpressionSyntax expression = returnStatement.Expression?.WalkDownParentheses(); + private static void AnalyzeReturnStatement(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) - return; + var returnStatement = (ReturnStatementSyntax)context.Node; - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); + ExpressionSyntax expression = returnStatement.Expression?.WalkDownParentheses(); - if (methodSymbol == null) - return; + if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + return; - ReportMethodGroup(context, expression); - } + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); - private static void AnalyzeYieldReturnStatement(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + if (methodSymbol is null) + return; - var yieldReturnStatement = (YieldStatementSyntax)context.Node; + ReportMethodGroup(context, expression); + } - ExpressionSyntax expression = yieldReturnStatement.Expression?.WalkDownParentheses(); + private static void AnalyzeYieldReturnStatement(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) - return; + var yieldReturnStatement = (YieldStatementSyntax)context.Node; - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); + ExpressionSyntax expression = yieldReturnStatement.Expression?.WalkDownParentheses(); - if (methodSymbol == null) - return; + if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + return; - ReportMethodGroup(context, expression); - } + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); - private static void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + if (methodSymbol is null) + return; - var arrowExpressionClause = (ArrowExpressionClauseSyntax)context.Node; + ReportMethodGroup(context, expression); + } - ExpressionSyntax expression = arrowExpressionClause.Expression?.WalkDownParentheses(); + private static void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) - return; + var arrowExpressionClause = (ArrowExpressionClauseSyntax)context.Node; - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); + ExpressionSyntax expression = arrowExpressionClause.Expression?.WalkDownParentheses(); - if (methodSymbol == null) - return; + if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + return; - ReportMethodGroup(context, expression); - } + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); - private static void AnalyzeSwitchExpressionArm(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + if (methodSymbol is null) + return; - var switchExpressionArm = (SwitchExpressionArmSyntax)context.Node; + ReportMethodGroup(context, expression); + } - ExpressionSyntax expression = switchExpressionArm.Expression?.WalkDownParentheses(); + private static void AnalyzeSwitchExpressionArm(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) - return; + var switchExpressionArm = (SwitchExpressionArmSyntax)context.Node; - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); + ExpressionSyntax expression = switchExpressionArm.Expression?.WalkDownParentheses(); - if (methodSymbol == null) - return; + if (!expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + return; - ReportMethodGroup(context, expression); - } + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression, context.CancellationToken); - private static void AnalyzeArrayInitializer(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + if (methodSymbol is null) + return; - var initializer = (InitializerExpressionSyntax)context.Node; + ReportMethodGroup(context, expression); + } - foreach (ExpressionSyntax expression in initializer.Expressions) + private static void AnalyzeArrayInitializer(SyntaxNodeAnalysisContext context) { - ExpressionSyntax expression2 = expression?.WalkDownParentheses(); + if (!ConvertToAnonymousFunction(context)) + return; - if (expression2.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + var initializer = (InitializerExpressionSyntax)context.Node; + + foreach (ExpressionSyntax expression in initializer.Expressions) { - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression2, context.CancellationToken); + ExpressionSyntax expression2 = expression?.WalkDownParentheses(); + + if (expression2.IsKind(SyntaxKind.IdentifierName, SyntaxKind.SimpleMemberAccessExpression)) + { + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(expression2, context.CancellationToken); - if (methodSymbol != null) - ReportMethodGroup(context, expression2); + if (methodSymbol is not null) + ReportMethodGroup(context, expression2); + } } } - } #if DEBUG - private static void AnalyzeIdentifierName(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + private static void AnalyzeIdentifierName(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - var identifierName = (IdentifierNameSyntax)context.Node; + var identifierName = (IdentifierNameSyntax)context.Node; - ConvertMethodGroupToAnonymousFunctionAnalysis.IsFixable(identifierName, context.SemanticModel, context.CancellationToken); - } + ConvertMethodGroupToAnonymousFunctionAnalysis.IsFixable(identifierName, context.SemanticModel, context.CancellationToken); + } - private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContext context) - { - if (!ConvertToAnonymousFunction(context)) - return; + private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContext context) + { + if (!ConvertToAnonymousFunction(context)) + return; - var simpleMemberAccess = (MemberAccessExpressionSyntax)context.Node; + var simpleMemberAccess = (MemberAccessExpressionSyntax)context.Node; - ConvertMethodGroupToAnonymousFunctionAnalysis.IsFixable(simpleMemberAccess, context.SemanticModel, context.CancellationToken); - } + ConvertMethodGroupToAnonymousFunctionAnalysis.IsFixable(simpleMemberAccess, context.SemanticModel, context.CancellationToken); + } #endif - private static bool ConvertToAnonymousFunction(SyntaxNodeAnalysisContext context) - { - return context.PreferAnonymousFunctionOrMethodGroup() == true; - } + private static bool ConvertToAnonymousFunction(SyntaxNodeAnalysisContext context) + { + return context.PreferAnonymousFunctionOrMethodGroup() == true; + } - private static bool ConvertToMethodGroup(SyntaxNodeAnalysisContext context) - { - return context.PreferAnonymousFunctionOrMethodGroup() == false; - } + private static bool ConvertToMethodGroup(SyntaxNodeAnalysisContext context) + { + return context.PreferAnonymousFunctionOrMethodGroup() == false; + } - private static void ReportAnonymousFunction(SyntaxNodeAnalysisContext context, AnonymousFunctionExpressionSyntax anonymousMethod) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAnonymousFunctionOrMethodGroup, anonymousMethod, "method group"); - } + private static void ReportAnonymousFunction(SyntaxNodeAnalysisContext context, AnonymousFunctionExpressionSyntax anonymousMethod) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAnonymousFunctionOrMethodGroup, anonymousMethod, "method group"); + } - private static void ReportMethodGroup(SyntaxNodeAnalysisContext context, ExpressionSyntax expression) - { - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseAnonymousFunctionOrMethodGroup, - expression, - "anonymous function"); + private static void ReportMethodGroup(SyntaxNodeAnalysisContext context, ExpressionSyntax expression) + { + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseAnonymousFunctionOrMethodGroup, + expression, + "anonymous function"); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseAsyncAwaitAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseAsyncAwaitAnalyzer.cs index 5dd79a89da..364710920a 100644 --- a/src/Analyzers/CSharp/Analysis/UseAsyncAwaitAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseAsyncAwaitAnalyzer.cs @@ -11,350 +11,351 @@ using Roslynator.CSharp.Syntax; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseAsyncAwaitAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseAsyncAwaitAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseAsyncAwait); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseAsyncAwait); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); - context.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); - context.RegisterSyntaxNodeAction(f => AnalyzeSimpleLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); - context.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); - context.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); - } + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) - { - var methodDeclaration = (MethodDeclarationSyntax)context.Node; + context.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); + context.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); + context.RegisterSyntaxNodeAction(f => AnalyzeSimpleLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); + context.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); + context.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); + } - if (methodDeclaration.Modifiers.Contains(SyntaxKind.AsyncKeyword)) - return; + private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) + { + var methodDeclaration = (MethodDeclarationSyntax)context.Node; - BlockSyntax body = methodDeclaration.Body; + if (methodDeclaration.Modifiers.Contains(SyntaxKind.AsyncKeyword)) + return; - if (body == null) - return; + BlockSyntax body = methodDeclaration.Body; - if (!body.Statements.Any()) - return; + if (body is null) + return; - IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclaration, context.CancellationToken); + if (!body.Statements.Any()) + return; - if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) - return; + IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclaration, context.CancellationToken); - if (IsFixable(body, context)) - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, methodDeclaration.Identifier); - } + if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) + return; - private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) - { - var localFunction = (LocalFunctionStatementSyntax)context.Node; + if (IsFixable(body, context)) + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, methodDeclaration.Identifier); + } - if (localFunction.Modifiers.Contains(SyntaxKind.AsyncKeyword)) - return; + private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) + { + var localFunction = (LocalFunctionStatementSyntax)context.Node; - BlockSyntax body = localFunction.Body; + if (localFunction.Modifiers.Contains(SyntaxKind.AsyncKeyword)) + return; - if (body == null) - return; + BlockSyntax body = localFunction.Body; - if (!body.Statements.Any()) - return; + if (body is null) + return; - IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(localFunction, context.CancellationToken); + if (!body.Statements.Any()) + return; - if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) - return; + IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(localFunction, context.CancellationToken); - if (IsFixable(body, context)) - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, localFunction.Identifier); - } + if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) + return; - private static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) - { - var simpleLambda = (SimpleLambdaExpressionSyntax)context.Node; + if (IsFixable(body, context)) + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, localFunction.Identifier); + } - if (simpleLambda.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) - return; + private static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) + { + var simpleLambda = (SimpleLambdaExpressionSyntax)context.Node; - if (simpleLambda.Body is not BlockSyntax body) - return; + if (simpleLambda.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) + return; - if (context.SemanticModel.GetSymbol(simpleLambda, context.CancellationToken) is not IMethodSymbol methodSymbol) - return; + if (simpleLambda.Body is not BlockSyntax body) + return; - if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) - return; + if (context.SemanticModel.GetSymbol(simpleLambda, context.CancellationToken) is not IMethodSymbol methodSymbol) + return; - if (IsFixable(body, context)) - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, simpleLambda); - } + if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) + return; - private static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisContext context) - { - var parenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)context.Node; + if (IsFixable(body, context)) + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, simpleLambda); + } - if (parenthesizedLambda.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) - return; + private static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisContext context) + { + var parenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)context.Node; - if (parenthesizedLambda.Body is not BlockSyntax body) - return; + if (parenthesizedLambda.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) + return; - if (context.SemanticModel.GetSymbol(parenthesizedLambda, context.CancellationToken) is not IMethodSymbol methodSymbol) - return; + if (parenthesizedLambda.Body is not BlockSyntax body) + return; - if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) - return; + if (context.SemanticModel.GetSymbol(parenthesizedLambda, context.CancellationToken) is not IMethodSymbol methodSymbol) + return; - if (IsFixable(body, context)) - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, parenthesizedLambda); - } + if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) + return; - private static void AnalyzeAnonymousMethodExpression(SyntaxNodeAnalysisContext context) - { - var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node; + if (IsFixable(body, context)) + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, parenthesizedLambda); + } - if (anonymousMethod.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) - return; + private static void AnalyzeAnonymousMethodExpression(SyntaxNodeAnalysisContext context) + { + var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node; - BlockSyntax body = anonymousMethod.Block; + if (anonymousMethod.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword)) + return; - if (body == null) - return; + BlockSyntax body = anonymousMethod.Block; - if (context.SemanticModel.GetSymbol(anonymousMethod, context.CancellationToken) is not IMethodSymbol methodSymbol) - return; + if (body is null) + return; - if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) - return; + if (context.SemanticModel.GetSymbol(anonymousMethod, context.CancellationToken) is not IMethodSymbol methodSymbol) + return; - if (IsFixable(body, context)) - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, anonymousMethod); - } + if (!SymbolUtility.IsAwaitable(methodSymbol.ReturnType)) + return; - private static bool IsFixable(BlockSyntax body, SyntaxNodeAnalysisContext context) - { - UseAsyncAwaitWalker walker = null; + if (IsFixable(body, context)) + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAsyncAwait, anonymousMethod); + } - try + private static bool IsFixable(BlockSyntax body, SyntaxNodeAnalysisContext context) { - walker = UseAsyncAwaitWalker.GetInstance(context.SemanticModel, context.CancellationToken); + UseAsyncAwaitWalker walker = null; - walker.VisitBlock(body); + try + { + walker = UseAsyncAwaitWalker.GetInstance(context.SemanticModel, context.CancellationToken); - return walker.ReturnStatement != null; - } - finally - { - if (walker != null) - UseAsyncAwaitWalker.Free(walker); - } - } + walker.VisitBlock(body); - private class UseAsyncAwaitWalker : StatementWalker - { - [ThreadStatic] - private static UseAsyncAwaitWalker _cachedInstance; - - private int _usingOrTryStatementDepth; - private bool _shouldVisit = true; - private readonly List _usingDeclarations = new(); + return walker.ReturnStatement is not null; + } + finally + { + if (walker is not null) + UseAsyncAwaitWalker.Free(walker); + } + } - public override bool ShouldVisit => _shouldVisit; + private class UseAsyncAwaitWalker : StatementWalker + { + [ThreadStatic] + private static UseAsyncAwaitWalker _cachedInstance; - public ReturnStatementSyntax ReturnStatement { get; private set; } + private int _usingOrTryStatementDepth; + private bool _shouldVisit = true; + private readonly List _usingDeclarations = new(); - public SemanticModel SemanticModel { get; private set; } + public override bool ShouldVisit => _shouldVisit; - public CancellationToken CancellationToken { get; private set; } + public ReturnStatementSyntax ReturnStatement { get; private set; } - public override void VisitUsingStatement(UsingStatementSyntax node) - { - _usingOrTryStatementDepth++; - base.VisitUsingStatement(node); - _usingOrTryStatementDepth--; - } + public SemanticModel SemanticModel { get; private set; } - public override void VisitTryStatement(TryStatementSyntax node) - { - BlockSyntax block = node.Block; + public CancellationToken CancellationToken { get; private set; } - if (block != null) + public override void VisitUsingStatement(UsingStatementSyntax node) { _usingOrTryStatementDepth++; - VisitBlock(block); + base.VisitUsingStatement(node); _usingOrTryStatementDepth--; } - foreach (CatchClauseSyntax catchClause in node.Catches) - VisitCatchClause(catchClause); + public override void VisitTryStatement(TryStatementSyntax node) + { + BlockSyntax block = node.Block; - FinallyClauseSyntax finallyClause = node.Finally; + if (block is not null) + { + _usingOrTryStatementDepth++; + VisitBlock(block); + _usingOrTryStatementDepth--; + } - if (finallyClause != null) - VisitFinallyClause(finallyClause); - } + foreach (CatchClauseSyntax catchClause in node.Catches) + VisitCatchClause(catchClause); - public override void VisitBlock(BlockSyntax node) - { - _usingDeclarations.Add(0); - base.VisitBlock(node); - _usingDeclarations.RemoveAt(_usingDeclarations.Count - 1); - } + FinallyClauseSyntax finallyClause = node.Finally; - public override void VisitSwitchSection(SwitchSectionSyntax node) - { - _usingDeclarations.Add(0); - base.VisitSwitchSection(node); - _usingDeclarations.RemoveAt(_usingDeclarations.Count - 1); - } - - public override void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) - { - if (node.UsingKeyword.IsKind(SyntaxKind.UsingKeyword)) - _usingDeclarations[_usingDeclarations.Count - 1]++; + if (finallyClause is not null) + VisitFinallyClause(finallyClause); + } - base.VisitLocalDeclarationStatement(node); - } + public override void VisitBlock(BlockSyntax node) + { + _usingDeclarations.Add(0); + base.VisitBlock(node); + _usingDeclarations.RemoveAt(_usingDeclarations.Count - 1); + } - public override void VisitReturnStatement(ReturnStatementSyntax node) - { - bool isInsideUsingOrTry = _usingOrTryStatementDepth > 0; + public override void VisitSwitchSection(SwitchSectionSyntax node) + { + _usingDeclarations.Add(0); + base.VisitSwitchSection(node); + _usingDeclarations.RemoveAt(_usingDeclarations.Count - 1); + } - if (!isInsideUsingOrTry) + public override void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { - foreach (int count in _usingDeclarations) - { - if (count > 0) - { - isInsideUsingOrTry = true; - break; - } - } + if (node.UsingKeyword.IsKind(SyntaxKind.UsingKeyword)) + _usingDeclarations[_usingDeclarations.Count - 1]++; + + base.VisitLocalDeclarationStatement(node); } - if (isInsideUsingOrTry) + public override void VisitReturnStatement(ReturnStatementSyntax node) { - ExpressionSyntax expression = node.Expression; + bool isInsideUsingOrTry = _usingOrTryStatementDepth > 0; - if (expression?.IsKind(SyntaxKind.AwaitExpression) == false - && !IsCompletedTask(expression)) + if (!isInsideUsingOrTry) { - ReturnStatement = node; - _shouldVisit = false; + foreach (int count in _usingDeclarations) + { + if (count > 0) + { + isInsideUsingOrTry = true; + break; + } + } } - } - base.VisitReturnStatement(node); - } + if (isInsideUsingOrTry) + { + ExpressionSyntax expression = node.Expression; - private bool IsCompletedTask(ExpressionSyntax expression) - { - if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) - { - var simpleMemberAccess = (MemberAccessExpressionSyntax)expression; + if (expression?.IsKind(SyntaxKind.AwaitExpression) == false + && !IsCompletedTask(expression)) + { + ReturnStatement = node; + _shouldVisit = false; + } + } - return string.Equals(simpleMemberAccess.Name.Identifier.ValueText, "CompletedTask", StringComparison.Ordinal) - && SemanticModel.GetSymbol(expression, CancellationToken) is IPropertySymbol propertySymbol - && IsTaskOrTaskOrT(propertySymbol.ContainingType); + base.VisitReturnStatement(node); } - else + + private bool IsCompletedTask(ExpressionSyntax expression) { - SimpleMemberInvocationExpressionInfo memberInvocation = SyntaxInfo.SimpleMemberInvocationExpressionInfo(expression); + if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) + { + var simpleMemberAccess = (MemberAccessExpressionSyntax)expression; - if (memberInvocation.Success) + return string.Equals(simpleMemberAccess.Name.Identifier.ValueText, "CompletedTask", StringComparison.Ordinal) + && SemanticModel.GetSymbol(expression, CancellationToken) is IPropertySymbol propertySymbol + && IsTaskOrTaskOrT(propertySymbol.ContainingType); + } + else { - switch (memberInvocation.NameText) + SimpleMemberInvocationExpressionInfo memberInvocation = SyntaxInfo.SimpleMemberInvocationExpressionInfo(expression); + + if (memberInvocation.Success) { - 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)) + switch (memberInvocation.NameText) + { + case "FromCanceled": + case "FromException": + case "FromResult": { - return true; + if (SemanticModel.GetSymbol(expression, CancellationToken) is IMethodSymbol methodSymbol + && (methodSymbol.Arity == 0 || methodSymbol.Arity == 1) + && methodSymbol.Parameters.Length == 1 + && IsTaskOrTaskOrT(methodSymbol.ContainingType)) + { + return true; + } + + break; } - - break; - } + } } } - } - - return false; - } - - private static bool IsTaskOrTaskOrT(INamedTypeSymbol typeSymbol) - { - return typeSymbol.HasMetadataName(MetadataNames.System_Threading_Tasks_Task) - || typeSymbol.HasMetadataName(MetadataNames.System_Threading_Tasks_Task_T); - } - public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) - { - } - - public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) - { - } + return false; + } - public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) - { - } + private static bool IsTaskOrTaskOrT(INamedTypeSymbol typeSymbol) + { + return typeSymbol.HasMetadataName(MetadataNames.System_Threading_Tasks_Task) + || typeSymbol.HasMetadataName(MetadataNames.System_Threading_Tasks_Task_T); + } - public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) - { - } + public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + } - public static UseAsyncAwaitWalker GetInstance(SemanticModel semanticModel, CancellationToken cancellationToken) - { - UseAsyncAwaitWalker walker = _cachedInstance; + public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + } - if (walker != null) + public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { - _cachedInstance = null; } - else + + public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { - walker = new UseAsyncAwaitWalker(); } - walker.SemanticModel = semanticModel; - walker.CancellationToken = cancellationToken; + public static UseAsyncAwaitWalker GetInstance(SemanticModel semanticModel, CancellationToken cancellationToken) + { + UseAsyncAwaitWalker walker = _cachedInstance; - return walker; - } + if (walker is not null) + { + _cachedInstance = null; + } + else + { + walker = new UseAsyncAwaitWalker(); + } - public static void Free(UseAsyncAwaitWalker walker) - { - walker._shouldVisit = true; - walker._usingDeclarations.Clear(); - walker.ReturnStatement = null; - walker.SemanticModel = null; - walker.CancellationToken = default; + walker.SemanticModel = semanticModel; + walker.CancellationToken = cancellationToken; + + return walker; + } - _cachedInstance = walker; + public static void Free(UseAsyncAwaitWalker walker) + { + walker._shouldVisit = true; + walker._usingDeclarations.Clear(); + walker.ReturnStatement = null; + walker.SemanticModel = null; + walker.CancellationToken = default; + + _cachedInstance = walker; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseAttributeUsageAttributeAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseAttributeUsageAttributeAnalyzer.cs index f199f43e9e..ba94d5d489 100644 --- a/src/Analyzers/CSharp/Analysis/UseAttributeUsageAttributeAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseAttributeUsageAttributeAnalyzer.cs @@ -6,79 +6,80 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseAttributeUsageAttributeAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseAttributeUsageAttributeAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseAttributeUsageAttribute); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseAttributeUsageAttribute); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - INamedTypeSymbol attributeSymbol = startContext.Compilation.GetTypeByMetadataName("System.Attribute"); - INamedTypeSymbol attributeUsageAttributeSymbol = startContext.Compilation.GetTypeByMetadataName("System.AttributeUsageAttribute"); + base.Initialize(context); - if (attributeSymbol != null - && attributeUsageAttributeSymbol != null) + context.RegisterCompilationStartAction(startContext => { - startContext.RegisterSymbolAction( - nodeContext => AnalyzerNamedTypeSymbol(nodeContext, attributeSymbol, attributeUsageAttributeSymbol), - SymbolKind.NamedType); - } - }); - } + INamedTypeSymbol attributeSymbol = startContext.Compilation.GetTypeByMetadataName("System.Attribute"); + INamedTypeSymbol attributeUsageAttributeSymbol = startContext.Compilation.GetTypeByMetadataName("System.AttributeUsageAttribute"); + + if (attributeSymbol is not null + && attributeUsageAttributeSymbol is not null) + { + startContext.RegisterSymbolAction( + nodeContext => AnalyzerNamedTypeSymbol(nodeContext, attributeSymbol, attributeUsageAttributeSymbol), + SymbolKind.NamedType); + } + }); + } - public static void AnalyzerNamedTypeSymbol( - SymbolAnalysisContext context, - INamedTypeSymbol attributeSymbol, - INamedTypeSymbol attributeUsageAttributeSymbol) - { - var typeSymbol = (INamedTypeSymbol)context.Symbol; + public static void AnalyzerNamedTypeSymbol( + SymbolAnalysisContext context, + INamedTypeSymbol attributeSymbol, + INamedTypeSymbol attributeUsageAttributeSymbol) + { + var typeSymbol = (INamedTypeSymbol)context.Symbol; - if (typeSymbol.IsImplicitlyDeclared) - return; + if (typeSymbol.IsImplicitlyDeclared) + return; - if (typeSymbol.TypeKind != TypeKind.Class) - return; + if (typeSymbol.TypeKind != TypeKind.Class) + return; - if (!typeSymbol.Name.EndsWith("Attribute", StringComparison.Ordinal)) - return; + if (!typeSymbol.Name.EndsWith("Attribute", StringComparison.Ordinal)) + return; - if (typeSymbol.HasAttribute(attributeUsageAttributeSymbol)) - return; + if (typeSymbol.HasAttribute(attributeUsageAttributeSymbol)) + return; - INamedTypeSymbol baseType = typeSymbol.BaseType; + INamedTypeSymbol baseType = typeSymbol.BaseType; - while (baseType?.SpecialType == SpecialType.None) - { - if (SymbolEqualityComparer.Default.Equals(baseType, attributeSymbol)) + while (baseType?.SpecialType == SpecialType.None) { - var classDeclaration = (ClassDeclarationSyntax)typeSymbol.GetSyntax(context.CancellationToken); + if (SymbolEqualityComparer.Default.Equals(baseType, attributeSymbol)) + { + var classDeclaration = (ClassDeclarationSyntax)typeSymbol.GetSyntax(context.CancellationToken); - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAttributeUsageAttribute, classDeclaration.Identifier); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAttributeUsageAttribute, classDeclaration.Identifier); - return; - } + return; + } - if (baseType.HasAttribute(attributeUsageAttributeSymbol)) - return; + if (baseType.HasAttribute(attributeUsageAttributeSymbol)) + return; - baseType = baseType.BaseType; + baseType = baseType.BaseType; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs index 4bbd8892b0..02b89ae5ff 100644 --- a/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs @@ -12,674 +12,675 @@ using Roslynator.CSharp; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseAutoPropertyAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseAutoPropertyAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize( - ref _supportedDiagnostics, - DiagnosticRules.UseAutoProperty, - DiagnosticRules.UseAutoPropertyFadeOut); - } + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize( + ref _supportedDiagnostics, + DiagnosticRules.UseAutoProperty, + DiagnosticRules.UseAutoPropertyFadeOut); + } - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterSyntaxNodeAction( - c => - { - if (DiagnosticRules.UseAutoProperty.IsEffective(c)) - AnalyzePropertyDeclaration(c); - }, - SyntaxKind.PropertyDeclaration); - } + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) - { - var property = (PropertyDeclarationSyntax)context.Node; + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticRules.UseAutoProperty.IsEffective(c)) + AnalyzePropertyDeclaration(c); + }, + SyntaxKind.PropertyDeclaration); + } - if (property.ContainsDiagnostics) - return; + private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) + { + var property = (PropertyDeclarationSyntax)context.Node; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + if (property.ContainsDiagnostics) + return; - IFieldSymbol fieldSymbol = null; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - AccessorDeclarationSyntax getter = null; - AccessorDeclarationSyntax setter = null; + IFieldSymbol fieldSymbol = null; - ArrowExpressionClauseSyntax expressionBody = property.ExpressionBody; + AccessorDeclarationSyntax getter = null; + AccessorDeclarationSyntax setter = null; - if (expressionBody != null) - { - IdentifierNameSyntax identifierName = GetIdentifierNameFromExpression(expressionBody.Expression); + ArrowExpressionClauseSyntax expressionBody = property.ExpressionBody; - if (identifierName != null) - fieldSymbol = GetBackingFieldSymbol(identifierName, semanticModel, cancellationToken); - } - else - { - getter = property.Getter(); + if (expressionBody is not null) + { + IdentifierNameSyntax identifierName = GetIdentifierNameFromExpression(expressionBody.Expression); - if (getter != null) + if (identifierName is not null) + fieldSymbol = GetBackingFieldSymbol(identifierName, semanticModel, cancellationToken); + } + else { - setter = property.Setter(); + getter = property.Getter(); - if (setter != null) + if (getter is not null) { - fieldSymbol = GetBackingFieldSymbol(getter, setter, semanticModel, cancellationToken); - } - else - { - IdentifierNameSyntax identifierName = GetIdentifierNameFromGetter(getter); + setter = property.Setter(); + + if (setter is not null) + { + fieldSymbol = GetBackingFieldSymbol(getter, setter, semanticModel, cancellationToken); + } + else + { + IdentifierNameSyntax identifierName = GetIdentifierNameFromGetter(getter); - if (identifierName != null) - fieldSymbol = GetBackingFieldSymbol(identifierName, semanticModel, cancellationToken); + if (identifierName is not null) + fieldSymbol = GetBackingFieldSymbol(identifierName, semanticModel, cancellationToken); + } } } - } - - if (fieldSymbol == null) - return; - - var variableDeclarator = (VariableDeclaratorSyntax)fieldSymbol.GetSyntax(cancellationToken); - - if (variableDeclarator.SyntaxTree != property.SyntaxTree) - return; - if (variableDeclarator.IsParentKind(SyntaxKind.VariableDeclaration) - && variableDeclarator.Parent.Parent is FieldDeclarationSyntax fieldDeclaration - && fieldDeclaration.AttributeLists.Any()) - { - return; - } + if (fieldSymbol is null) + return; - if (!CheckPreprocessorDirectives(property)) - return; + var variableDeclarator = (VariableDeclaratorSyntax)fieldSymbol.GetSyntax(cancellationToken); - if (!CheckPreprocessorDirectives(variableDeclarator)) - return; + if (variableDeclarator.SyntaxTree != property.SyntaxTree) + return; - IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(property, cancellationToken); + if (variableDeclarator.IsParentKind(SyntaxKind.VariableDeclaration) + && variableDeclarator.Parent.Parent is FieldDeclarationSyntax fieldDeclaration + && fieldDeclaration.AttributeLists.Any()) + { + return; + } - if (propertySymbol?.IsStatic != fieldSymbol.IsStatic) - return; + if (!CheckPreprocessorDirectives(property)) + return; - if (!propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty) - return; + if (!CheckPreprocessorDirectives(variableDeclarator)) + return; - if (!SymbolEqualityComparer.Default.Equals(propertySymbol.Type, fieldSymbol.Type)) - return; + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(property, cancellationToken); - if (!SymbolEqualityComparer.Default.Equals(propertySymbol.ContainingType, fieldSymbol.ContainingType)) - return; + if (propertySymbol?.IsStatic != fieldSymbol.IsStatic) + return; - if (setter == null - && propertySymbol.IsOverride - && propertySymbol.OverriddenProperty?.SetMethod != null) - { - return; - } + if (!propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty) + return; - cancellationToken.ThrowIfCancellationRequested(); + if (!SymbolEqualityComparer.Default.Equals(propertySymbol.Type, fieldSymbol.Type)) + return; - foreach (AttributeData attributeData in fieldSymbol.GetAttributes()) - { - if (attributeData.AttributeClass.HasMetadataName(MetadataNames.System_NonSerializedAttribute)) + if (!SymbolEqualityComparer.Default.Equals(propertySymbol.ContainingType, fieldSymbol.ContainingType)) return; - } - if (HasStructLayoutAttributeWithExplicitKind(propertySymbol.ContainingType)) - return; + if (setter is null + && propertySymbol.IsOverride + && propertySymbol.OverriddenProperty?.SetMethod is not null) + { + return; + } - if (!IsFixableBackingField(property, propertySymbol, fieldSymbol, semanticModel, cancellationToken)) - return; + cancellationToken.ThrowIfCancellationRequested(); - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAutoProperty, property.Identifier); + foreach (AttributeData attributeData in fieldSymbol.GetAttributes()) + { + if (attributeData.AttributeClass.HasMetadataName(MetadataNames.System_NonSerializedAttribute)) + return; + } - if (property.ExpressionBody != null) - { - DiagnosticHelpers.ReportNode(context, DiagnosticRules.UseAutoPropertyFadeOut, property.ExpressionBody); - } - else - { - if (getter != null) - FadeOut(getter); + if (HasStructLayoutAttributeWithExplicitKind(propertySymbol.ContainingType)) + return; - if (setter != null) - FadeOut(setter); - } + if (!IsFixableBackingField(property, propertySymbol, fieldSymbol, semanticModel, cancellationToken)) + return; - void FadeOut(AccessorDeclarationSyntax accessor) - { - BlockSyntax body = accessor.Body; + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseAutoProperty, property.Identifier); - if (body != null) + if (property.ExpressionBody is not null) { - switch (body.Statements[0]) - { - case ReturnStatementSyntax returnStatement: - { - 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; - } - } - - CSharpDiagnosticHelpers.ReportBraces(context, DiagnosticRules.UseAutoPropertyFadeOut, body); + DiagnosticHelpers.ReportNode(context, DiagnosticRules.UseAutoPropertyFadeOut, property.ExpressionBody); } else { - DiagnosticHelpers.ReportNode(context, DiagnosticRules.UseAutoPropertyFadeOut, accessor.ExpressionBody); + if (getter is not null) + FadeOut(getter); + + if (setter is not null) + FadeOut(setter); } - } - } - private static bool IsFixableBackingField( - PropertyDeclarationSyntax propertyDeclaration, - IPropertySymbol propertySymbol, - IFieldSymbol fieldSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - INamedTypeSymbol containingType = fieldSymbol.ContainingType; + void FadeOut(AccessorDeclarationSyntax accessor) + { + BlockSyntax body = accessor.Body; - bool shouldSearchForReferenceInInstanceConstructor = !containingType.IsSealed - && !propertySymbol.IsStatic - && (propertySymbol.IsVirtual || propertySymbol.IsOverride); + if (body is not null) + { + switch (body.Statements[0]) + { + case ReturnStatementSyntax returnStatement: + { + 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; + } + } - var isFixable = false; - UseAutoPropertyWalker walker = null; + CSharpDiagnosticHelpers.ReportBraces(context, DiagnosticRules.UseAutoPropertyFadeOut, body); + } + else + { + DiagnosticHelpers.ReportNode(context, DiagnosticRules.UseAutoPropertyFadeOut, accessor.ExpressionBody); + } + } + } - try + private static bool IsFixableBackingField( + PropertyDeclarationSyntax propertyDeclaration, + IPropertySymbol propertySymbol, + IFieldSymbol fieldSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - walker = UseAutoPropertyWalker.GetInstance(); - - ImmutableArray syntaxReferences = containingType.DeclaringSyntaxReferences; + INamedTypeSymbol containingType = fieldSymbol.ContainingType; - if (syntaxReferences.Length == 1) - { - walker.SetValues(fieldSymbol, shouldSearchForReferenceInInstanceConstructor, semanticModel, cancellationToken); + bool shouldSearchForReferenceInInstanceConstructor = !containingType.IsSealed + && !propertySymbol.IsStatic + && (propertySymbol.IsVirtual || propertySymbol.IsOverride); - walker.Visit(propertyDeclaration.Parent); + var isFixable = false; + UseAutoPropertyWalker walker = null; - isFixable = walker.Success; - } - else + try { - foreach (SyntaxReference syntaxReference in syntaxReferences) - { - SyntaxNode typeDeclaration = syntaxReference.GetSyntax(cancellationToken); + walker = UseAutoPropertyWalker.GetInstance(); - if (typeDeclaration.SyntaxTree != semanticModel.SyntaxTree) - { - isFixable = false; - break; - } + ImmutableArray syntaxReferences = containingType.DeclaringSyntaxReferences; + if (syntaxReferences.Length == 1) + { walker.SetValues(fieldSymbol, shouldSearchForReferenceInInstanceConstructor, semanticModel, cancellationToken); - walker.Visit(typeDeclaration); + walker.Visit(propertyDeclaration.Parent); isFixable = walker.Success; - - if (!isFixable) - break; } - } - } - finally - { - if (walker != null) - UseAutoPropertyWalker.Free(walker); - } + else + { + foreach (SyntaxReference syntaxReference in syntaxReferences) + { + SyntaxNode typeDeclaration = syntaxReference.GetSyntax(cancellationToken); - return isFixable; - } + if (typeDeclaration.SyntaxTree != semanticModel.SyntaxTree) + { + isFixable = false; + break; + } - private static IFieldSymbol GetBackingFieldSymbol( - IdentifierNameSyntax identifierName, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ISymbol symbol = semanticModel.GetSymbol(identifierName, cancellationToken); + walker.SetValues(fieldSymbol, shouldSearchForReferenceInInstanceConstructor, semanticModel, cancellationToken); - if (symbol?.DeclaredAccessibility == Accessibility.Private - && symbol.Kind == SymbolKind.Field) - { - var fieldSymbol = (IFieldSymbol)symbol; + walker.Visit(typeDeclaration); + + isFixable = walker.Success; - if (fieldSymbol.IsReadOnly - && !fieldSymbol.IsVolatile) + if (!isFixable) + break; + } + } + } + finally { - return fieldSymbol; + if (walker is not null) + UseAutoPropertyWalker.Free(walker); } + + return isFixable; } - return null; - } + private static IFieldSymbol GetBackingFieldSymbol( + IdentifierNameSyntax identifierName, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + ISymbol symbol = semanticModel.GetSymbol(identifierName, cancellationToken); - private static IFieldSymbol GetBackingFieldSymbol( - AccessorDeclarationSyntax getter, - AccessorDeclarationSyntax setter, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - IdentifierNameSyntax getterName = GetIdentifierNameFromGetter(getter); + if (symbol?.DeclaredAccessibility == Accessibility.Private + && symbol.Kind == SymbolKind.Field) + { + var fieldSymbol = (IFieldSymbol)symbol; + + if (fieldSymbol.IsReadOnly + && !fieldSymbol.IsVolatile) + { + return fieldSymbol; + } + } - if (getterName == null) return null; + } - IdentifierNameSyntax setterName = GetIdentifierNameFromSetter(setter); + private static IFieldSymbol GetBackingFieldSymbol( + AccessorDeclarationSyntax getter, + AccessorDeclarationSyntax setter, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + IdentifierNameSyntax getterName = GetIdentifierNameFromGetter(getter); - if (setterName == null) - return null; + if (getterName is null) + return null; - ISymbol getterSymbol = semanticModel.GetSymbol(getterName, cancellationToken); + IdentifierNameSyntax setterName = GetIdentifierNameFromSetter(setter); - if (getterSymbol?.DeclaredAccessibility != Accessibility.Private) - return null; + if (setterName is null) + return null; - if (getterSymbol.Kind != SymbolKind.Field) - return null; + ISymbol getterSymbol = semanticModel.GetSymbol(getterName, cancellationToken); - var fieldSymbol = (IFieldSymbol)getterSymbol; + if (getterSymbol?.DeclaredAccessibility != Accessibility.Private) + return null; - if (fieldSymbol.IsVolatile) - return null; + if (getterSymbol.Kind != SymbolKind.Field) + return null; - ISymbol setterSymbol = semanticModel.GetSymbol(setterName, cancellationToken); + var fieldSymbol = (IFieldSymbol)getterSymbol; - if (SymbolEqualityComparer.Default.Equals(fieldSymbol, setterSymbol)) - return fieldSymbol; + if (fieldSymbol.IsVolatile) + return null; - return null; - } + ISymbol setterSymbol = semanticModel.GetSymbol(setterName, cancellationToken); - private static IdentifierNameSyntax GetIdentifierNameFromGetter(AccessorDeclarationSyntax getter) - { - if (getter != null) - { - BlockSyntax body = getter.Body; + if (SymbolEqualityComparer.Default.Equals(fieldSymbol, setterSymbol)) + return fieldSymbol; - if (body != null) - { - if (body.Statements.SingleOrDefault(shouldThrow: false) is ReturnStatementSyntax returnStatement) - { - return GetIdentifierNameFromExpression(returnStatement.Expression); - } - } - else - { - return GetIdentifierNameFromExpression(getter.ExpressionBody?.Expression); - } + return null; } - return null; - } - - private static IdentifierNameSyntax GetIdentifierNameFromSetter(AccessorDeclarationSyntax setter) - { - if (setter != null) + private static IdentifierNameSyntax GetIdentifierNameFromGetter(AccessorDeclarationSyntax getter) { - BlockSyntax body = setter.Body; - - if (body != null) + if (getter is not null) { - if (body.Statements.SingleOrDefault(shouldThrow: false) is ExpressionStatementSyntax expressionStatement) + BlockSyntax body = getter.Body; + + if (body is not null) + { + if (body.Statements.SingleOrDefault(shouldThrow: false) is ReturnStatementSyntax returnStatement) + { + return GetIdentifierNameFromExpression(returnStatement.Expression); + } + } + else { - return GetIdentifierName(expressionStatement.Expression); + return GetIdentifierNameFromExpression(getter.ExpressionBody?.Expression); } } - else - { - return GetIdentifierName(setter.ExpressionBody?.Expression); - } - } - return null; + return null; + } - static IdentifierNameSyntax GetIdentifierName(ExpressionSyntax expression) + private static IdentifierNameSyntax GetIdentifierNameFromSetter(AccessorDeclarationSyntax setter) { - if (expression?.Kind() == SyntaxKind.SimpleAssignmentExpression) + if (setter is not null) { - var assignment = (AssignmentExpressionSyntax)expression; - ExpressionSyntax right = assignment.Right; + BlockSyntax body = setter.Body; - if (right.IsKind(SyntaxKind.IdentifierName) - && ((IdentifierNameSyntax)right).Identifier.ValueText == "value") + if (body is not null) { - return GetIdentifierNameFromExpression(assignment.Left); + if (body.Statements.SingleOrDefault(shouldThrow: false) is ExpressionStatementSyntax expressionStatement) + { + return GetIdentifierName(expressionStatement.Expression); + } + } + else + { + return GetIdentifierName(setter.ExpressionBody?.Expression); } } return null; - } - } - private static IdentifierNameSyntax GetIdentifierNameFromExpression(ExpressionSyntax expression) - { - switch (expression?.Kind()) - { - case SyntaxKind.IdentifierName: - { - return (IdentifierNameSyntax)expression; - } - case SyntaxKind.SimpleMemberAccessExpression: + static IdentifierNameSyntax GetIdentifierName(ExpressionSyntax expression) + { + if (expression?.Kind() == SyntaxKind.SimpleAssignmentExpression) { - var memberAccess = (MemberAccessExpressionSyntax)expression; + var assignment = (AssignmentExpressionSyntax)expression; + ExpressionSyntax right = assignment.Right; - if (memberAccess.Expression?.Kind() == SyntaxKind.ThisExpression) + if (right.IsKind(SyntaxKind.IdentifierName) + && ((IdentifierNameSyntax)right).Identifier.ValueText == "value") { - SimpleNameSyntax name = memberAccess.Name; - - if (name.IsKind(SyntaxKind.IdentifierName)) - return (IdentifierNameSyntax)name; + return GetIdentifierNameFromExpression(assignment.Left); } - - break; } - } - - return null; - } - private static bool HasStructLayoutAttributeWithExplicitKind(INamedTypeSymbol typeSymbol) - { - AttributeData attribute = typeSymbol.GetAttribute(MetadataNames.System_Runtime_InteropServices_StructLayoutAttribute); + return null; + } + } - if (attribute != null) + private static IdentifierNameSyntax GetIdentifierNameFromExpression(ExpressionSyntax expression) { - TypedConstant typedConstant = attribute.ConstructorArguments.SingleOrDefault(shouldThrow: false); + switch (expression?.Kind()) + { + case SyntaxKind.IdentifierName: + { + return (IdentifierNameSyntax)expression; + } + case SyntaxKind.SimpleMemberAccessExpression: + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - return typedConstant.Type?.HasMetadataName(MetadataNames.System_Runtime_InteropServices_LayoutKind) == true - && (((LayoutKind)typedConstant.Value) == LayoutKind.Explicit); - } + if (memberAccess.Expression?.Kind() == SyntaxKind.ThisExpression) + { + SimpleNameSyntax name = memberAccess.Name; - return false; - } + if (name.IsKind(SyntaxKind.IdentifierName)) + return (IdentifierNameSyntax)name; + } - private static bool CheckPreprocessorDirectives(PropertyDeclarationSyntax property) - { - ArrowExpressionClauseSyntax expressionBody = property.ExpressionBody; + break; + } + } - if (expressionBody != null) - { - if (expressionBody.SpanContainsDirectives()) - return false; + return null; } - else if (property.AccessorList.Accessors.Any(f => f.SpanContainsDirectives())) + + private static bool HasStructLayoutAttributeWithExplicitKind(INamedTypeSymbol typeSymbol) { - return false; - } + AttributeData attribute = typeSymbol.GetAttribute(MetadataNames.System_Runtime_InteropServices_StructLayoutAttribute); - return true; - } + if (attribute is not null) + { + TypedConstant typedConstant = attribute.ConstructorArguments.SingleOrDefault(shouldThrow: false); - private static bool CheckPreprocessorDirectives(VariableDeclaratorSyntax declarator) - { - var variableDeclaration = (VariableDeclarationSyntax)declarator.Parent; + return typedConstant.Type?.HasMetadataName(MetadataNames.System_Runtime_InteropServices_LayoutKind) == true + && (((LayoutKind)typedConstant.Value) == LayoutKind.Explicit); + } - if (variableDeclaration.Variables.Count == 1) + return false; + } + + private static bool CheckPreprocessorDirectives(PropertyDeclarationSyntax property) { - if (variableDeclaration.Parent.SpanContainsDirectives()) + ArrowExpressionClauseSyntax expressionBody = property.ExpressionBody; + + if (expressionBody is not null) + { + if (expressionBody.SpanContainsDirectives()) + return false; + } + else if (property.AccessorList.Accessors.Any(f => f.SpanContainsDirectives())) + { return false; + } + + return true; } - else if (declarator.SpanContainsDirectives()) + + private static bool CheckPreprocessorDirectives(VariableDeclaratorSyntax declarator) { - return false; - } + var variableDeclaration = (VariableDeclarationSyntax)declarator.Parent; - return true; - } + if (variableDeclaration.Variables.Count == 1) + { + if (variableDeclaration.Parent.SpanContainsDirectives()) + return false; + } + else if (declarator.SpanContainsDirectives()) + { + return false; + } - private class UseAutoPropertyWalker : CSharpSyntaxNodeWalker - { - private bool _isInInstanceConstructor; + return true; + } - public IFieldSymbol FieldSymbol { get; private set; } + private class UseAutoPropertyWalker : CSharpSyntaxNodeWalker + { + private bool _isInInstanceConstructor; - public bool ShouldSearchForReferenceInInstanceConstructor { get; private set; } + public IFieldSymbol FieldSymbol { get; private set; } - public SemanticModel SemanticModel { get; private set; } + public bool ShouldSearchForReferenceInInstanceConstructor { get; private set; } - public CancellationToken CancellationToken { get; private set; } + public SemanticModel SemanticModel { get; private set; } - public bool Success { get; set; } = true; + public CancellationToken CancellationToken { get; private set; } - protected override bool ShouldVisit => Success; + public bool Success { get; set; } = true; - public void SetValues( - IFieldSymbol fieldSymbol, - bool shouldSearchForReferenceInInstanceConstructor, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - FieldSymbol = fieldSymbol; - ShouldSearchForReferenceInInstanceConstructor = shouldSearchForReferenceInInstanceConstructor; - SemanticModel = semanticModel; - CancellationToken = cancellationToken; - Success = true; - } + protected override bool ShouldVisit => Success; - public override void VisitArgument(ArgumentSyntax node) - { - CancellationToken.ThrowIfCancellationRequested(); + public void SetValues( + IFieldSymbol fieldSymbol, + bool shouldSearchForReferenceInInstanceConstructor, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + FieldSymbol = fieldSymbol; + ShouldSearchForReferenceInInstanceConstructor = shouldSearchForReferenceInInstanceConstructor; + SemanticModel = semanticModel; + CancellationToken = cancellationToken; + Success = true; + } - if (node.RefOrOutKeyword.IsKind(SyntaxKind.RefKeyword, SyntaxKind.OutKeyword)) + public override void VisitArgument(ArgumentSyntax node) { - ExpressionSyntax expression = node.Expression?.WalkDownParentheses(); + CancellationToken.ThrowIfCancellationRequested(); - switch (expression?.Kind()) + if (node.RefOrOutKeyword.IsKind(SyntaxKind.RefKeyword, SyntaxKind.OutKeyword)) { - case SyntaxKind.IdentifierName: - { - if (IsBackingFieldReference((IdentifierNameSyntax)expression)) - Success = false; + ExpressionSyntax expression = node.Expression?.WalkDownParentheses(); - return; - } - case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccessExpression = (MemberAccessExpressionSyntax)expression; + switch (expression?.Kind()) + { + case SyntaxKind.IdentifierName: + { + if (IsBackingFieldReference((IdentifierNameSyntax)expression)) + Success = false; - if (memberAccessExpression.Expression.IsKind(SyntaxKind.ThisExpression)) + return; + } + case SyntaxKind.SimpleMemberAccessExpression: { - SimpleNameSyntax name = memberAccessExpression.Name; + var memberAccessExpression = (MemberAccessExpressionSyntax)expression; - if (name.IsKind(SyntaxKind.IdentifierName)) + if (memberAccessExpression.Expression.IsKind(SyntaxKind.ThisExpression)) { - if (IsBackingFieldReference((IdentifierNameSyntax)name)) - Success = false; + SimpleNameSyntax name = memberAccessExpression.Name; + + if (name.IsKind(SyntaxKind.IdentifierName)) + { + if (IsBackingFieldReference((IdentifierNameSyntax)name)) + Success = false; - return; + return; + } } - } - break; - } + break; + } + } } + + base.VisitArgument(node); } - base.VisitArgument(node); - } + public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) + { + CancellationToken.ThrowIfCancellationRequested(); - public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) - { - CancellationToken.ThrowIfCancellationRequested(); + Debug.Assert(!_isInInstanceConstructor); - Debug.Assert(!_isInInstanceConstructor); + if (ShouldSearchForReferenceInInstanceConstructor + && !node.Modifiers.Contains(SyntaxKind.StaticKeyword)) + { + _isInInstanceConstructor = true; + } - if (ShouldSearchForReferenceInInstanceConstructor - && !node.Modifiers.Contains(SyntaxKind.StaticKeyword)) - { - _isInInstanceConstructor = true; + base.VisitConstructorDeclaration(node); + _isInInstanceConstructor = false; } - base.VisitConstructorDeclaration(node); - _isInInstanceConstructor = false; - } - - public override void VisitAssignmentExpression(AssignmentExpressionSyntax node) - { - if (FieldSymbol.Type.TypeKind == TypeKind.Struct - && IsAssigned(node.Left)) - { - Success = false; - } - else + public override void VisitAssignmentExpression(AssignmentExpressionSyntax node) { - base.VisitAssignmentExpression(node); + if (FieldSymbol.Type.TypeKind == TypeKind.Struct + && IsAssigned(node.Left)) + { + Success = false; + } + else + { + base.VisitAssignmentExpression(node); + } } - } - public override void VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) - { - if (node.IsKind(SyntaxKind.PreIncrementExpression, SyntaxKind.PreDecrementExpression) - && FieldSymbol.Type.TypeKind == TypeKind.Struct - && IsAssigned(node.Operand)) - { - Success = false; - } - else + public override void VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) { - base.VisitPrefixUnaryExpression(node); + if (node.IsKind(SyntaxKind.PreIncrementExpression, SyntaxKind.PreDecrementExpression) + && FieldSymbol.Type.TypeKind == TypeKind.Struct + && IsAssigned(node.Operand)) + { + Success = false; + } + else + { + base.VisitPrefixUnaryExpression(node); + } } - } - public override void VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) - { - if (node.IsKind(SyntaxKind.PostIncrementExpression, SyntaxKind.PostDecrementExpression) - && FieldSymbol.Type.TypeKind == TypeKind.Struct - && IsAssigned(node.Operand)) + public override void VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) { - Success = false; - } - else - { - base.VisitPostfixUnaryExpression(node); + if (node.IsKind(SyntaxKind.PostIncrementExpression, SyntaxKind.PostDecrementExpression) + && FieldSymbol.Type.TypeKind == TypeKind.Struct + && IsAssigned(node.Operand)) + { + Success = false; + } + else + { + base.VisitPostfixUnaryExpression(node); + } } - } - private bool IsAssigned(ExpressionSyntax expression) - { - switch (expression.Kind()) + private bool IsAssigned(ExpressionSyntax expression) { - case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccessExpression = (MemberAccessExpressionSyntax)expression; - expression = memberAccessExpression.Expression; - - break; - } - case SyntaxKind.ElementAccessExpression: - { - var elementAccessExpression = (ElementAccessExpressionSyntax)expression; - expression = elementAccessExpression.Expression; + switch (expression.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + { + var memberAccessExpression = (MemberAccessExpressionSyntax)expression; + expression = memberAccessExpression.Expression; - break; - } - default: - { - return false; - } - } + break; + } + case SyntaxKind.ElementAccessExpression: + { + var elementAccessExpression = (ElementAccessExpressionSyntax)expression; + expression = elementAccessExpression.Expression; - switch (expression.Kind()) - { - case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccessExpression = ((MemberAccessExpressionSyntax)expression); + break; + } + default: + { + return false; + } + } - if (memberAccessExpression.Expression.IsKind(SyntaxKind.ThisExpression) - && memberAccessExpression.Name.IsKind(SyntaxKind.IdentifierName) - && IsBackingFieldReference((IdentifierNameSyntax)memberAccessExpression.Name)) + switch (expression.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: { - return true; + var memberAccessExpression = ((MemberAccessExpressionSyntax)expression); + + 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; - break; - } - case SyntaxKind.IdentifierName: - { - if (IsBackingFieldReference((IdentifierNameSyntax)expression)) - return true; + break; + } + } - break; - } + return false; } - return false; - } - - public override void VisitIdentifierName(IdentifierNameSyntax node) - { - if (_isInInstanceConstructor - && IsBackingFieldReference(node)) + public override void VisitIdentifierName(IdentifierNameSyntax node) { - Success = false; + if (_isInInstanceConstructor + && IsBackingFieldReference(node)) + { + Success = false; + } + else + { + base.VisitIdentifierName(node); + } } - else + + private bool IsBackingFieldReference(IdentifierNameSyntax identifierName) { - base.VisitIdentifierName(node); + return string.Equals(identifierName.Identifier.ValueText, FieldSymbol.Name, StringComparison.Ordinal) + && SymbolEqualityComparer.Default.Equals(SemanticModel.GetSymbol(identifierName, CancellationToken), FieldSymbol); } - } - private bool IsBackingFieldReference(IdentifierNameSyntax identifierName) - { - return string.Equals(identifierName.Identifier.ValueText, FieldSymbol.Name, StringComparison.Ordinal) - && SymbolEqualityComparer.Default.Equals(SemanticModel.GetSymbol(identifierName, CancellationToken), FieldSymbol); - } + [ThreadStatic] + private static UseAutoPropertyWalker _cachedInstance; - [ThreadStatic] - private static UseAutoPropertyWalker _cachedInstance; + public static UseAutoPropertyWalker GetInstance() + { + UseAutoPropertyWalker walker = _cachedInstance; - public static UseAutoPropertyWalker GetInstance() - { - UseAutoPropertyWalker walker = _cachedInstance; + if (walker is not null) + { + Debug.Assert(walker.FieldSymbol is null); + Debug.Assert(walker.SemanticModel is null); + Debug.Assert(walker.CancellationToken == default); - if (walker != null) - { - Debug.Assert(walker.FieldSymbol == null); - Debug.Assert(walker.SemanticModel == null); - Debug.Assert(walker.CancellationToken == default); + _cachedInstance = null; + return walker; + } - _cachedInstance = null; - return walker; + return new UseAutoPropertyWalker(); } - return new UseAutoPropertyWalker(); - } - - public static void Free(UseAutoPropertyWalker walker) - { - walker.SetValues( - default(IFieldSymbol), - false, - default(SemanticModel), - default(CancellationToken)); + public static void Free(UseAutoPropertyWalker walker) + { + walker.SetValues( + default(IFieldSymbol), + false, + default(SemanticModel), + default(CancellationToken)); - _cachedInstance = walker; + _cachedInstance = walker; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseBlockBodyOrExpressionBodyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseBlockBodyOrExpressionBodyAnalyzer.cs index 40085c7d43..4a03f7f1f9 100644 --- a/src/Analyzers/CSharp/Analysis/UseBlockBodyOrExpressionBodyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseBlockBodyOrExpressionBodyAnalyzer.cs @@ -8,220 +8,123 @@ using Roslynator.CSharp; using Roslynator.CSharp.CodeStyle; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseBlockBodyOrExpressionBodyAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseBlockBodyOrExpressionBodyAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseBlockBodyOrExpressionBody); - } + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseBlockBodyOrExpressionBody); + } - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); - startContext.RegisterSyntaxNodeAction(f => AnalyzePropertyDeclaration(f), SyntaxKind.PropertyDeclaration); - startContext.RegisterSyntaxNodeAction(f => AnalyzeIndexerDeclaration(f), SyntaxKind.IndexerDeclaration); - startContext.RegisterSyntaxNodeAction(f => AnalyzeOperatorDeclaration(f), SyntaxKind.OperatorDeclaration); - startContext.RegisterSyntaxNodeAction(f => AnalyzeConversionOperatorDeclaration(f), SyntaxKind.ConversionOperatorDeclaration); - startContext.RegisterSyntaxNodeAction(f => AnalyzeConstructorDeclaration(f), SyntaxKind.ConstructorDeclaration); - startContext.RegisterSyntaxNodeAction(f => AnalyzeDestructorDeclaration(f), SyntaxKind.DestructorDeclaration); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); - - startContext.RegisterSyntaxNodeAction( - f => AnalyzeAccessorDeclaration(f), - SyntaxKind.GetAccessorDeclaration, - SyntaxKind.SetAccessorDeclaration, - SyntaxKind.AddAccessorDeclaration, - SyntaxKind.RemoveAccessorDeclaration, - SyntaxKind.InitAccessorDeclaration); - }); - } - - private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) - { - var methodDeclaration = (MethodDeclarationSyntax)context.Node; - - BlockSyntax body = methodDeclaration.Body; - if (body != null) - { - if (body.ContainsDirectives) - return; - - BodyStyle style = context.GetBodyStyle(); - - if (style.IsDefault) - return; - - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body); - - if (!analysis.Success) - return; - - if (!style.UseExpression) - return; + base.Initialize(context); - if (style.UseBlockWhenDeclarationIsMultiLine == true - && methodDeclaration.SyntaxTree.IsMultiLineSpan(methodDeclaration.HeaderSpan())) + context.RegisterCompilationStartAction(startContext => { - return; - } + if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) + return; - AnalyzeBlock(context, body, analysis, style); + startContext.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); + startContext.RegisterSyntaxNodeAction(f => AnalyzePropertyDeclaration(f), SyntaxKind.PropertyDeclaration); + startContext.RegisterSyntaxNodeAction(f => AnalyzeIndexerDeclaration(f), SyntaxKind.IndexerDeclaration); + startContext.RegisterSyntaxNodeAction(f => AnalyzeOperatorDeclaration(f), SyntaxKind.OperatorDeclaration); + startContext.RegisterSyntaxNodeAction(f => AnalyzeConversionOperatorDeclaration(f), SyntaxKind.ConversionOperatorDeclaration); + startContext.RegisterSyntaxNodeAction(f => AnalyzeConstructorDeclaration(f), SyntaxKind.ConstructorDeclaration); + startContext.RegisterSyntaxNodeAction(f => AnalyzeDestructorDeclaration(f), SyntaxKind.DestructorDeclaration); + startContext.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); + + startContext.RegisterSyntaxNodeAction( + f => AnalyzeAccessorDeclaration(f), + SyntaxKind.GetAccessorDeclaration, + SyntaxKind.SetAccessorDeclaration, + SyntaxKind.AddAccessorDeclaration, + SyntaxKind.RemoveAccessorDeclaration, + SyntaxKind.InitAccessorDeclaration); + }); } - else + + private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) { - ArrowExpressionClauseSyntax expressionBody = methodDeclaration.ExpressionBody; + var methodDeclaration = (MethodDeclarationSyntax)context.Node; - if (expressionBody?.ContainsDirectives == false) + BlockSyntax body = methodDeclaration.Body; + if (body is not null) { + if (body.ContainsDirectives) + return; + BodyStyle style = context.GetBodyStyle(); if (style.IsDefault) return; - if (style.UseBlock) - { - ReportDiagnostic(context, expressionBody); + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body); + + if (!analysis.Success) + return; + + if (!style.UseExpression) return; - } if (style.UseBlockWhenDeclarationIsMultiLine == true && methodDeclaration.SyntaxTree.IsMultiLineSpan(methodDeclaration.HeaderSpan())) { - ReportDiagnostic(context, expressionBody); return; } - if (style.UseBlockWhenExpressionIsMultiLine == true - && expressionBody.Expression?.IsMultiLine() == true) - { - ReportDiagnostic(context, expressionBody); - } + AnalyzeBlock(context, body, analysis, style); } - } - } - - private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) - { - var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; - - ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - - if (expressionBody?.ContainsDirectives == false) - { - BodyStyle style = context.GetBodyStyle(); - - if (style.IsDefault) - return; - - if (style.UseBlock) + else { - ReportDiagnostic(context, expressionBody); - return; - } - - if (style.UseBlockWhenDeclarationIsMultiLine == true - && propertyDeclaration.SyntaxTree.IsMultiLineSpan(propertyDeclaration.HeaderSpan())) - { - ReportDiagnostic(context, expressionBody); - return; - } - - if (style.UseBlockWhenExpressionIsMultiLine == true - && expressionBody.Expression?.IsMultiLine() == true) - { - ReportDiagnostic(context, expressionBody); - } - } - } - - private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) - { - var indexerDeclaration = (IndexerDeclarationSyntax)context.Node; - - ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; - - if (expressionBody?.ContainsDirectives == false) - { - BodyStyle style = context.GetBodyStyle(); - - if (style.IsDefault) - return; - - if (style.UseBlock) - { - ReportDiagnostic(context, expressionBody); - return; - } - - if (style.UseBlockWhenDeclarationIsMultiLine == true - && indexerDeclaration.SyntaxTree.IsMultiLineSpan(indexerDeclaration.HeaderSpan())) - { - ReportDiagnostic(context, expressionBody); - return; - } + ArrowExpressionClauseSyntax expressionBody = methodDeclaration.ExpressionBody; - if (style.UseBlockWhenExpressionIsMultiLine == true - && expressionBody.Expression?.IsMultiLine() == true) - { - ReportDiagnostic(context, expressionBody); + if (expressionBody?.ContainsDirectives == false) + { + BodyStyle style = context.GetBodyStyle(); + + if (style.IsDefault) + return; + + if (style.UseBlock) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenDeclarationIsMultiLine == true + && methodDeclaration.SyntaxTree.IsMultiLineSpan(methodDeclaration.HeaderSpan())) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenExpressionIsMultiLine == true + && expressionBody.Expression?.IsMultiLine() == true) + { + ReportDiagnostic(context, expressionBody); + } + } } } - } - - private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context) - { - var operatorDeclaration = (OperatorDeclarationSyntax)context.Node; - BlockSyntax body = operatorDeclaration.Body; - if (body != null) + private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) { - if (body.ContainsDirectives) - return; + var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; - BodyStyle style = context.GetBodyStyle(); - - if (style.IsDefault) - return; - - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body, allowExpressionStatement: false); - - if (!analysis.Success) - return; - - if (!style.UseExpression) - return; - - if (style.UseBlockWhenDeclarationIsMultiLine == true - && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) - { - return; - } - - AnalyzeBlock(context, body, analysis, style); - } - else - { - ArrowExpressionClauseSyntax expressionBody = operatorDeclaration.ExpressionBody; + ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; if (expressionBody?.ContainsDirectives == false) { @@ -237,7 +140,7 @@ private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context } if (style.UseBlockWhenDeclarationIsMultiLine == true - && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) + && propertyDeclaration.SyntaxTree.IsMultiLineSpan(propertyDeclaration.HeaderSpan())) { ReportDiagnostic(context, expressionBody); return; @@ -250,42 +153,12 @@ private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context } } } - } - private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisContext context) - { - var operatorDeclaration = (ConversionOperatorDeclarationSyntax)context.Node; - - BlockSyntax body = operatorDeclaration.Body; - if (body != null) + private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) { - if (body.ContainsDirectives) - return; - - BodyStyle style = context.GetBodyStyle(); - - if (style.IsDefault) - return; - - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body, allowExpressionStatement: false); - - if (!analysis.Success) - return; - - if (!style.UseExpression) - return; - - if (style.UseBlockWhenDeclarationIsMultiLine == true - && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) - { - return; - } + var indexerDeclaration = (IndexerDeclarationSyntax)context.Node; - AnalyzeBlock(context, body, analysis, style); - } - else - { - ArrowExpressionClauseSyntax expressionBody = operatorDeclaration.ExpressionBody; + ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; if (expressionBody?.ContainsDirectives == false) { @@ -301,7 +174,7 @@ private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisConte } if (style.UseBlockWhenDeclarationIsMultiLine == true - && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) + && indexerDeclaration.SyntaxTree.IsMultiLineSpan(indexerDeclaration.HeaderSpan())) { ReportDiagnostic(context, expressionBody); return; @@ -314,359 +187,487 @@ private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisConte } } } - } - private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext context) - { - var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node; - - BlockSyntax body = constructorDeclaration.Body; - if (body != null) + private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context) { - if (body.ContainsDirectives) - return; - - BodyStyle style = context.GetBodyStyle(); + var operatorDeclaration = (OperatorDeclarationSyntax)context.Node; - if (style.IsDefault) - return; - - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body); - - if (!analysis.Success) - return; - - if (!style.UseExpression) - return; - - if (style.UseBlockWhenDeclarationIsMultiLine == true - && constructorDeclaration.SyntaxTree.IsMultiLineSpan(constructorDeclaration.HeaderSpan())) + BlockSyntax body = operatorDeclaration.Body; + if (body is not null) { - return; - } - - AnalyzeBlock(context, body, analysis, style); - } - else - { - ArrowExpressionClauseSyntax expressionBody = constructorDeclaration.ExpressionBody; + if (body.ContainsDirectives) + return; - if (expressionBody?.ContainsDirectives == false) - { BodyStyle style = context.GetBodyStyle(); if (style.IsDefault) return; - if (style.UseBlock) - { - ReportDiagnostic(context, expressionBody); + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body, allowExpressionStatement: false); + + if (!analysis.Success) + return; + + if (!style.UseExpression) return; - } if (style.UseBlockWhenDeclarationIsMultiLine == true - && constructorDeclaration.SyntaxTree.IsMultiLineSpan(constructorDeclaration.HeaderSpan())) + && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) { - ReportDiagnostic(context, expressionBody); return; } - if (style.UseBlockWhenExpressionIsMultiLine == true - && expressionBody.Expression?.IsMultiLine() == true) + AnalyzeBlock(context, body, analysis, style); + } + else + { + ArrowExpressionClauseSyntax expressionBody = operatorDeclaration.ExpressionBody; + + if (expressionBody?.ContainsDirectives == false) { - ReportDiagnostic(context, expressionBody); + BodyStyle style = context.GetBodyStyle(); + + if (style.IsDefault) + return; + + if (style.UseBlock) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenDeclarationIsMultiLine == true + && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenExpressionIsMultiLine == true + && expressionBody.Expression?.IsMultiLine() == true) + { + ReportDiagnostic(context, expressionBody); + } } } } - } - - private static void AnalyzeDestructorDeclaration(SyntaxNodeAnalysisContext context) - { - var destructorDeclaration = (DestructorDeclarationSyntax)context.Node; - BlockSyntax body = destructorDeclaration.Body; - if (body != null) + private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisContext context) { - if (body.ContainsDirectives) - return; - - BodyStyle style = context.GetBodyStyle(); - - if (style.IsDefault) - return; - - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body); + var operatorDeclaration = (ConversionOperatorDeclarationSyntax)context.Node; - if (!analysis.Success) - return; - - if (!style.UseExpression) - return; - - if (style.UseBlockWhenDeclarationIsMultiLine == true - && destructorDeclaration.SyntaxTree.IsMultiLineSpan(destructorDeclaration.HeaderSpan())) + BlockSyntax body = operatorDeclaration.Body; + if (body is not null) { - return; - } - - AnalyzeBlock(context, body, analysis, style); - } - else - { - ArrowExpressionClauseSyntax expressionBody = destructorDeclaration.ExpressionBody; + if (body.ContainsDirectives) + return; - if (expressionBody?.ContainsDirectives == false) - { BodyStyle style = context.GetBodyStyle(); if (style.IsDefault) return; - if (style.UseBlock) - { - ReportDiagnostic(context, expressionBody); + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body, allowExpressionStatement: false); + + if (!analysis.Success) + return; + + if (!style.UseExpression) return; - } if (style.UseBlockWhenDeclarationIsMultiLine == true - && destructorDeclaration.SyntaxTree.IsMultiLineSpan(destructorDeclaration.HeaderSpan())) + && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) { - ReportDiagnostic(context, expressionBody); return; } - if (style.UseBlockWhenExpressionIsMultiLine == true - && expressionBody.Expression?.IsMultiLine() == true) + AnalyzeBlock(context, body, analysis, style); + } + else + { + ArrowExpressionClauseSyntax expressionBody = operatorDeclaration.ExpressionBody; + + if (expressionBody?.ContainsDirectives == false) { - ReportDiagnostic(context, expressionBody); + BodyStyle style = context.GetBodyStyle(); + + if (style.IsDefault) + return; + + if (style.UseBlock) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenDeclarationIsMultiLine == true + && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenExpressionIsMultiLine == true + && expressionBody.Expression?.IsMultiLine() == true) + { + ReportDiagnostic(context, expressionBody); + } } } } - } - - private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) - { - var localFunction = (LocalFunctionStatementSyntax)context.Node; - BlockSyntax body = localFunction.Body; - if (body != null) + private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext context) { - if (body.ContainsDirectives) - return; + var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node; - BodyStyle style = context.GetBodyStyle(); + BlockSyntax body = constructorDeclaration.Body; + if (body is not null) + { + if (body.ContainsDirectives) + return; - if (style.IsDefault) - return; + BodyStyle style = context.GetBodyStyle(); - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body); + if (style.IsDefault) + return; - if (!analysis.Success) - return; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body); - if (!style.UseExpression) - return; + if (!analysis.Success) + return; - if (style.UseBlockWhenDeclarationIsMultiLine == true - && localFunction.SyntaxTree.IsMultiLineSpan(localFunction.HeaderSpan())) - { - return; + if (!style.UseExpression) + return; + + if (style.UseBlockWhenDeclarationIsMultiLine == true + && constructorDeclaration.SyntaxTree.IsMultiLineSpan(constructorDeclaration.HeaderSpan())) + { + return; + } + + AnalyzeBlock(context, body, analysis, style); } + else + { + ArrowExpressionClauseSyntax expressionBody = constructorDeclaration.ExpressionBody; - AnalyzeBlock(context, body, analysis, style); + if (expressionBody?.ContainsDirectives == false) + { + BodyStyle style = context.GetBodyStyle(); + + if (style.IsDefault) + return; + + if (style.UseBlock) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenDeclarationIsMultiLine == true + && constructorDeclaration.SyntaxTree.IsMultiLineSpan(constructorDeclaration.HeaderSpan())) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenExpressionIsMultiLine == true + && expressionBody.Expression?.IsMultiLine() == true) + { + ReportDiagnostic(context, expressionBody); + } + } + } } - else + + private static void AnalyzeDestructorDeclaration(SyntaxNodeAnalysisContext context) { - ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; + var destructorDeclaration = (DestructorDeclarationSyntax)context.Node; - if (expressionBody?.ContainsDirectives == false) + BlockSyntax body = destructorDeclaration.Body; + if (body is not null) { + if (body.ContainsDirectives) + return; + BodyStyle style = context.GetBodyStyle(); if (style.IsDefault) return; - if (style.UseBlock) - { - ReportDiagnostic(context, expressionBody); + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body); + + if (!analysis.Success) + return; + + if (!style.UseExpression) return; - } if (style.UseBlockWhenDeclarationIsMultiLine == true - && localFunction.SyntaxTree.IsMultiLineSpan(localFunction.HeaderSpan())) + && destructorDeclaration.SyntaxTree.IsMultiLineSpan(destructorDeclaration.HeaderSpan())) { - ReportDiagnostic(context, expressionBody); return; } - if (style.UseBlockWhenExpressionIsMultiLine == true - && expressionBody.Expression?.IsMultiLine() == true) + AnalyzeBlock(context, body, analysis, style); + } + else + { + ArrowExpressionClauseSyntax expressionBody = destructorDeclaration.ExpressionBody; + + if (expressionBody?.ContainsDirectives == false) { - ReportDiagnostic(context, expressionBody); + BodyStyle style = context.GetBodyStyle(); + + if (style.IsDefault) + return; + + if (style.UseBlock) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenDeclarationIsMultiLine == true + && destructorDeclaration.SyntaxTree.IsMultiLineSpan(destructorDeclaration.HeaderSpan())) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenExpressionIsMultiLine == true + && expressionBody.Expression?.IsMultiLine() == true) + { + ReportDiagnostic(context, expressionBody); + } } } } - } - - private static void AnalyzeAccessorDeclaration(SyntaxNodeAnalysisContext context) - { - var accessor = (AccessorDeclarationSyntax)context.Node; - - BlockSyntax body = accessor.Body; - if (body != null) - { - AnalyzeAccessorDeclarationBlock(context, accessor, body); - } - else + private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) { - ArrowExpressionClauseSyntax expressionBody = accessor.ExpressionBody; + var localFunction = (LocalFunctionStatementSyntax)context.Node; - if (expressionBody?.ContainsDirectives == false) + BlockSyntax body = localFunction.Body; + if (body is not null) { + if (body.ContainsDirectives) + return; + BodyStyle style = context.GetBodyStyle(); if (style.IsDefault) return; - if (style.UseBlock) + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body); + + if (!analysis.Success) + return; + + if (!style.UseExpression) + return; + + if (style.UseBlockWhenDeclarationIsMultiLine == true + && localFunction.SyntaxTree.IsMultiLineSpan(localFunction.HeaderSpan())) { - ReportDiagnostic(context, expressionBody); return; } - if (style.UseBlockWhenExpressionIsMultiLine == true - && expressionBody.Expression?.IsMultiLine() == true) + AnalyzeBlock(context, body, analysis, style); + } + else + { + ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; + + if (expressionBody?.ContainsDirectives == false) { - ReportDiagnostic(context, expressionBody); + BodyStyle style = context.GetBodyStyle(); + + if (style.IsDefault) + return; + + if (style.UseBlock) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenDeclarationIsMultiLine == true + && localFunction.SyntaxTree.IsMultiLineSpan(localFunction.HeaderSpan())) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenExpressionIsMultiLine == true + && expressionBody.Expression?.IsMultiLine() == true) + { + ReportDiagnostic(context, expressionBody); + } } } } - } - private static void AnalyzeAccessorDeclarationBlock( - SyntaxNodeAnalysisContext context, - AccessorDeclarationSyntax accessor, - BlockSyntax body) - { - if (body.ContainsDirectives) - return; + private static void AnalyzeAccessorDeclaration(SyntaxNodeAnalysisContext context) + { + var accessor = (AccessorDeclarationSyntax)context.Node; - if (accessor.AttributeLists.Any()) - return; + BlockSyntax body = accessor.Body; - BodyStyle style = context.GetBodyStyle(); + if (body is not null) + { + AnalyzeAccessorDeclarationBlock(context, accessor, body); + } + else + { + ArrowExpressionClauseSyntax expressionBody = accessor.ExpressionBody; - if (style.IsDefault) - return; + if (expressionBody?.ContainsDirectives == false) + { + BodyStyle style = context.GetBodyStyle(); + + if (style.IsDefault) + return; + + if (style.UseBlock) + { + ReportDiagnostic(context, expressionBody); + return; + } + + if (style.UseBlockWhenExpressionIsMultiLine == true + && expressionBody.Expression?.IsMultiLine() == true) + { + ReportDiagnostic(context, expressionBody); + } + } + } + } - bool isGetter = accessor.IsKind(SyntaxKind.GetAccessorDeclaration); + private static void AnalyzeAccessorDeclarationBlock( + SyntaxNodeAnalysisContext context, + AccessorDeclarationSyntax accessor, + BlockSyntax body) + { + if (body.ContainsDirectives) + return; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body, allowExpressionStatement: !isGetter); + if (accessor.AttributeLists.Any()) + return; - ExpressionSyntax expression = analysis.Expression; + BodyStyle style = context.GetBodyStyle(); - if (expression == null) - return; + if (style.IsDefault) + return; - if (!style.UseExpression) - return; + bool isGetter = accessor.IsKind(SyntaxKind.GetAccessorDeclaration); - if (style.UseBlockWhenExpressionIsMultiLine == true - && expression.IsMultiLine()) - { - return; - } + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(body, allowExpressionStatement: !isGetter); - if (isGetter - && accessor.Parent is AccessorListSyntax accessorList - && accessorList.Accessors.Count == 1) - { - if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(accessorList.OpenBraceToken)) + ExpressionSyntax expression = analysis.Expression; + + if (expression is null) return; - if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(accessor.Keyword)) + if (!style.UseExpression) return; - if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(body.OpenBraceToken)) + if (style.UseBlockWhenExpressionIsMultiLine == true + && expression.IsMultiLine()) + { return; + } - if (style.UseBlockWhenDeclarationIsMultiLine == true) + if (isGetter + && accessor.Parent is AccessorListSyntax accessorList + && accessorList.Accessors.Count == 1) { - switch (accessorList.Parent.Kind()) + if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(accessorList.OpenBraceToken)) + return; + + if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(accessor.Keyword)) + return; + + if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(body.OpenBraceToken)) + return; + + if (style.UseBlockWhenDeclarationIsMultiLine == true) { - case SyntaxKind.PropertyDeclaration: - { - if (accessor.SyntaxTree.IsMultiLineSpan(((PropertyDeclarationSyntax)accessorList.Parent).HeaderSpan())) - return; - - break; - } - case SyntaxKind.IndexerDeclaration: - { - if (accessor.SyntaxTree.IsMultiLineSpan(((IndexerDeclarationSyntax)accessorList.Parent).HeaderSpan())) - return; - - break; - } - default: - { - SyntaxDebug.Fail(accessorList.Parent); - break; - } + switch (accessorList.Parent.Kind()) + { + case SyntaxKind.PropertyDeclaration: + { + if (accessor.SyntaxTree.IsMultiLineSpan(((PropertyDeclarationSyntax)accessorList.Parent).HeaderSpan())) + return; + + break; + } + case SyntaxKind.IndexerDeclaration: + { + if (accessor.SyntaxTree.IsMultiLineSpan(((IndexerDeclarationSyntax)accessorList.Parent).HeaderSpan())) + return; + + break; + } + default: + { + SyntaxDebug.Fail(accessorList.Parent); + break; + } + } + + return; } + ReportDiagnostic(context, accessorList); return; } - ReportDiagnostic(context, accessorList); - return; - } - - if (!accessor.Keyword.TrailingTrivia.IsEmptyOrWhitespace()) - return; + if (!accessor.Keyword.TrailingTrivia.IsEmptyOrWhitespace()) + return; - if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(body.OpenBraceToken)) - return; + if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(body.OpenBraceToken)) + return; - if (!accessor.Keyword.LeadingTrivia.IsEmptyOrWhitespace()) - return; + if (!accessor.Keyword.LeadingTrivia.IsEmptyOrWhitespace()) + return; - ReportDiagnostic(context, body); - } + ReportDiagnostic(context, body); + } - private static void AnalyzeBlock(SyntaxNodeAnalysisContext context, BlockSyntax block, BlockExpressionAnalysis analysis, BodyStyle style) - { - if (style.UseBlockWhenExpressionIsMultiLine == true - && analysis.Expression.IsMultiLine()) + private static void AnalyzeBlock(SyntaxNodeAnalysisContext context, BlockSyntax block, BlockExpressionAnalysis analysis, BodyStyle style) { - return; - } + if (style.UseBlockWhenExpressionIsMultiLine == true + && analysis.Expression.IsMultiLine()) + { + return; + } - if (!style.UseExpression) - return; + if (!style.UseExpression) + return; - if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(block.OpenBraceToken)) - return; + if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(block.OpenBraceToken)) + return; - if (!analysis.ReturnOrThrowKeyword.LeadingTrivia.IsEmptyOrWhitespace()) - return; + if (!analysis.ReturnOrThrowKeyword.LeadingTrivia.IsEmptyOrWhitespace()) + return; - ReportDiagnostic(context, analysis.Block); - } + ReportDiagnostic(context, analysis.Block); + } - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, AccessorListSyntax accessorList) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseBlockBodyOrExpressionBody, accessorList, "expression"); - } + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, AccessorListSyntax accessorList) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseBlockBodyOrExpressionBody, accessorList, "expression"); + } - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, BlockSyntax block) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseBlockBodyOrExpressionBody, block, "expression"); - } + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, BlockSyntax block) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseBlockBodyOrExpressionBody, block, "expression"); + } - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, ArrowExpressionClauseSyntax expressionBody) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseBlockBodyOrExpressionBody, expressionBody, "block"); + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, ArrowExpressionClauseSyntax expressionBody) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseBlockBodyOrExpressionBody, expressionBody, "block"); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseConditionalAccessAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseConditionalAccessAnalyzer.cs index acadf42f5d..297d46c847 100644 --- a/src/Analyzers/CSharp/Analysis/UseConditionalAccessAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseConditionalAccessAnalyzer.cs @@ -12,432 +12,433 @@ using Roslynator.CSharp; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseConditionalAccessAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseConditionalAccessAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseConditionalAccess); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseConditionalAccess); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) - return; + base.Initialize(context); - startContext.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeBinaryExpression(f), SyntaxKind.LogicalAndExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeBinaryExpression(f), SyntaxKind.LogicalOrExpression); - }); - } + context.RegisterCompilationStartAction(startContext => + { + if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) + return; - private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) - { - var ifStatement = (IfStatementSyntax)context.Node; + startContext.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement); + startContext.RegisterSyntaxNodeAction(f => AnalyzeBinaryExpression(f), SyntaxKind.LogicalAndExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeBinaryExpression(f), SyntaxKind.LogicalOrExpression); + }); + } - if (!ifStatement.IsSimpleIf()) - return; + private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) + { + var ifStatement = (IfStatementSyntax)context.Node; - if (ifStatement.ContainsDiagnostics) - return; + if (!ifStatement.IsSimpleIf()) + return; - if (ifStatement.SpanContainsDirectives()) - return; + if (ifStatement.ContainsDiagnostics) + return; - NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(ifStatement.Condition, allowedStyles: NullCheckStyles.NotEqualsToNull); + if (ifStatement.SpanContainsDirectives()) + return; - ExpressionSyntax expression = nullCheck.Expression; + NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(ifStatement.Condition, allowedStyles: NullCheckStyles.NotEqualsToNull); - if (expression == null) - return; + ExpressionSyntax expression = nullCheck.Expression; - SimpleMemberInvocationStatementInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationStatementInfo(ifStatement.SingleNonBlockStatementOrDefault()); + if (expression is null) + return; - ExpressionSyntax expression2 = invocationInfo.Expression; + SimpleMemberInvocationStatementInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationStatementInfo(ifStatement.SingleNonBlockStatementOrDefault()); - if (expression2 == null) - return; + ExpressionSyntax expression2 = invocationInfo.Expression; - ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(expression); + if (expression2 is null) + return; - if (typeSymbol == null) - return; + ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(expression); - if (typeSymbol.IsNullableType()) - { - if (!expression2.IsKind(SyntaxKind.SimpleMemberAccessExpression)) + if (typeSymbol is null) return; - var memberAccess = (MemberAccessExpressionSyntax)expression2; + if (typeSymbol.IsNullableType()) + { + if (!expression2.IsKind(SyntaxKind.SimpleMemberAccessExpression)) + return; - if (memberAccess.Name is not IdentifierNameSyntax identifierName) - return; + var memberAccess = (MemberAccessExpressionSyntax)expression2; - if (!string.Equals(identifierName.Identifier.ValueText, "Value", StringComparison.Ordinal)) - return; + if (memberAccess.Name is not IdentifierNameSyntax identifierName) + return; - expression2 = memberAccess.Expression; - } + if (!string.Equals(identifierName.Identifier.ValueText, "Value", StringComparison.Ordinal)) + return; - if (!CSharpFactory.AreEquivalent(expression, expression2)) - return; + expression2 = memberAccess.Expression; + } - if (ifStatement.IsInExpressionTree(context.SemanticModel, context.CancellationToken)) - return; + if (!CSharpFactory.AreEquivalent(expression, expression2)) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseConditionalAccess, ifStatement); - } + if (ifStatement.IsInExpressionTree(context.SemanticModel, context.CancellationToken)) + return; - private static void AnalyzeBinaryExpression(SyntaxNodeAnalysisContext context) - { - var binaryExpression = (BinaryExpressionSyntax)context.Node; + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseConditionalAccess, ifStatement); + } - if (binaryExpression.ContainsDiagnostics) - return; + private static void AnalyzeBinaryExpression(SyntaxNodeAnalysisContext context) + { + var binaryExpression = (BinaryExpressionSyntax)context.Node; - SyntaxKind kind = binaryExpression.Kind(); + if (binaryExpression.ContainsDiagnostics) + return; - if (binaryExpression.WalkUpParentheses().IsParentKind(kind)) - return; + SyntaxKind kind = binaryExpression.Kind(); - if (binaryExpression.IsInExpressionTree(context.SemanticModel, context.CancellationToken)) - return; + if (binaryExpression.WalkUpParentheses().IsParentKind(kind)) + return; - (ExpressionSyntax left, ExpressionSyntax right) = GetFixableExpressions(binaryExpression, kind, context.SemanticModel, context.CancellationToken); + if (binaryExpression.IsInExpressionTree(context.SemanticModel, context.CancellationToken)) + return; - if (left == null) - return; + (ExpressionSyntax left, ExpressionSyntax right) = GetFixableExpressions(binaryExpression, kind, context.SemanticModel, context.CancellationToken); - ISymbol operatorSymbol = context.SemanticModel.GetSymbol(binaryExpression, context.CancellationToken); + if (left is null) + return; - if (operatorSymbol?.Name == WellKnownMemberNames.BitwiseOrOperatorName) - { - INamedTypeSymbol containingType = operatorSymbol.ContainingType; + ISymbol operatorSymbol = context.SemanticModel.GetSymbol(binaryExpression, context.CancellationToken); - if (containingType.SpecialType != SpecialType.System_Boolean - && !ExistsImplicitConversionToBoolean(containingType)) + if (operatorSymbol?.Name == WellKnownMemberNames.BitwiseOrOperatorName) { - return; + INamedTypeSymbol containingType = operatorSymbol.ContainingType; + + if (containingType.SpecialType != SpecialType.System_Boolean + && !ExistsImplicitConversionToBoolean(containingType)) + { + return; + } } - } - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseConditionalAccess, - Location.Create(binaryExpression.SyntaxTree, TextSpan.FromBounds(left.SpanStart, right.Span.End))); + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseConditionalAccess, + Location.Create(binaryExpression.SyntaxTree, TextSpan.FromBounds(left.SpanStart, right.Span.End))); - static bool ExistsImplicitConversionToBoolean(INamedTypeSymbol typeSymbol) - { - foreach (ISymbol member in typeSymbol.GetMembers(WellKnownMemberNames.ImplicitConversionName)) + static bool ExistsImplicitConversionToBoolean(INamedTypeSymbol typeSymbol) { - if (member.Kind == SymbolKind.Method) + foreach (ISymbol member in typeSymbol.GetMembers(WellKnownMemberNames.ImplicitConversionName)) { - var methodSymbol = (IMethodSymbol)member; + if (member.Kind == SymbolKind.Method) + { + var methodSymbol = (IMethodSymbol)member; - if (methodSymbol.ReturnType.SpecialType == SpecialType.System_Boolean) - return true; + if (methodSymbol.ReturnType.SpecialType == SpecialType.System_Boolean) + return true; + } } - } - return false; + return false; + } } - } - private static bool IsFixable( - ExpressionSyntax left, - ExpressionSyntax right, - SyntaxKind binaryExpressionKind, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - NullCheckStyles allowedStyles = (binaryExpressionKind == SyntaxKind.LogicalAndExpression) - ? NullCheckStyles.NotEqualsToNull - : NullCheckStyles.EqualsToNull; + private static bool IsFixable( + ExpressionSyntax left, + ExpressionSyntax right, + SyntaxKind binaryExpressionKind, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + NullCheckStyles allowedStyles = (binaryExpressionKind == SyntaxKind.LogicalAndExpression) + ? NullCheckStyles.NotEqualsToNull + : NullCheckStyles.EqualsToNull; - NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(left, semanticModel, allowedStyles: allowedStyles, cancellationToken: cancellationToken); + NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(left, semanticModel, allowedStyles: allowedStyles, cancellationToken: cancellationToken); - ExpressionSyntax expression = nullCheck.Expression; + ExpressionSyntax expression = nullCheck.Expression; - if (expression == null) - return false; + if (expression is null) + return false; - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (typeSymbol == null) - return false; + if (typeSymbol is null) + return false; - if (!typeSymbol.IsReferenceTypeOrNullableType()) - return false; + if (!typeSymbol.IsReferenceTypeOrNullableType()) + return false; - if (right == null) - return false; + if (right is null) + return false; - if (!ValidateRightExpression(right, binaryExpressionKind, semanticModel, cancellationToken)) - return false; + if (!ValidateRightExpression(right, binaryExpressionKind, semanticModel, cancellationToken)) + return false; - if (CSharpUtility.ContainsOutArgumentWithLocalOrParameter(right, semanticModel, cancellationToken)) - return false; + if (CSharpUtility.ContainsOutArgumentWithLocalOrParameter(right, semanticModel, cancellationToken)) + return false; - ExpressionSyntax e = FindExpressionThatCanBeConditionallyAccessed(expression, right, isNullable: !typeSymbol.IsReferenceType, semanticModel, cancellationToken); + ExpressionSyntax e = FindExpressionThatCanBeConditionallyAccessed(expression, right, isNullable: !typeSymbol.IsReferenceType, semanticModel, cancellationToken); - return e != null; - } + return e is not null; + } - internal static ExpressionSyntax FindExpressionThatCanBeConditionallyAccessed( - ExpressionSyntax expressionToFind, - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - return FindExpressionThatCanBeConditionallyAccessed( - expressionToFind: expressionToFind, - expression: expression, - isNullable: false, - semanticModel: semanticModel, - cancellationToken: cancellationToken); - } + internal static ExpressionSyntax FindExpressionThatCanBeConditionallyAccessed( + ExpressionSyntax expressionToFind, + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + return FindExpressionThatCanBeConditionallyAccessed( + expressionToFind: expressionToFind, + expression: expression, + isNullable: false, + semanticModel: semanticModel, + cancellationToken: cancellationToken); + } - internal static ExpressionSyntax FindExpressionThatCanBeConditionallyAccessed( - ExpressionSyntax expressionToFind, - ExpressionSyntax expression, - bool isNullable, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (expression.IsKind(SyntaxKind.LogicalNotExpression)) - expression = ((PrefixUnaryExpressionSyntax)expression).Operand; + internal static ExpressionSyntax FindExpressionThatCanBeConditionallyAccessed( + ExpressionSyntax expressionToFind, + ExpressionSyntax expression, + bool isNullable, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (expression.IsKind(SyntaxKind.LogicalNotExpression)) + expression = ((PrefixUnaryExpressionSyntax)expression).Operand; - SyntaxKind kind = expressionToFind.Kind(); + SyntaxKind kind = expressionToFind.Kind(); - SyntaxToken firstToken = expression.GetFirstToken(); + SyntaxToken firstToken = expression.GetFirstToken(); - int start = firstToken.SpanStart; + int start = firstToken.SpanStart; - SyntaxNode node = firstToken.Parent; + SyntaxNode node = firstToken.Parent; - while (node?.SpanStart == start) - { - if (kind == node.Kind() - && node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression) - && semanticModel.GetTypeSymbol(node.Parent, cancellationToken)?.Kind != SymbolKind.PointerType - && CSharpFactory.AreEquivalent(expressionToFind, node)) + while (node?.SpanStart == start) { - if (!isNullable) - return (ExpressionSyntax)node; - - if (node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) - && (((MemberAccessExpressionSyntax)node.Parent).Name is IdentifierNameSyntax identifierName) - && string.Equals(identifierName.Identifier.ValueText, "Value", StringComparison.Ordinal) - && node.Parent.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression)) + if (kind == node.Kind() + && node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression) + && semanticModel.GetTypeSymbol(node.Parent, cancellationToken)?.Kind != SymbolKind.PointerType + && CSharpFactory.AreEquivalent(expressionToFind, node)) { - return (ExpressionSyntax)node.Parent; + if (!isNullable) + return (ExpressionSyntax)node; + + if (node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) + && (((MemberAccessExpressionSyntax)node.Parent).Name is IdentifierNameSyntax identifierName) + && string.Equals(identifierName.Identifier.ValueText, "Value", StringComparison.Ordinal) + && node.Parent.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression)) + { + return (ExpressionSyntax)node.Parent; + } + + return null; } - return null; + node = node.Parent; } - node = node.Parent; + return null; } - return null; - } - - private static bool ValidateRightExpression( - ExpressionSyntax expression, - SyntaxKind binaryExpressionKind, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - if (binaryExpressionKind == SyntaxKind.LogicalAndExpression) + private static bool ValidateRightExpression( + ExpressionSyntax expression, + SyntaxKind binaryExpressionKind, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - switch (expression.Kind()) + if (binaryExpressionKind == SyntaxKind.LogicalAndExpression) { - case SyntaxKind.LessThanExpression: - case SyntaxKind.GreaterThanExpression: - case SyntaxKind.LessThanOrEqualExpression: - case SyntaxKind.GreaterThanOrEqualExpression: - case SyntaxKind.EqualsExpression: - { - expression = ((BinaryExpressionSyntax)expression) - .Right? - .WalkDownParentheses(); + switch (expression.Kind()) + { + case SyntaxKind.LessThanExpression: + case SyntaxKind.GreaterThanExpression: + case SyntaxKind.LessThanOrEqualExpression: + case SyntaxKind.GreaterThanOrEqualExpression: + case SyntaxKind.EqualsExpression: + { + expression = ((BinaryExpressionSyntax)expression) + .Right? + .WalkDownParentheses(); - if (expression == 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 != null; - } - case SyntaxKind.NotEqualsExpression: - { - return ((BinaryExpressionSyntax)expression) - .Right? - .WalkDownParentheses() - .Kind() == SyntaxKind.NullLiteralExpression; - } - case SyntaxKind.IsPatternExpression: - { - var isPatternExpression = (IsPatternExpressionSyntax)expression; + return optional.HasValue + && optional.Value is not null; + } + case SyntaxKind.NotEqualsExpression: + { + return ((BinaryExpressionSyntax)expression) + .Right? + .WalkDownParentheses() + .Kind() == SyntaxKind.NullLiteralExpression; + } + case SyntaxKind.IsPatternExpression: + { + var isPatternExpression = (IsPatternExpressionSyntax)expression; - PatternSyntax pattern = isPatternExpression.Pattern; + PatternSyntax pattern = isPatternExpression.Pattern; - if (pattern is ConstantPatternSyntax constantPattern) + if (pattern is ConstantPatternSyntax constantPattern) + { + return !constantPattern.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression); + } + else if (pattern.IsKind(SyntaxKind.NotPattern)) + { + pattern = ((UnaryPatternSyntax)pattern).Pattern; + + // 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 !constantPattern.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression); + return true; } - else if (pattern.IsKind(SyntaxKind.NotPattern)) + default: { - pattern = ((UnaryPatternSyntax)pattern).Pattern; - - // x != null && x.P is not T; - if (pattern is ConstantPatternSyntax constantPattern2) - return constantPattern2.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression); + return false; } - - return true; - } - case SyntaxKind.SimpleMemberAccessExpression: - case SyntaxKind.InvocationExpression: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.LogicalNotExpression: - case SyntaxKind.IsExpression: - case SyntaxKind.AsExpression: - { - return true; - } - default: - { - return false; - } + } } - } - else if (binaryExpressionKind == SyntaxKind.LogicalOrExpression) - { - switch (expression.Kind()) + else if (binaryExpressionKind == SyntaxKind.LogicalOrExpression) { - case SyntaxKind.SimpleMemberAccessExpression: - case SyntaxKind.InvocationExpression: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.LogicalNotExpression: - return true; - default: - return false; + switch (expression.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.InvocationExpression: + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.LogicalNotExpression: + return true; + default: + return false; + } } - } - Debug.Fail(binaryExpressionKind.ToString()); + Debug.Fail(binaryExpressionKind.ToString()); - return false; - } - - internal static (ExpressionSyntax left, ExpressionSyntax right) GetFixableExpressions( - BinaryExpressionSyntax binaryExpression, - SyntaxKind kind, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ExpressionSyntax e = binaryExpression; - - ExpressionSyntax left; - ExpressionSyntax right = null; + return false; + } - while (true) + internal static (ExpressionSyntax left, ExpressionSyntax right) GetFixableExpressions( + BinaryExpressionSyntax binaryExpression, + SyntaxKind kind, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - ExpressionSyntax last = GetLastChild(e); - - if (last != null) - { - e = last; - } - else - { - while (e != binaryExpression - && IsFirstChild(e)) - { - e = (ExpressionSyntax)e.Parent; - } + ExpressionSyntax e = binaryExpression; - if (e == binaryExpression) - break; + ExpressionSyntax left; + ExpressionSyntax right = null; - e = GetPreviousSibling(e); - } - - if (!e.IsKind(kind, SyntaxKind.ParenthesizedExpression)) + while (true) { - if (right == null) + ExpressionSyntax last = GetLastChild(e); + + if (last is not null) { - right = e; + e = last; } else { - left = e; + while (e != binaryExpression + && IsFirstChild(e)) + { + e = (ExpressionSyntax)e.Parent; + } - if (!binaryExpression.ContainsDirectives(TextSpan.FromBounds(left.SpanStart, right.Span.End)) - && IsFixable(left, right, kind, semanticModel, cancellationToken)) + if (e == binaryExpression) + break; + + e = GetPreviousSibling(e); + } + + if (!e.IsKind(kind, SyntaxKind.ParenthesizedExpression)) + { + if (right is null) { - return (left, right); + right = e; } + else + { + left = e; - right = left; + if (!binaryExpression.ContainsDirectives(TextSpan.FromBounds(left.SpanStart, right.Span.End)) + && IsFixable(left, right, kind, semanticModel, cancellationToken)) + { + return (left, right); + } + + right = left; + } } } - } - return default; + return default; - ExpressionSyntax GetLastChild(SyntaxNode node) - { - SyntaxKind kind2 = node.Kind(); - - if (kind2 == kind) - return ((BinaryExpressionSyntax)node).Right; + ExpressionSyntax GetLastChild(SyntaxNode node) + { + SyntaxKind kind2 = node.Kind(); - if (kind2 == SyntaxKind.ParenthesizedExpression) - return ((ParenthesizedExpressionSyntax)node).Expression; + if (kind2 == kind) + return ((BinaryExpressionSyntax)node).Right; - return null; - } + if (kind2 == SyntaxKind.ParenthesizedExpression) + return ((ParenthesizedExpressionSyntax)node).Expression; - ExpressionSyntax GetPreviousSibling(SyntaxNode node) - { - SyntaxNode parent = node.Parent; + return null; + } - if (parent.IsKind(kind)) + ExpressionSyntax GetPreviousSibling(SyntaxNode node) { - var logicalAnd = (BinaryExpressionSyntax)parent; + SyntaxNode parent = node.Parent; - if (logicalAnd.Right == node) - return logicalAnd.Left; - } + if (parent.IsKind(kind)) + { + var logicalAnd = (BinaryExpressionSyntax)parent; - return null; - } + if (logicalAnd.Right == node) + return logicalAnd.Left; + } - bool IsFirstChild(SyntaxNode node) - { - SyntaxNode parent = node.Parent; + return null; + } + + bool IsFirstChild(SyntaxNode node) + { + SyntaxNode parent = node.Parent; - if (parent.IsKind(kind)) - return ((BinaryExpressionSyntax)parent).Left == node; + if (parent.IsKind(kind)) + return ((BinaryExpressionSyntax)parent).Left == node; - return true; + return true; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis.cs b/src/Analyzers/CSharp/Analysis/UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis.cs index d80c3ba1d1..5465343cc0 100644 --- a/src/Analyzers/CSharp/Analysis/UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis.cs @@ -10,45 +10,46 @@ using Microsoft.CodeAnalysis.Text; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis; - -internal static class UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis +namespace Roslynator.CSharp.Analysis { - public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) + internal static class UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis { - InvocationExpressionSyntax invocationExpression = invocationInfo.InvocationExpression; + public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) + { + InvocationExpressionSyntax invocationExpression = invocationInfo.InvocationExpression; - if (invocationExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) - return; + if (invocationExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) + return; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; + IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) - return; + if (methodSymbol is null) + return; - if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "Any")) - return; + if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "Any")) + return; - ExpressionSyntax expression = invocationInfo.Expression; + ExpressionSyntax expression = invocationInfo.Expression; - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (typeSymbol == null) - return; + if (typeSymbol is null) + return; - string propertyName = SymbolUtility.GetCountOrLengthPropertyName(typeSymbol, semanticModel, expression.SpanStart); + string propertyName = SymbolUtility.GetCountOrLengthPropertyName(typeSymbol, semanticModel, expression.SpanStart); - if (propertyName == null) - return; + if (propertyName is null) + return; - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseCountOrLengthPropertyInsteadOfAnyMethod, - Location.Create(context.Node.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationExpression.Span.End)), - ImmutableDictionary.CreateRange(new[] { new KeyValuePair("PropertyName", propertyName) }), - propertyName); + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseCountOrLengthPropertyInsteadOfAnyMethod, + Location.Create(context.Node.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationExpression.Span.End)), + ImmutableDictionary.CreateRange(new[] { new KeyValuePair("PropertyName", propertyName) }), + propertyName); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseEmptyStringLiteralOrStringEmptyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseEmptyStringLiteralOrStringEmptyAnalyzer.cs index 3d1266f7de..3d76a51f2b 100644 --- a/src/Analyzers/CSharp/Analysis/UseEmptyStringLiteralOrStringEmptyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseEmptyStringLiteralOrStringEmptyAnalyzer.cs @@ -7,114 +7,115 @@ using Microsoft.CodeAnalysis.Diagnostics; using Roslynator.CSharp.CodeStyle; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseEmptyStringLiteralOrStringEmptyAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseEmptyStringLiteralOrStringEmptyAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseEmptyStringLiteralOrStringEmpty); - } + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseEmptyStringLiteralOrStringEmpty); + } - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterSyntaxNodeAction( - c => - { - if (c.GetEmptyStringStyle() == EmptyStringStyle.Literal) - AnalyzeSimpleMemberAccessExpression(c); - }, - SyntaxKind.SimpleMemberAccessExpression); - context.RegisterSyntaxNodeAction( - c => - { - if (c.GetEmptyStringStyle() == EmptyStringStyle.Field) - AnalyzeStringLiteralExpression(c); - }, - SyntaxKind.StringLiteralExpression); - - context.RegisterSyntaxNodeAction( - c => - { - if (c.GetEmptyStringStyle() == EmptyStringStyle.Field) - AnalyzeInterpolatedStringExpression(c); - }, - SyntaxKind.InterpolatedStringExpression); - } + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); + + context.RegisterSyntaxNodeAction( + c => + { + if (c.GetEmptyStringStyle() == EmptyStringStyle.Literal) + AnalyzeSimpleMemberAccessExpression(c); + }, + SyntaxKind.SimpleMemberAccessExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (c.GetEmptyStringStyle() == EmptyStringStyle.Field) + AnalyzeStringLiteralExpression(c); + }, + SyntaxKind.StringLiteralExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (c.GetEmptyStringStyle() == EmptyStringStyle.Field) + AnalyzeInterpolatedStringExpression(c); + }, + SyntaxKind.InterpolatedStringExpression); + } - private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContext context) - { - var memberAccess = (MemberAccessExpressionSyntax)context.Node; + private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContext context) + { + var memberAccess = (MemberAccessExpressionSyntax)context.Node; - if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) - return; + if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) + return; - if (memberAccess.Expression == null) - return; + if (memberAccess.Expression is null) + return; - if (memberAccess.Name?.Identifier.ValueText != "Empty") - return; + if (memberAccess.Name?.Identifier.ValueText != "Empty") + return; - var fieldSymbol = context.SemanticModel.GetSymbol(memberAccess.Name, context.CancellationToken) as IFieldSymbol; + var fieldSymbol = context.SemanticModel.GetSymbol(memberAccess.Name, context.CancellationToken) as IFieldSymbol; - if (!SymbolUtility.IsPublicStaticReadOnly(fieldSymbol)) - return; + if (!SymbolUtility.IsPublicStaticReadOnly(fieldSymbol)) + return; - if (fieldSymbol.ContainingType?.SpecialType != SpecialType.System_String) - return; + if (fieldSymbol.ContainingType?.SpecialType != SpecialType.System_String) + return; - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseEmptyStringLiteralOrStringEmpty, - memberAccess, - "empty string literal"); - } + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseEmptyStringLiteralOrStringEmpty, + memberAccess, + "empty string literal"); + } - private static void AnalyzeStringLiteralExpression(SyntaxNodeAnalysisContext context) - { - var literalExpression = (LiteralExpressionSyntax)context.Node; + private static void AnalyzeStringLiteralExpression(SyntaxNodeAnalysisContext context) + { + var literalExpression = (LiteralExpressionSyntax)context.Node; - if (literalExpression.Token.ValueText.Length > 0) - return; + if (literalExpression.Token.ValueText.Length > 0) + return; - if (CSharpUtility.IsPartOfExpressionThatMustBeConstant(literalExpression)) - return; + if (CSharpUtility.IsPartOfExpressionThatMustBeConstant(literalExpression)) + return; - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseEmptyStringLiteralOrStringEmpty, - literalExpression, - "'string.Empty'"); - } + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseEmptyStringLiteralOrStringEmpty, + literalExpression, + "'string.Empty'"); + } - private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContext context) - { - var interpolatedString = (InterpolatedStringExpressionSyntax)context.Node; + private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContext context) + { + var interpolatedString = (InterpolatedStringExpressionSyntax)context.Node; - if (interpolatedString.Contents.Any()) - return; + if (interpolatedString.Contents.Any()) + return; - if (CSharpUtility.IsPartOfExpressionThatMustBeConstant(interpolatedString)) - return; + if (CSharpUtility.IsPartOfExpressionThatMustBeConstant(interpolatedString)) + return; - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseEmptyStringLiteralOrStringEmpty, - interpolatedString, - "'string.Empty'"); + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseEmptyStringLiteralOrStringEmpty, + interpolatedString, + "'string.Empty'"); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseEventArgsEmptyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseEventArgsEmptyAnalyzer.cs index 8f306028a6..df1611571b 100644 --- a/src/Analyzers/CSharp/Analysis/UseEventArgsEmptyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseEventArgsEmptyAnalyzer.cs @@ -7,49 +7,50 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseEventArgsEmptyAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseEventArgsEmptyAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseEventArgsEmpty); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseEventArgsEmpty); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - context.RegisterSyntaxNodeAction(f => AnalyzeObjectCreationExpression(f), SyntaxKind.ObjectCreationExpression); - } + context.RegisterSyntaxNodeAction(f => AnalyzeObjectCreationExpression(f), SyntaxKind.ObjectCreationExpression); + } - private static void AnalyzeObjectCreationExpression(SyntaxNodeAnalysisContext context) - { - if (context.Node.SpanContainsDirectives()) - return; + private static void AnalyzeObjectCreationExpression(SyntaxNodeAnalysisContext context) + { + if (context.Node.SpanContainsDirectives()) + return; - var objectCreation = (ObjectCreationExpressionSyntax)context.Node; + var objectCreation = (ObjectCreationExpressionSyntax)context.Node; - if (objectCreation.ArgumentList?.Arguments.Count != 0) - return; + if (objectCreation.ArgumentList?.Arguments.Count != 0) + return; - if (objectCreation.Initializer != null) - return; + if (objectCreation.Initializer is not null) + return; - ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(objectCreation, context.CancellationToken); + ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(objectCreation, context.CancellationToken); - if (typeSymbol?.HasMetadataName(MetadataNames.System_EventArgs) != true) - return; + if (typeSymbol?.HasMetadataName(MetadataNames.System_EventArgs) != true) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseEventArgsEmpty, objectCreation); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseEventArgsEmpty, objectCreation); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseExceptionFilterAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseExceptionFilterAnalyzer.cs index 874b483988..296cf85590 100644 --- a/src/Analyzers/CSharp/Analysis/UseExceptionFilterAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseExceptionFilterAnalyzer.cs @@ -11,192 +11,193 @@ using Microsoft.CodeAnalysis.Diagnostics; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseExceptionFilterAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseExceptionFilterAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseExceptionFilter); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseExceptionFilter); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) - return; + base.Initialize(context); - startContext.RegisterSyntaxNodeAction(f => AnalyzeCatchClause(f), SyntaxKind.CatchClause); - }); - } + context.RegisterCompilationStartAction(startContext => + { + if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) + return; - private static void AnalyzeCatchClause(SyntaxNodeAnalysisContext context) - { - var catchClause = (CatchClauseSyntax)context.Node; + startContext.RegisterSyntaxNodeAction(f => AnalyzeCatchClause(f), SyntaxKind.CatchClause); + }); + } - if (catchClause.Filter != null) - return; + private static void AnalyzeCatchClause(SyntaxNodeAnalysisContext context) + { + var catchClause = (CatchClauseSyntax)context.Node; - if (catchClause.Block.Statements.FirstOrDefault() is not IfStatementSyntax ifStatement) - return; + if (catchClause.Filter is not null) + return; - if (IsThrowStatementWithoutExpression(ifStatement.Statement.SingleNonBlockStatementOrDefault()) - ^ IsThrowStatementWithoutExpression(ifStatement.Else?.Statement.SingleNonBlockStatementOrDefault())) - { - bool canUseExceptionFilter; - UseExceptionFilterWalker walker = null; + if (catchClause.Block.Statements.FirstOrDefault() is not IfStatementSyntax ifStatement) + return; - try + if (IsThrowStatementWithoutExpression(ifStatement.Statement.SingleNonBlockStatementOrDefault()) + ^ IsThrowStatementWithoutExpression(ifStatement.Else?.Statement.SingleNonBlockStatementOrDefault())) { - walker = UseExceptionFilterWalker.GetInstance(); + bool canUseExceptionFilter; + UseExceptionFilterWalker walker = null; - walker.SemanticModel = context.SemanticModel; - walker.CancellationToken = context.CancellationToken; + try + { + walker = UseExceptionFilterWalker.GetInstance(); - walker.Visit(ifStatement.Condition); + walker.SemanticModel = context.SemanticModel; + walker.CancellationToken = context.CancellationToken; - canUseExceptionFilter = walker.CanUseExceptionFilter; - } - finally - { - if (walker != null) - UseExceptionFilterWalker.Free(walker); - } + walker.Visit(ifStatement.Condition); - if (!canUseExceptionFilter) - return; + canUseExceptionFilter = walker.CanUseExceptionFilter; + } + finally + { + if (walker is not null) + UseExceptionFilterWalker.Free(walker); + } - if (ifStatement.ContainsUnbalancedIfElseDirectives()) - return; + if (!canUseExceptionFilter) + return; + + if (ifStatement.ContainsUnbalancedIfElseDirectives()) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseExceptionFilter, ifStatement.IfKeyword); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseExceptionFilter, ifStatement.IfKeyword); + } } - } - private static bool IsThrowStatementWithoutExpression(StatementSyntax statement) - { - return (statement is ThrowStatementSyntax throwStatement) - && throwStatement.Expression == null; - } + private static bool IsThrowStatementWithoutExpression(StatementSyntax statement) + { + return (statement is ThrowStatementSyntax throwStatement) + && throwStatement.Expression is null; + } - private class UseExceptionFilterWalker : CSharpSyntaxNodeWalker - { - [ThreadStatic] - private static UseExceptionFilterWalker _cachedInstance; + private class UseExceptionFilterWalker : CSharpSyntaxNodeWalker + { + [ThreadStatic] + private static UseExceptionFilterWalker _cachedInstance; - private static readonly Regex _exceptionElementRegex = new(@"\<(?i:exception)\ +cref=(?:""|')"); + private static readonly Regex _exceptionElementRegex = new(@"\<(?i:exception)\ +cref=(?:""|')"); - public bool CanUseExceptionFilter { get; set; } = true; + public bool CanUseExceptionFilter { get; set; } = true; - public SemanticModel SemanticModel { get; set; } + public SemanticModel SemanticModel { get; set; } - public CancellationToken CancellationToken { get; set; } + public CancellationToken CancellationToken { get; set; } - protected override bool ShouldVisit => CanUseExceptionFilter; + protected override bool ShouldVisit => CanUseExceptionFilter; - public override void VisitInvocationExpression(InvocationExpressionSyntax node) - { - switch (node.Expression) + public override void VisitInvocationExpression(InvocationExpressionSyntax node) { - case SimpleNameSyntax simpleName: - { - AnalyzeSimpleName(simpleName); - break; - } - case MemberBindingExpressionSyntax memberBindingExpression: - { - AnalyzeSimpleName(memberBindingExpression.Name); - break; - } - case MemberAccessExpressionSyntax memberAccessExpression: - { - AnalyzeSimpleName(memberAccessExpression.Name); - break; - } - default: - { - SyntaxDebug.Fail(node); - break; - } + switch (node.Expression) + { + case SimpleNameSyntax simpleName: + { + AnalyzeSimpleName(simpleName); + break; + } + case MemberBindingExpressionSyntax memberBindingExpression: + { + AnalyzeSimpleName(memberBindingExpression.Name); + break; + } + case MemberAccessExpressionSyntax memberAccessExpression: + { + AnalyzeSimpleName(memberAccessExpression.Name); + break; + } + default: + { + SyntaxDebug.Fail(node); + break; + } + } + + base.VisitInvocationExpression(node); } - base.VisitInvocationExpression(node); - } + private void AnalyzeSimpleName(SimpleNameSyntax simpleName) + { + if (simpleName.Identifier.ValueText.StartsWith("ThrowIf", StringComparison.Ordinal)) + CanUseExceptionFilter = false; - private void AnalyzeSimpleName(SimpleNameSyntax simpleName) - { - if (simpleName.Identifier.ValueText.StartsWith("ThrowIf", StringComparison.Ordinal)) - CanUseExceptionFilter = false; + ISymbol symbol = SemanticModel.GetSymbol(simpleName, CancellationToken); - ISymbol symbol = SemanticModel.GetSymbol(simpleName, CancellationToken); + string xml = symbol?.GetDocumentationCommentXml(cancellationToken: CancellationToken); - string xml = symbol?.GetDocumentationCommentXml(cancellationToken: CancellationToken); + if (xml is not null + && _exceptionElementRegex.IsMatch(xml)) + { + CanUseExceptionFilter = false; + } + } - if (xml != null - && _exceptionElementRegex.IsMatch(xml)) + public override void VisitAwaitExpression(AwaitExpressionSyntax node) { CanUseExceptionFilter = false; } - } - public override void VisitAwaitExpression(AwaitExpressionSyntax node) - { - CanUseExceptionFilter = false; - } + public override void VisitThrowExpression(ThrowExpressionSyntax node) + { + CanUseExceptionFilter = false; + } - public override void VisitThrowExpression(ThrowExpressionSyntax node) - { - CanUseExceptionFilter = false; - } + public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + } - public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) - { - } + public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + } - public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) - { - } + public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + } - public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) - { - } + public static UseExceptionFilterWalker GetInstance() + { + UseExceptionFilterWalker walker = _cachedInstance; - public static UseExceptionFilterWalker GetInstance() - { - UseExceptionFilterWalker walker = _cachedInstance; + if (walker is not null) + { + Debug.Assert(walker.CanUseExceptionFilter = true); + Debug.Assert(walker.SemanticModel is null); + Debug.Assert(walker.CancellationToken == default); - if (walker != null) - { - Debug.Assert(walker.CanUseExceptionFilter = true); - Debug.Assert(walker.SemanticModel == null); - Debug.Assert(walker.CancellationToken == default); + _cachedInstance = null; + return walker; + } - _cachedInstance = null; - return walker; + return new UseExceptionFilterWalker(); } - return new UseExceptionFilterWalker(); - } - - public static void Free(UseExceptionFilterWalker walker) - { - walker.CanUseExceptionFilter = true; - walker.SemanticModel = null; - walker.CancellationToken = default; + public static void Free(UseExceptionFilterWalker walker) + { + walker.CanUseExceptionFilter = true; + walker.SemanticModel = null; + walker.CancellationToken = default; - _cachedInstance = walker; + _cachedInstance = walker; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseExclusiveOrOperatorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseExclusiveOrOperatorAnalyzer.cs index 3135c7a31f..0fc7a1e79c 100644 --- a/src/Analyzers/CSharp/Analysis/UseExclusiveOrOperatorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseExclusiveOrOperatorAnalyzer.cs @@ -10,120 +10,121 @@ using Roslynator.CSharp.Syntax; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseExclusiveOrOperatorAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseExclusiveOrOperatorAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseExclusiveOrOperator); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseExclusiveOrOperator); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterSyntaxNodeAction(f => AnalyzeLogicalOrExpression(f), SyntaxKind.LogicalOrExpression); - } + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - private static void AnalyzeLogicalOrExpression(SyntaxNodeAnalysisContext context) - { - SyntaxNode node = context.Node; + context.RegisterSyntaxNodeAction(f => AnalyzeLogicalOrExpression(f), SyntaxKind.LogicalOrExpression); + } - if (node.ContainsDiagnostics) - return; + private static void AnalyzeLogicalOrExpression(SyntaxNodeAnalysisContext context) + { + SyntaxNode node = context.Node; - if (node.SpanContainsDirectives()) - return; + if (node.ContainsDiagnostics) + return; - BinaryExpressionInfo info = SyntaxInfo.BinaryExpressionInfo((BinaryExpressionSyntax)context.Node); + if (node.SpanContainsDirectives()) + return; - if (!info.Success) - return; + BinaryExpressionInfo info = SyntaxInfo.BinaryExpressionInfo((BinaryExpressionSyntax)context.Node); - if (!info.Left.IsKind(SyntaxKind.LogicalAndExpression)) - return; + if (!info.Success) + return; - if (!info.Right.IsKind(SyntaxKind.LogicalAndExpression)) - return; + if (!info.Left.IsKind(SyntaxKind.LogicalAndExpression)) + return; - ExpressionPair expressions = GetExpressionPair((BinaryExpressionSyntax)info.Left); + if (!info.Right.IsKind(SyntaxKind.LogicalAndExpression)) + return; - if (!expressions.IsValid) - return; + ExpressionPair expressions = GetExpressionPair((BinaryExpressionSyntax)info.Left); - ExpressionPair expressions2 = GetExpressionPair((BinaryExpressionSyntax)info.Right); + if (!expressions.IsValid) + return; - if (!expressions2.IsValid) - return; + ExpressionPair expressions2 = GetExpressionPair((BinaryExpressionSyntax)info.Right); - if (expressions.Expression.Kind() != expressions2.InvertedExpression.Kind()) - return; + if (!expressions2.IsValid) + return; - if (expressions.InvertedExpression.Kind() != expressions2.Expression.Kind()) - return; + if (expressions.Expression.Kind() != expressions2.InvertedExpression.Kind()) + return; - if (!AreEquivalent(expressions.Expression, expressions2.InvertedExpression)) - return; + if (expressions.InvertedExpression.Kind() != expressions2.Expression.Kind()) + return; - if (!AreEquivalent(expressions.InvertedExpression, expressions2.Expression)) - return; + if (!AreEquivalent(expressions.Expression, expressions2.InvertedExpression)) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseExclusiveOrOperator, context.Node); - } + if (!AreEquivalent(expressions.InvertedExpression, expressions2.Expression)) + return; - private static ExpressionPair GetExpressionPair(BinaryExpressionSyntax logicalAnd) - { - BinaryExpressionInfo info = SyntaxInfo.BinaryExpressionInfo(logicalAnd); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseExclusiveOrOperator, context.Node); + } - if (info.Success) + private static ExpressionPair GetExpressionPair(BinaryExpressionSyntax logicalAnd) { - ExpressionSyntax left = info.Left; - ExpressionSyntax right = info.Right; + BinaryExpressionInfo info = SyntaxInfo.BinaryExpressionInfo(logicalAnd); - if (left.Kind() == SyntaxKind.LogicalNotExpression) + if (info.Success) { - if (right.Kind() != SyntaxKind.LogicalNotExpression) + ExpressionSyntax left = info.Left; + ExpressionSyntax right = info.Right; + + if (left.Kind() == SyntaxKind.LogicalNotExpression) { - var logicalNot = (PrefixUnaryExpressionSyntax)left; + if (right.Kind() != SyntaxKind.LogicalNotExpression) + { + var logicalNot = (PrefixUnaryExpressionSyntax)left; - return new ExpressionPair(right, logicalNot.Operand.WalkDownParentheses()); + return new ExpressionPair(right, logicalNot.Operand.WalkDownParentheses()); + } } - } - else if (right.Kind() == SyntaxKind.LogicalNotExpression) - { - var logicalNot = (PrefixUnaryExpressionSyntax)right; + else if (right.Kind() == SyntaxKind.LogicalNotExpression) + { + var logicalNot = (PrefixUnaryExpressionSyntax)right; - return new ExpressionPair(left, logicalNot.Operand.WalkDownParentheses()); + return new ExpressionPair(left, logicalNot.Operand.WalkDownParentheses()); + } } - } - - return default; - } - private readonly struct ExpressionPair - { - public ExpressionPair(ExpressionSyntax expression, ExpressionSyntax invertedExpression) - { - Expression = expression; - InvertedExpression = invertedExpression; + return default; } - public bool IsValid + private readonly struct ExpressionPair { - get { return Expression != null && InvertedExpression != null; } - } + public ExpressionPair(ExpressionSyntax expression, ExpressionSyntax invertedExpression) + { + Expression = expression; + InvertedExpression = invertedExpression; + } - public ExpressionSyntax Expression { get; } - public ExpressionSyntax InvertedExpression { get; } + public bool IsValid + { + get { return Expression is not null && InvertedExpression is not null; } + } + + public ExpressionSyntax Expression { get; } + public ExpressionSyntax InvertedExpression { get; } + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseExplicitlyOrImplicitlyTypedArrayAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseExplicitlyOrImplicitlyTypedArrayAnalyzer.cs index bd75ddd763..eb1409a8ef 100644 --- a/src/Analyzers/CSharp/Analysis/UseExplicitlyOrImplicitlyTypedArrayAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseExplicitlyOrImplicitlyTypedArrayAnalyzer.cs @@ -8,170 +8,171 @@ using Microsoft.CodeAnalysis.Text; using Roslynator.CSharp.CodeStyle; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseExplicitlyOrImplicitlyTypedArrayAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseExplicitlyOrImplicitlyTypedArrayAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseExplicitlyOrImplicitlyTypedArray); - } + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseExplicitlyOrImplicitlyTypedArray); + } - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterSyntaxNodeAction( - c => - { - ArrayCreationTypeStyle style = c.GetArrayCreationTypeStyle(); + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - if (style == ArrayCreationTypeStyle.Explicit - || style == ArrayCreationTypeStyle.ImplicitWhenTypeIsObvious) + context.RegisterSyntaxNodeAction( + c => { - AnalyzeImplicitArrayCreationExpression(c, style); - } - }, - SyntaxKind.ImplicitArrayCreationExpression); + ArrayCreationTypeStyle style = c.GetArrayCreationTypeStyle(); - context.RegisterSyntaxNodeAction( - c => - { - ArrayCreationTypeStyle style = c.GetArrayCreationTypeStyle(); + if (style == ArrayCreationTypeStyle.Explicit + || style == ArrayCreationTypeStyle.ImplicitWhenTypeIsObvious) + { + AnalyzeImplicitArrayCreationExpression(c, style); + } + }, + SyntaxKind.ImplicitArrayCreationExpression); - if (style == ArrayCreationTypeStyle.Implicit - || style == ArrayCreationTypeStyle.ImplicitWhenTypeIsObvious) + context.RegisterSyntaxNodeAction( + c => { - AnalyzeArrayCreationExpression(c, style); - } - }, - SyntaxKind.ArrayCreationExpression); - } + ArrayCreationTypeStyle style = c.GetArrayCreationTypeStyle(); - private static void AnalyzeImplicitArrayCreationExpression(SyntaxNodeAnalysisContext context, ArrayCreationTypeStyle kind) - { - var expression = (ImplicitArrayCreationExpressionSyntax)context.Node; + if (style == ArrayCreationTypeStyle.Implicit + || style == ArrayCreationTypeStyle.ImplicitWhenTypeIsObvious) + { + AnalyzeArrayCreationExpression(c, style); + } + }, + SyntaxKind.ArrayCreationExpression); + } - if (expression.ContainsDiagnostics) - return; + private static void AnalyzeImplicitArrayCreationExpression(SyntaxNodeAnalysisContext context, ArrayCreationTypeStyle kind) + { + var expression = (ImplicitArrayCreationExpressionSyntax)context.Node; - if (expression.NewKeyword.ContainsDirectives) - return; + if (expression.ContainsDiagnostics) + return; - if (expression.OpenBracketToken.ContainsDirectives) - return; + if (expression.NewKeyword.ContainsDirectives) + return; - if (expression.CloseBracketToken.ContainsDirectives) - return; + if (expression.OpenBracketToken.ContainsDirectives) + return; - IArrayTypeSymbol arrayTypeSymbol = null; + if (expression.CloseBracketToken.ContainsDirectives) + return; - if (kind == ArrayCreationTypeStyle.ImplicitWhenTypeIsObvious) - { - InitializerExpressionSyntax initializer = expression.Initializer; + IArrayTypeSymbol arrayTypeSymbol = null; - if (initializer != null) + if (kind == ArrayCreationTypeStyle.ImplicitWhenTypeIsObvious) { - var isObvious = false; + InitializerExpressionSyntax initializer = expression.Initializer; - foreach (ExpressionSyntax expression2 in initializer.Expressions) + if (initializer is not null) { - if (arrayTypeSymbol == null) + var isObvious = false; + + foreach (ExpressionSyntax expression2 in initializer.Expressions) { - arrayTypeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken) as IArrayTypeSymbol; + if (arrayTypeSymbol is null) + { + arrayTypeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken) as IArrayTypeSymbol; - if (arrayTypeSymbol?.ElementType.SupportsExplicitDeclaration() != true) - return; - } + if (arrayTypeSymbol?.ElementType.SupportsExplicitDeclaration() != true) + return; + } - isObvious = CSharpTypeAnalysis.IsTypeObvious(expression2, arrayTypeSymbol.ElementType, includeNullability: true, context.SemanticModel, context.CancellationToken); + isObvious = CSharpTypeAnalysis.IsTypeObvious(expression2, arrayTypeSymbol.ElementType, includeNullability: true, context.SemanticModel, context.CancellationToken); + + if (!isObvious) + break; + } - if (!isObvious) - break; + if (isObvious) + return; } + } + + if (arrayTypeSymbol is null) + { + arrayTypeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken) as IArrayTypeSymbol; - if (isObvious) + if (arrayTypeSymbol?.ElementType.SupportsExplicitDeclaration() != true) return; } - } - if (arrayTypeSymbol == null) - { - arrayTypeSymbol = context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken) as IArrayTypeSymbol; + Location location = Location.Create(expression.SyntaxTree, TextSpan.FromBounds(expression.NewKeyword.SpanStart, expression.CloseBracketToken.Span.End)); - if (arrayTypeSymbol?.ElementType.SupportsExplicitDeclaration() != true) - return; + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseExplicitlyOrImplicitlyTypedArray, + location, + "explicitly"); } - Location location = Location.Create(expression.SyntaxTree, TextSpan.FromBounds(expression.NewKeyword.SpanStart, expression.CloseBracketToken.Span.End)); - - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseExplicitlyOrImplicitlyTypedArray, - location, - "explicitly"); - } - - private static void AnalyzeArrayCreationExpression(SyntaxNodeAnalysisContext context, ArrayCreationTypeStyle kind) - { - var arrayCreation = (ArrayCreationExpressionSyntax)context.Node; + private static void AnalyzeArrayCreationExpression(SyntaxNodeAnalysisContext context, ArrayCreationTypeStyle kind) + { + var arrayCreation = (ArrayCreationExpressionSyntax)context.Node; - if (arrayCreation.ContainsDiagnostics) - return; + if (arrayCreation.ContainsDiagnostics) + return; - ArrayTypeSyntax arrayType = arrayCreation.Type; + ArrayTypeSyntax arrayType = arrayCreation.Type; - if (arrayType.ContainsDirectives) - return; + if (arrayType.ContainsDirectives) + return; - SeparatedSyntaxList expressions = arrayCreation.Initializer?.Expressions ?? default; + SeparatedSyntaxList expressions = arrayCreation.Initializer?.Expressions ?? default; - if (!expressions.Any()) - return; + if (!expressions.Any()) + return; - ITypeSymbol typeSymbol = null; + ITypeSymbol typeSymbol = null; - if (kind == ArrayCreationTypeStyle.ImplicitWhenTypeIsObvious) - { - foreach (ExpressionSyntax expression in expressions) + if (kind == ArrayCreationTypeStyle.ImplicitWhenTypeIsObvious) { - if (typeSymbol == null) + foreach (ExpressionSyntax expression in expressions) { - typeSymbol = context.SemanticModel.GetTypeSymbol(arrayCreation.Type.ElementType, context.CancellationToken); + if (typeSymbol is null) + { + typeSymbol = context.SemanticModel.GetTypeSymbol(arrayCreation.Type.ElementType, context.CancellationToken); - if (typeSymbol?.IsErrorType() != false) + if (typeSymbol?.IsErrorType() != false) + return; + } + + if (!CSharpTypeAnalysis.IsTypeObvious(expression, typeSymbol, includeNullability: true, context.SemanticModel, context.CancellationToken)) return; } - - if (!CSharpTypeAnalysis.IsTypeObvious(expression, typeSymbol, includeNullability: true, context.SemanticModel, context.CancellationToken)) - return; } - } - TypeSyntax elementType = arrayType.ElementType; - SyntaxList rankSpecifiers = arrayType.RankSpecifiers; + TypeSyntax elementType = arrayType.ElementType; + SyntaxList rankSpecifiers = arrayType.RankSpecifiers; - TextSpan textSpan = TextSpan.FromBounds( - elementType.SpanStart, - ((rankSpecifiers.Count > 1) ? rankSpecifiers.LastButOne() : (SyntaxNode)elementType).Span.End); + TextSpan textSpan = TextSpan.FromBounds( + elementType.SpanStart, + ((rankSpecifiers.Count > 1) ? rankSpecifiers.LastButOne() : (SyntaxNode)elementType).Span.End); - Location location = Location.Create(arrayCreation.SyntaxTree, textSpan); + Location location = Location.Create(arrayCreation.SyntaxTree, textSpan); - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseExplicitlyOrImplicitlyTypedArray, - location, - "implicitly"); + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseExplicitlyOrImplicitlyTypedArray, + location, + "implicitly"); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseForStatementInsteadOfWhileStatementAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseForStatementInsteadOfWhileStatementAnalyzer.cs index f19f8c8df8..0cfeaa95a7 100644 --- a/src/Analyzers/CSharp/Analysis/UseForStatementInsteadOfWhileStatementAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseForStatementInsteadOfWhileStatementAnalyzer.cs @@ -10,226 +10,227 @@ using Roslynator.CSharp.Syntax; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseForStatementInsteadOfWhileStatementAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseForStatementInsteadOfWhileStatementAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseForStatementInsteadOfWhileStatement); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseForStatementInsteadOfWhileStatement); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterSyntaxNodeAction(f => AnalyzeWhileStatement(f), SyntaxKind.WhileStatement); - } + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - private static void AnalyzeWhileStatement(SyntaxNodeAnalysisContext context) - { - var whileStatement = (WhileStatementSyntax)context.Node; + context.RegisterSyntaxNodeAction(f => AnalyzeWhileStatement(f), SyntaxKind.WhileStatement); + } - ExpressionSyntax condition = whileStatement.Condition; + private static void AnalyzeWhileStatement(SyntaxNodeAnalysisContext context) + { + var whileStatement = (WhileStatementSyntax)context.Node; - if (condition.IsMissing) - return; + ExpressionSyntax condition = whileStatement.Condition; - if (condition.WalkDownParentheses().IsKind(SyntaxKind.TrueLiteralExpression)) - return; + if (condition.IsMissing) + return; - if (!condition.IsSingleLine()) - return; + if (condition.WalkDownParentheses().IsKind(SyntaxKind.TrueLiteralExpression)) + return; - StatementSyntax statement = whileStatement.Statement; + if (!condition.IsSingleLine()) + return; - if (statement is not BlockSyntax block) - return; + StatementSyntax statement = whileStatement.Statement; - SyntaxList innerStatements = block.Statements; + if (statement is not BlockSyntax block) + return; - if (innerStatements.Count <= 1) - return; + SyntaxList innerStatements = block.Statements; - ExpressionSyntax incrementedExpression = GetIncrementedExpression(innerStatements.Last()); + if (innerStatements.Count <= 1) + return; - if (!incrementedExpression.IsKind(SyntaxKind.IdentifierName)) - return; + ExpressionSyntax incrementedExpression = GetIncrementedExpression(innerStatements.Last()); - SyntaxList outerStatements = SyntaxInfo.StatementListInfo(whileStatement).Statements; + if (!incrementedExpression.IsKind(SyntaxKind.IdentifierName)) + return; - int index = outerStatements.IndexOf(whileStatement); + SyntaxList outerStatements = SyntaxInfo.StatementListInfo(whileStatement).Statements; - if (index <= 0) - return; + int index = outerStatements.IndexOf(whileStatement); - SingleLocalDeclarationStatementInfo localInfo = GetLocalInfo(outerStatements[index - 1]); + if (index <= 0) + return; - if (!localInfo.Success) - return; + SingleLocalDeclarationStatementInfo localInfo = GetLocalInfo(outerStatements[index - 1]); - if (index > 1) - { - SingleLocalDeclarationStatementInfo localInfo2 = GetLocalInfo(outerStatements[index - 2]); + if (!localInfo.Success) + return; - if (localInfo2.Success) + if (index > 1) { - ExpressionSyntax incrementedExpression2 = GetIncrementedExpression(innerStatements[innerStatements.Count - 2]); + SingleLocalDeclarationStatementInfo localInfo2 = GetLocalInfo(outerStatements[index - 2]); - if (incrementedExpression2 is IdentifierNameSyntax identifierName2 - && string.Equals(localInfo2.Identifier.ValueText, identifierName2.Identifier.ValueText, StringComparison.Ordinal)) + if (localInfo2.Success) { - return; + ExpressionSyntax incrementedExpression2 = GetIncrementedExpression(innerStatements[innerStatements.Count - 2]); + + if (incrementedExpression2 is IdentifierNameSyntax identifierName2 + && string.Equals(localInfo2.Identifier.ValueText, identifierName2.Identifier.ValueText, StringComparison.Ordinal)) + { + return; + } } } - } - - var identifierName = (IdentifierNameSyntax)incrementedExpression; - if (!string.Equals(localInfo.Identifier.ValueText, identifierName.Identifier.ValueText, StringComparison.Ordinal)) - return; + var identifierName = (IdentifierNameSyntax)incrementedExpression; - if (ContainsContinueStatement()) - return; + if (!string.Equals(localInfo.Identifier.ValueText, identifierName.Identifier.ValueText, StringComparison.Ordinal)) + return; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + if (ContainsContinueStatement()) + return; - ISymbol symbol = semanticModel.GetDeclaredSymbol(localInfo.Declarator, cancellationToken); + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (symbol?.Kind != SymbolKind.Local) - return; + ISymbol symbol = semanticModel.GetDeclaredSymbol(localInfo.Declarator, cancellationToken); - if (IsLocalVariableReferencedAfterWhileStatement()) - return; + if (symbol?.Kind != SymbolKind.Local) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseForStatementInsteadOfWhileStatement, whileStatement.WhileKeyword); + if (IsLocalVariableReferencedAfterWhileStatement()) + return; - bool ContainsContinueStatement() - { - ContainsContinueStatementWalker walker = ContainsContinueStatementWalker.GetInstance(); - walker.ContainsContinueStatement = false; + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseForStatementInsteadOfWhileStatement, whileStatement.WhileKeyword); - var containsContinueStatement = false; - - foreach (StatementSyntax innerStatement in innerStatements) + bool ContainsContinueStatement() { - walker.Visit(innerStatement); + ContainsContinueStatementWalker walker = ContainsContinueStatementWalker.GetInstance(); + walker.ContainsContinueStatement = false; + + var containsContinueStatement = false; - if (walker.ContainsContinueStatement) + foreach (StatementSyntax innerStatement in innerStatements) { - containsContinueStatement = true; - break; + walker.Visit(innerStatement); + + if (walker.ContainsContinueStatement) + { + containsContinueStatement = true; + break; + } } - } - ContainsContinueStatementWalker.Free(walker); + ContainsContinueStatementWalker.Free(walker); - return containsContinueStatement; - } + return containsContinueStatement; + } - bool IsLocalVariableReferencedAfterWhileStatement() - { - ContainsLocalOrParameterReferenceWalker walker = null; - try + bool IsLocalVariableReferencedAfterWhileStatement() { - walker = ContainsLocalOrParameterReferenceWalker.GetInstance(symbol, semanticModel, cancellationToken); + ContainsLocalOrParameterReferenceWalker walker = null; + try + { + walker = ContainsLocalOrParameterReferenceWalker.GetInstance(symbol, semanticModel, cancellationToken); - walker.VisitList(outerStatements, index + 1); + walker.VisitList(outerStatements, index + 1); - return walker.Result; - } - finally - { - if (walker != null) - ContainsLocalOrParameterReferenceWalker.Free(walker); + return walker.Result; + } + finally + { + if (walker is not null) + ContainsLocalOrParameterReferenceWalker.Free(walker); + } } } - } - private static ExpressionSyntax GetIncrementedExpression(StatementSyntax statement) - { - if (statement is ExpressionStatementSyntax expressionStatement) + private static ExpressionSyntax GetIncrementedExpression(StatementSyntax statement) { - ExpressionSyntax expression = expressionStatement.Expression; - - if (expression.IsKind(SyntaxKind.PostIncrementExpression)) + if (statement is ExpressionStatementSyntax expressionStatement) { - var postIncrementExpression = (PostfixUnaryExpressionSyntax)expression; - - return postIncrementExpression.Operand; - } - } + ExpressionSyntax expression = expressionStatement.Expression; - return null; - } - - private static SingleLocalDeclarationStatementInfo GetLocalInfo(StatementSyntax statement) - { - return (statement.IsKind(SyntaxKind.LocalDeclarationStatement)) - ? SyntaxInfo.SingleLocalDeclarationStatementInfo((LocalDeclarationStatementSyntax)statement) - : default; - } - - private class ContainsContinueStatementWalker : CSharpSyntaxNodeWalker - { - [ThreadStatic] - private static ContainsContinueStatementWalker _cachedInstance; - - public bool ContainsContinueStatement { get; set; } + if (expression.IsKind(SyntaxKind.PostIncrementExpression)) + { + var postIncrementExpression = (PostfixUnaryExpressionSyntax)expression; - protected override bool ShouldVisit => !ContainsContinueStatement; + return postIncrementExpression.Operand; + } + } - public override void VisitContinueStatement(ContinueStatementSyntax node) - { - ContainsContinueStatement = true; + return null; } - public override void VisitDoStatement(DoStatementSyntax node) + private static SingleLocalDeclarationStatementInfo GetLocalInfo(StatementSyntax statement) { + return (statement.IsKind(SyntaxKind.LocalDeclarationStatement)) + ? SyntaxInfo.SingleLocalDeclarationStatementInfo((LocalDeclarationStatementSyntax)statement) + : default; } - public override void VisitForStatement(ForStatementSyntax node) + private class ContainsContinueStatementWalker : CSharpSyntaxNodeWalker { - } + [ThreadStatic] + private static ContainsContinueStatementWalker _cachedInstance; - public override void VisitForEachStatement(ForEachStatementSyntax node) - { - } + public bool ContainsContinueStatement { get; set; } - public override void VisitForEachVariableStatement(ForEachVariableStatementSyntax node) - { - } + protected override bool ShouldVisit => !ContainsContinueStatement; - public override void VisitWhileStatement(WhileStatementSyntax node) - { - } + public override void VisitContinueStatement(ContinueStatementSyntax node) + { + ContainsContinueStatement = true; + } - public static ContainsContinueStatementWalker GetInstance() - { - ContainsContinueStatementWalker walker = _cachedInstance; + public override void VisitDoStatement(DoStatementSyntax node) + { + } - if (walker != null) + public override void VisitForStatement(ForStatementSyntax node) { - _cachedInstance = null; - return walker; } - return new ContainsContinueStatementWalker(); - } + public override void VisitForEachStatement(ForEachStatementSyntax node) + { + } - public static void Free(ContainsContinueStatementWalker walker) - { - _cachedInstance = walker; + public override void VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + } + + public override void VisitWhileStatement(WhileStatementSyntax node) + { + } + + public static ContainsContinueStatementWalker GetInstance() + { + ContainsContinueStatementWalker walker = _cachedInstance; + + if (walker is not null) + { + _cachedInstance = null; + return walker; + } + + return new ContainsContinueStatementWalker(); + } + + public static void Free(ContainsContinueStatementWalker walker) + { + _cachedInstance = walker; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseGenericEventHandlerAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseGenericEventHandlerAnalyzer.cs index 19ec965246..e572c2133f 100644 --- a/src/Analyzers/CSharp/Analysis/UseGenericEventHandlerAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseGenericEventHandlerAnalyzer.cs @@ -8,104 +8,105 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseGenericEventHandlerAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseGenericEventHandlerAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseGenericEventHandler); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseGenericEventHandler); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - context.RegisterSymbolAction(f => AnalyzeEvent(f), SymbolKind.Event); - } + context.RegisterSymbolAction(f => AnalyzeEvent(f), SymbolKind.Event); + } - private static void AnalyzeEvent(SymbolAnalysisContext context) - { - var eventSymbol = (IEventSymbol)context.Symbol; + private static void AnalyzeEvent(SymbolAnalysisContext context) + { + var eventSymbol = (IEventSymbol)context.Symbol; - if (eventSymbol.IsImplicitlyDeclared) - return; + if (eventSymbol.IsImplicitlyDeclared) + return; - if (eventSymbol.IsOverride) - return; + if (eventSymbol.IsOverride) + return; - if (!eventSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty) - return; + if (!eventSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty) + return; - var namedType = eventSymbol.Type as INamedTypeSymbol; + var namedType = eventSymbol.Type as INamedTypeSymbol; - if (namedType?.Arity != 0) - return; + if (namedType?.Arity != 0) + return; - if (namedType.HasMetadataName(MetadataNames.System_EventHandler)) - return; + if (namedType.HasMetadataName(MetadataNames.System_EventHandler)) + return; - IMethodSymbol delegateInvokeMethod = namedType.DelegateInvokeMethod; + IMethodSymbol delegateInvokeMethod = namedType.DelegateInvokeMethod; - if (delegateInvokeMethod == null) - return; + if (delegateInvokeMethod is null) + return; - if (!delegateInvokeMethod.ReturnType.IsVoid()) - return; + if (!delegateInvokeMethod.ReturnType.IsVoid()) + return; - ImmutableArray parameters = delegateInvokeMethod.Parameters; + ImmutableArray parameters = delegateInvokeMethod.Parameters; - if (parameters.Length != 2) - return; + if (parameters.Length != 2) + return; - if (!parameters[0].Type.IsObject()) - return; + if (!parameters[0].Type.IsObject()) + return; - if (eventSymbol.ImplementsInterfaceMember(allInterfaces: true)) - return; + if (eventSymbol.ImplementsInterfaceMember(allInterfaces: true)) + return; - SyntaxNode node = eventSymbol.GetSyntax(context.CancellationToken); + SyntaxNode node = eventSymbol.GetSyntax(context.CancellationToken); - TypeSyntax type = GetTypeSyntax(node); + TypeSyntax type = GetTypeSyntax(node); - if (type == null) - return; + if (type is null) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseGenericEventHandler, type); - } + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseGenericEventHandler, type); + } - private static TypeSyntax GetTypeSyntax(SyntaxNode node) - { - switch (node) + private static TypeSyntax GetTypeSyntax(SyntaxNode node) { - case EventDeclarationSyntax eventDeclaration: - { - return eventDeclaration.Type; - } - case VariableDeclaratorSyntax declarator: - { - if (declarator.Parent is VariableDeclarationSyntax declaration) - return declaration.Type; - - SyntaxDebug.Fail(declarator.Parent); - break; - } - default: - { - SyntaxDebug.Fail(node); - break; - } + switch (node) + { + case EventDeclarationSyntax eventDeclaration: + { + return eventDeclaration.Type; + } + case VariableDeclaratorSyntax declarator: + { + if (declarator.Parent is VariableDeclarationSyntax declaration) + return declaration.Type; + + SyntaxDebug.Fail(declarator.Parent); + break; + } + default: + { + SyntaxDebug.Fail(node); + break; + } + } + + return null; } - - return null; } } diff --git a/src/Analyzers/CSharp/Analysis/UseNameOfOperatorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseNameOfOperatorAnalyzer.cs index 36f72363a3..89798473ed 100644 --- a/src/Analyzers/CSharp/Analysis/UseNameOfOperatorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseNameOfOperatorAnalyzer.cs @@ -11,271 +11,272 @@ using Roslynator.CSharp; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UseNameOfOperatorAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UseNameOfOperatorAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) + get { - Immutable.InterlockedInitialize( - ref _supportedDiagnostics, - DiagnosticRules.UseNameOfOperator, - DiagnosticRules.UseNameOfOperatorFadeOut); - } + if (_supportedDiagnostics.IsDefault) + { + Immutable.InterlockedInitialize( + ref _supportedDiagnostics, + DiagnosticRules.UseNameOfOperator, + DiagnosticRules.UseNameOfOperatorFadeOut); + } - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) - return; + base.Initialize(context); - startContext.RegisterSyntaxNodeAction( - c => - { - if (DiagnosticRules.UseNameOfOperator.IsEffective(c)) - AnalyzeArgument(c); - }, - SyntaxKind.Argument); - }); - } + context.RegisterCompilationStartAction(startContext => + { + if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) + return; + + startContext.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticRules.UseNameOfOperator.IsEffective(c)) + AnalyzeArgument(c); + }, + SyntaxKind.Argument); + }); + } - public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) - { - ExpressionSyntax expression = invocationInfo.Expression; + public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) + { + ExpressionSyntax expression = invocationInfo.Expression; - if (expression.Kind() != SyntaxKind.SimpleMemberAccessExpression) - return; + if (expression.Kind() != SyntaxKind.SimpleMemberAccessExpression) + return; - var memberAccessExpression = (MemberAccessExpressionSyntax)expression; + var memberAccessExpression = (MemberAccessExpressionSyntax)expression; - if (context.SemanticModel.GetSymbol(memberAccessExpression, context.CancellationToken) is not IFieldSymbol fieldSymbol) - return; + if (context.SemanticModel.GetSymbol(memberAccessExpression, context.CancellationToken) is not IFieldSymbol fieldSymbol) + return; - INamedTypeSymbol containingType = fieldSymbol.ContainingType; + INamedTypeSymbol containingType = fieldSymbol.ContainingType; - if (containingType?.TypeKind != TypeKind.Enum) - return; + if (containingType?.TypeKind != TypeKind.Enum) + return; - if (containingType.HasAttribute(MetadataNames.System_FlagsAttribute)) - return; + if (containingType.HasAttribute(MetadataNames.System_FlagsAttribute)) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseNameOfOperator, invocationInfo.InvocationExpression); - } + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseNameOfOperator, invocationInfo.InvocationExpression); + } - private static void AnalyzeArgument(SyntaxNodeAnalysisContext context) - { - var argument = (ArgumentSyntax)context.Node; + private static void AnalyzeArgument(SyntaxNodeAnalysisContext context) + { + var argument = (ArgumentSyntax)context.Node; - ExpressionSyntax expression = argument.Expression; + ExpressionSyntax expression = argument.Expression; - if (expression?.IsKind(SyntaxKind.StringLiteralExpression) != true) - return; + if (expression?.IsKind(SyntaxKind.StringLiteralExpression) != true) + return; - ParameterInfo parameterInfo = GetNextParametersInScope(argument); + ParameterInfo parameterInfo = GetNextParametersInScope(argument); - if (parameterInfo.Success) - { - Analyze(context, argument, expression, parameterInfo); + if (parameterInfo.Success) + { + Analyze(context, argument, expression, parameterInfo); + } + else + { + Analyze(context, argument, expression); + } } - else + + private static void Analyze( + SyntaxNodeAnalysisContext context, + ArgumentSyntax argument, + ExpressionSyntax expression, + in ParameterInfo parameterInfo) { - Analyze(context, argument, expression); - } - } + var literalExpression = (LiteralExpressionSyntax)expression; - private static void Analyze( - SyntaxNodeAnalysisContext context, - ArgumentSyntax argument, - ExpressionSyntax expression, - in ParameterInfo parameterInfo) - { - var literalExpression = (LiteralExpressionSyntax)expression; + ParameterSyntax parameter = FindMatchingParameter(parameterInfo, literalExpression.Token.ValueText); - ParameterSyntax parameter = FindMatchingParameter(parameterInfo, literalExpression.Token.ValueText); + if (parameter is null) + return; - if (parameter == null) - return; + IParameterSymbol parameterSymbol = context.SemanticModel.DetermineParameter(argument, allowParams: true, allowCandidate: false, cancellationToken: context.CancellationToken); - IParameterSymbol parameterSymbol = context.SemanticModel.DetermineParameter(argument, allowParams: true, allowCandidate: false, cancellationToken: context.CancellationToken); + if (parameterSymbol is null) + return; - if (parameterSymbol == null) - return; + string parameterName = parameterSymbol.Name; - string parameterName = parameterSymbol.Name; + if (!string.Equals(parameterName, "paramName", StringComparison.Ordinal) + && !string.Equals(parameterName, "parameterName", StringComparison.Ordinal)) + { + return; + } - if (!string.Equals(parameterName, "paramName", StringComparison.Ordinal) - && !string.Equals(parameterName, "parameterName", StringComparison.Ordinal)) - { - return; + ReportDiagnostic(context, literalExpression, parameter.Identifier.Text); } - ReportDiagnostic(context, literalExpression, parameter.Identifier.Text); - } - - private static ParameterSyntax FindMatchingParameter(ParameterInfo parameterInfo, string name) - { - do + private static ParameterSyntax FindMatchingParameter(ParameterInfo parameterInfo, string name) { - if (parameterInfo.Parameter != null) - { - ParameterSyntax parameter = parameterInfo.Parameter; - - if (string.Equals(parameter.Identifier.ValueText, name, StringComparison.Ordinal)) - return parameter; - } - else if (parameterInfo.ParameterList != null) + do { - foreach (ParameterSyntax parameter in parameterInfo.ParameterList.Parameters) + if (parameterInfo.Parameter is not null) { + ParameterSyntax parameter = parameterInfo.Parameter; + if (string.Equals(parameter.Identifier.ValueText, name, StringComparison.Ordinal)) return parameter; } + else if (parameterInfo.ParameterList is not null) + { + foreach (ParameterSyntax parameter in parameterInfo.ParameterList.Parameters) + { + if (string.Equals(parameter.Identifier.ValueText, name, StringComparison.Ordinal)) + return parameter; + } + } + + parameterInfo = GetNextParametersInScope(parameterInfo.Node); } + while (parameterInfo.Success); - parameterInfo = GetNextParametersInScope(parameterInfo.Node); + return null; } - while (parameterInfo.Success); - return null; - } - - private static ParameterInfo GetNextParametersInScope(SyntaxNode node) - { - for (SyntaxNode current = node.Parent; current != null; current = current.Parent) + private static ParameterInfo GetNextParametersInScope(SyntaxNode node) { - ParameterInfo info = ParameterInfo.Create(current); - - if (info.Success) - return info; - } - - return ParameterInfo.Empty; - } + for (SyntaxNode current = node.Parent; current is not null; current = current.Parent) + { + ParameterInfo info = ParameterInfo.Create(current); - private static void Analyze(SyntaxNodeAnalysisContext context, ArgumentSyntax argument, ExpressionSyntax expression) - { - AccessorDeclarationSyntax accessor = argument.FirstAncestor(); + if (info.Success) + return info; + } - if (accessor?.IsKind(SyntaxKind.SetAccessorDeclaration) != true) - return; + return ParameterInfo.Empty; + } - PropertyDeclarationSyntax property = accessor.FirstAncestor(); + private static void Analyze(SyntaxNodeAnalysisContext context, ArgumentSyntax argument, ExpressionSyntax expression) + { + AccessorDeclarationSyntax accessor = argument.FirstAncestor(); - if (property == null) - return; + if (accessor?.IsKind(SyntaxKind.SetAccessorDeclaration) != true) + return; - var literalExpression = (LiteralExpressionSyntax)expression; + PropertyDeclarationSyntax property = accessor.FirstAncestor(); - string text = literalExpression.Token.ValueText; + if (property is null) + return; - if (!string.Equals(property.Identifier.ValueText, text, StringComparison.Ordinal)) - return; + var literalExpression = (LiteralExpressionSyntax)expression; - IParameterSymbol parameterSymbol = context.SemanticModel.DetermineParameter(argument, allowParams: true, allowCandidate: false, cancellationToken: context.CancellationToken); + string text = literalExpression.Token.ValueText; - if (parameterSymbol == null) - return; + if (!string.Equals(property.Identifier.ValueText, text, StringComparison.Ordinal)) + return; - if (!string.Equals(parameterSymbol.Name, "propertyName", StringComparison.Ordinal)) - return; + IParameterSymbol parameterSymbol = context.SemanticModel.DetermineParameter(argument, allowParams: true, allowCandidate: false, cancellationToken: context.CancellationToken); - ReportDiagnostic(context, literalExpression, property.Identifier.Text); - } + if (parameterSymbol is null) + return; - private static void ReportDiagnostic( - SyntaxNodeAnalysisContext context, - LiteralExpressionSyntax literalExpression, - string identifier) - { - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseNameOfOperator, - literalExpression.GetLocation(), - ImmutableDictionary.CreateRange(new[] { new KeyValuePair("Identifier", identifier) })); + if (!string.Equals(parameterSymbol.Name, "propertyName", StringComparison.Ordinal)) + return; - string text = literalExpression.Token.Text; + ReportDiagnostic(context, literalExpression, property.Identifier.Text); + } - if (text.Length >= 2) + private static void ReportDiagnostic( + SyntaxNodeAnalysisContext context, + LiteralExpressionSyntax literalExpression, + string identifier) { - SyntaxTree syntaxTree = literalExpression.SyntaxTree; - TextSpan span = literalExpression.Span; - DiagnosticHelpers.ReportDiagnostic( context, - DiagnosticRules.UseNameOfOperatorFadeOut, - Location.Create(syntaxTree, new TextSpan(span.Start, (text[0] == '@') ? 2 : 1))); + DiagnosticRules.UseNameOfOperator, + literalExpression.GetLocation(), + ImmutableDictionary.CreateRange(new[] { new KeyValuePair("Identifier", identifier) })); - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseNameOfOperatorFadeOut, - Location.Create(syntaxTree, new TextSpan(span.End - 1, 1))); - } - } - - private readonly struct ParameterInfo - { - public static ParameterInfo Empty { get; } = new(); + string text = literalExpression.Token.Text; - private ParameterInfo(SyntaxNode node, ParameterSyntax parameter) - { - Node = node; - Parameter = parameter; - ParameterList = null; + if (text.Length >= 2) + { + SyntaxTree syntaxTree = literalExpression.SyntaxTree; + TextSpan span = literalExpression.Span; + + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseNameOfOperatorFadeOut, + Location.Create(syntaxTree, new TextSpan(span.Start, (text[0] == '@') ? 2 : 1))); + + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseNameOfOperatorFadeOut, + Location.Create(syntaxTree, new TextSpan(span.End - 1, 1))); + } } - private ParameterInfo(SyntaxNode node, BaseParameterListSyntax parameterList) + private readonly struct ParameterInfo { - Node = node; - Parameter = null; - ParameterList = parameterList; - } + public static ParameterInfo Empty { get; } = new(); - public ParameterSyntax Parameter { get; } + private ParameterInfo(SyntaxNode node, ParameterSyntax parameter) + { + Node = node; + Parameter = parameter; + ParameterList = null; + } - public BaseParameterListSyntax ParameterList { get; } + private ParameterInfo(SyntaxNode node, BaseParameterListSyntax parameterList) + { + Node = node; + Parameter = null; + ParameterList = parameterList; + } - public SyntaxNode Node { get; } + public ParameterSyntax Parameter { get; } - public bool Success - { - get { return Node != null; } - } + public BaseParameterListSyntax ParameterList { get; } - public static ParameterInfo Create(SyntaxNode node) - { - switch (node.Kind()) + public SyntaxNode Node { get; } + + public bool Success { - case SyntaxKind.MethodDeclaration: - return new ParameterInfo(node, ((MethodDeclarationSyntax)node).ParameterList); - case SyntaxKind.ConstructorDeclaration: - return new ParameterInfo(node, ((ConstructorDeclarationSyntax)node).ParameterList); - case SyntaxKind.IndexerDeclaration: - return new ParameterInfo(node, ((IndexerDeclarationSyntax)node).ParameterList); - case SyntaxKind.SimpleLambdaExpression: - return new ParameterInfo(node, ((SimpleLambdaExpressionSyntax)node).Parameter); - case SyntaxKind.ParenthesizedLambdaExpression: - return new ParameterInfo(node, ((ParenthesizedLambdaExpressionSyntax)node).ParameterList); - case SyntaxKind.AnonymousMethodExpression: - return new ParameterInfo(node, ((AnonymousMethodExpressionSyntax)node).ParameterList); - case SyntaxKind.LocalFunctionStatement: - return new ParameterInfo(node, ((LocalFunctionStatementSyntax)node).ParameterList); + get { return Node is not null; } } - return Empty; + public static ParameterInfo Create(SyntaxNode node) + { + switch (node.Kind()) + { + case SyntaxKind.MethodDeclaration: + return new ParameterInfo(node, ((MethodDeclarationSyntax)node).ParameterList); + case SyntaxKind.ConstructorDeclaration: + return new ParameterInfo(node, ((ConstructorDeclarationSyntax)node).ParameterList); + case SyntaxKind.IndexerDeclaration: + return new ParameterInfo(node, ((IndexerDeclarationSyntax)node).ParameterList); + case SyntaxKind.SimpleLambdaExpression: + return new ParameterInfo(node, ((SimpleLambdaExpressionSyntax)node).Parameter); + case SyntaxKind.ParenthesizedLambdaExpression: + return new ParameterInfo(node, ((ParenthesizedLambdaExpressionSyntax)node).ParameterList); + case SyntaxKind.AnonymousMethodExpression: + return new ParameterInfo(node, ((AnonymousMethodExpressionSyntax)node).ParameterList); + case SyntaxKind.LocalFunctionStatement: + return new ParameterInfo(node, ((LocalFunctionStatementSyntax)node).ParameterList); + } + + return Empty; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfAsAndNullCheckAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfAsAndNullCheckAnalyzer.cs index 82a612a308..2617fdb8e6 100644 --- a/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfAsAndNullCheckAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfAsAndNullCheckAnalyzer.cs @@ -9,93 +9,94 @@ using Microsoft.CodeAnalysis.Diagnostics; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis.UsePatternMatching; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UsePatternMatchingInsteadOfAsAndNullCheckAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis.UsePatternMatching { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UsePatternMatchingInsteadOfAsAndNullCheckAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UsePatternMatchingInsteadOfAsAndNullCheck); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UsePatternMatchingInsteadOfAsAndNullCheck); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp7) - return; + base.Initialize(context); - startContext.RegisterSyntaxNodeAction(f => AnalyzeAsExpression(f), SyntaxKind.AsExpression); - }); - } + context.RegisterCompilationStartAction(startContext => + { + if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp7) + return; - private static void AnalyzeAsExpression(SyntaxNodeAnalysisContext context) - { - var asExpression = (BinaryExpressionSyntax)context.Node; + startContext.RegisterSyntaxNodeAction(f => AnalyzeAsExpression(f), SyntaxKind.AsExpression); + }); + } - AsExpressionInfo asExpressionInfo = SyntaxInfo.AsExpressionInfo(asExpression); + private static void AnalyzeAsExpression(SyntaxNodeAnalysisContext context) + { + var asExpression = (BinaryExpressionSyntax)context.Node; - if (!asExpressionInfo.Success) - return; + AsExpressionInfo asExpressionInfo = SyntaxInfo.AsExpressionInfo(asExpression); - SingleLocalDeclarationStatementInfo localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo(asExpression); + if (!asExpressionInfo.Success) + return; - if (!localInfo.Success) - return; + SingleLocalDeclarationStatementInfo localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo(asExpression); - if (localInfo.Statement.SpanOrTrailingTriviaContainsDirectives()) - return; + if (!localInfo.Success) + return; - if (localInfo.Statement.NextStatement() is not IfStatementSyntax ifStatement) - return; + if (localInfo.Statement.SpanOrTrailingTriviaContainsDirectives()) + return; - if (!ifStatement.IsSimpleIf()) - return; + if (localInfo.Statement.NextStatement() is not IfStatementSyntax ifStatement) + return; - if (ifStatement.SpanOrLeadingTriviaContainsDirectives()) - return; + if (!ifStatement.IsSimpleIf()) + return; - StatementSyntax statement = ifStatement.SingleNonBlockStatementOrDefault(); + if (ifStatement.SpanOrLeadingTriviaContainsDirectives()) + return; - if (statement == null) - return; + StatementSyntax statement = ifStatement.SingleNonBlockStatementOrDefault(); - if (!CSharpFacts.IsJumpStatement(statement.Kind())) - return; + if (statement is null) + return; - NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(ifStatement.Condition, NullCheckStyles.EqualsToNull | NullCheckStyles.IsNull); + if (!CSharpFacts.IsJumpStatement(statement.Kind())) + return; - if (!nullCheck.Success) - return; + NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(ifStatement.Condition, NullCheckStyles.EqualsToNull | NullCheckStyles.IsNull); - if (!string.Equals(localInfo.IdentifierText, (nullCheck.Expression as IdentifierNameSyntax)?.Identifier.ValueText, StringComparison.Ordinal)) - return; + if (!nullCheck.Success) + return; - if (!localInfo.Type.IsVar) - { - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + if (!string.Equals(localInfo.IdentifierText, (nullCheck.Expression as IdentifierNameSyntax)?.Identifier.ValueText, StringComparison.Ordinal)) + return; - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(asExpressionInfo.Type, cancellationToken); + if (!localInfo.Type.IsVar) + { + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (typeSymbol.IsNullableType()) - return; + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(asExpressionInfo.Type, cancellationToken); - if (!SymbolEqualityComparer.Default.Equals(semanticModel.GetTypeSymbol(localInfo.Type, cancellationToken), typeSymbol)) - return; - } + if (typeSymbol.IsNullableType()) + return; + + if (!SymbolEqualityComparer.Default.Equals(semanticModel.GetTypeSymbol(localInfo.Type, cancellationToken), typeSymbol)) + return; + } - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePatternMatchingInsteadOfAsAndNullCheck, localInfo.Statement); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePatternMatchingInsteadOfAsAndNullCheck, localInfo.Statement); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfIsAndCastAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfIsAndCastAnalyzer.cs index ef6d303262..d35f15f28a 100644 --- a/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfIsAndCastAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfIsAndCastAnalyzer.cs @@ -9,152 +9,153 @@ using Microsoft.CodeAnalysis.Diagnostics; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis.UsePatternMatching; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UsePatternMatchingInsteadOfIsAndCastAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis.UsePatternMatching { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UsePatternMatchingInsteadOfIsAndCastAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UsePatternMatchingInsteadOfIsAndCast); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UsePatternMatchingInsteadOfIsAndCast); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterCompilationStartAction(startContext => + public override void Initialize(AnalysisContext context) { - if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp7) - return; + base.Initialize(context); - startContext.RegisterSyntaxNodeAction(f => AnalyzeIsExpression(f), SyntaxKind.IsExpression); - }); - } + context.RegisterCompilationStartAction(startContext => + { + if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp7) + return; - private static void AnalyzeIsExpression(SyntaxNodeAnalysisContext context) - { - var isExpression = (BinaryExpressionSyntax)context.Node; + startContext.RegisterSyntaxNodeAction(f => AnalyzeIsExpression(f), SyntaxKind.IsExpression); + }); + } + + private static void AnalyzeIsExpression(SyntaxNodeAnalysisContext context) + { + var isExpression = (BinaryExpressionSyntax)context.Node; - IsExpressionInfo isExpressionInfo = SyntaxInfo.IsExpressionInfo(isExpression); + IsExpressionInfo isExpressionInfo = SyntaxInfo.IsExpressionInfo(isExpression); - if (!isExpressionInfo.Success) - return; + if (!isExpressionInfo.Success) + return; - ExpressionSyntax expression = isExpressionInfo.Expression; + ExpressionSyntax expression = isExpressionInfo.Expression; - var identifierName = expression as IdentifierNameSyntax; + var identifierName = expression as IdentifierNameSyntax; - if (identifierName == null) - { - if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) + if (identifierName is null) { - var memberAccess = (MemberAccessExpressionSyntax)expression; + if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - if (memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) - identifierName = memberAccess.Name as IdentifierNameSyntax; - } + if (memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) + identifierName = memberAccess.Name as IdentifierNameSyntax; + } - if (identifierName == null) - return; - } + if (identifierName is null) + return; + } - ExpressionSyntax left = isExpression.WalkUpParentheses(); + ExpressionSyntax left = isExpression.WalkUpParentheses(); - SyntaxNode node = left.Parent; + SyntaxNode node = left.Parent; - if (node.ContainsDiagnostics) - return; + if (node.ContainsDiagnostics) + return; - switch (node.Kind()) - { - case SyntaxKind.LogicalAndExpression: - { - var logicalAnd = (BinaryExpressionSyntax)node; + switch (node.Kind()) + { + case SyntaxKind.LogicalAndExpression: + { + var logicalAnd = (BinaryExpressionSyntax)node; - if (left != logicalAnd.Left) - return; + if (left != logicalAnd.Left) + return; - ExpressionSyntax right = logicalAnd.Right; + ExpressionSyntax right = logicalAnd.Right; - if (right == 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; - } - case SyntaxKind.IfStatement: - { - var ifStatement = (IfStatementSyntax)node; + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePatternMatchingInsteadOfIsAndCast, logicalAnd); + break; + } + case SyntaxKind.IfStatement: + { + var ifStatement = (IfStatementSyntax)node; - if (left != ifStatement.Condition) - return; + if (left != ifStatement.Condition) + return; - StatementSyntax statement = ifStatement.Statement; + StatementSyntax statement = ifStatement.Statement; - if (statement == 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; + } + } } - } - private static bool IsFixable( - SyntaxNode node, - IdentifierNameSyntax identifierName, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - bool isFixable; - UsePatternMatchingWalker walker = null; - - try + private static bool IsFixable( + SyntaxNode node, + IdentifierNameSyntax identifierName, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - walker = UsePatternMatchingWalker.GetInstance(); + bool isFixable; + UsePatternMatchingWalker walker = null; - walker.SetValues(identifierName, semanticModel, cancellationToken); + try + { + walker = UsePatternMatchingWalker.GetInstance(); - walker.Visit(node); + walker.SetValues(identifierName, semanticModel, cancellationToken); - isFixable = walker.IsFixable.GetValueOrDefault(); - } - finally - { - if (walker != null) - UsePatternMatchingWalker.Free(walker); - } + walker.Visit(node); - return isFixable; + isFixable = walker.IsFixable.GetValueOrDefault(); + } + finally + { + if (walker is not null) + UsePatternMatchingWalker.Free(walker); + } + + return isFixable; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingWalker.cs b/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingWalker.cs index 2fc6803a77..9fe2cd5277 100644 --- a/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingWalker.cs +++ b/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingWalker.cs @@ -8,100 +8,101 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis.UsePatternMatching; - -internal class UsePatternMatchingWalker : CSharpSyntaxNodeWalker +namespace Roslynator.CSharp.Analysis.UsePatternMatching { - [ThreadStatic] - private static UsePatternMatchingWalker _cachedInstance; - - private ISymbol _symbol; - private IdentifierNameSyntax _identifierName; - private string _name; - private SemanticModel _semanticModel; - private CancellationToken _cancellationToken; - - public bool? IsFixable { get; private set; } - - protected override bool ShouldVisit + internal class UsePatternMatchingWalker : CSharpSyntaxNodeWalker { - get { return IsFixable != false; } - } + [ThreadStatic] + private static UsePatternMatchingWalker _cachedInstance; - public void SetValues( - IdentifierNameSyntax identifierName, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - IsFixable = null; + private ISymbol _symbol; + private IdentifierNameSyntax _identifierName; + private string _name; + private SemanticModel _semanticModel; + private CancellationToken _cancellationToken; - _symbol = null; - _name = identifierName?.Identifier.ValueText; - _identifierName = identifierName; - _semanticModel = semanticModel; - _cancellationToken = cancellationToken; - } + public bool? IsFixable { get; private set; } - public override void VisitIdentifierName(IdentifierNameSyntax node) - { - _cancellationToken.ThrowIfCancellationRequested(); + protected override bool ShouldVisit + { + get { return IsFixable != false; } + } - if (string.Equals(node.Identifier.ValueText, _name)) + public void SetValues( + IdentifierNameSyntax identifierName, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - if (_symbol == null) - { - _symbol = _semanticModel.GetSymbol(_identifierName, _cancellationToken); + IsFixable = null; - if (_symbol?.IsErrorType() != false) - { - IsFixable = false; - return; - } - } + _symbol = null; + _name = identifierName?.Identifier.ValueText; + _identifierName = identifierName; + _semanticModel = semanticModel; + _cancellationToken = cancellationToken; + } - if (SymbolEqualityComparer.Default.Equals(_symbol, _semanticModel.GetSymbol(node, _cancellationToken))) - { - ExpressionSyntax n = node; + public override void VisitIdentifierName(IdentifierNameSyntax node) + { + _cancellationToken.ThrowIfCancellationRequested(); - if (n.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) - && ((MemberAccessExpressionSyntax)n.Parent).Expression.IsKind(SyntaxKind.ThisExpression)) + if (string.Equals(node.Identifier.ValueText, _name)) + { + if (_symbol is null) { - n = (ExpressionSyntax)n.Parent; + _symbol = _semanticModel.GetSymbol(_identifierName, _cancellationToken); + + if (_symbol?.IsErrorType() != false) + { + IsFixable = false; + return; + } } - if (!n.WalkUpParentheses().IsParentKind(SyntaxKind.CastExpression)) + if (SymbolEqualityComparer.Default.Equals(_symbol, _semanticModel.GetSymbol(node, _cancellationToken))) { - IsFixable = false; - return; - } + ExpressionSyntax n = node; + + if (n.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) + && ((MemberAccessExpressionSyntax)n.Parent).Expression.IsKind(SyntaxKind.ThisExpression)) + { + n = (ExpressionSyntax)n.Parent; + } - IsFixable = true; + if (!n.WalkUpParentheses().IsParentKind(SyntaxKind.CastExpression)) + { + IsFixable = false; + return; + } + + IsFixable = true; + } } } - } - - public static UsePatternMatchingWalker GetInstance() - { - UsePatternMatchingWalker walker = _cachedInstance; - if (walker != null) + public static UsePatternMatchingWalker GetInstance() { - Debug.Assert(walker._symbol == null); - Debug.Assert(walker._identifierName == null); - Debug.Assert(walker._semanticModel == null); - Debug.Assert(walker._cancellationToken == default); + UsePatternMatchingWalker walker = _cachedInstance; - _cachedInstance = null; - return walker; - } + if (walker is not null) + { + Debug.Assert(walker._symbol is null); + Debug.Assert(walker._identifierName is null); + Debug.Assert(walker._semanticModel is null); + Debug.Assert(walker._cancellationToken == default); - return new UsePatternMatchingWalker(); - } + _cachedInstance = null; + return walker; + } - public static void Free(UsePatternMatchingWalker walker) - { - walker.SetValues(default(IdentifierNameSyntax), default(SemanticModel), default(CancellationToken)); + return new UsePatternMatchingWalker(); + } + + public static void Free(UsePatternMatchingWalker walker) + { + walker.SetValues(default(IdentifierNameSyntax), default(SemanticModel), default(CancellationToken)); - _cachedInstance = walker; + _cachedInstance = walker; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UsePredefinedTypeAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UsePredefinedTypeAnalyzer.cs index d6f7ef519f..aaa1875556 100644 --- a/src/Analyzers/CSharp/Analysis/UsePredefinedTypeAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UsePredefinedTypeAnalyzer.cs @@ -7,243 +7,244 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class UsePredefinedTypeAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class UsePredefinedTypeAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UsePredefinedType); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UsePredefinedType); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); - - context.RegisterSyntaxNodeAction(f => AnalyzeQualifiedName(f), SyntaxKind.QualifiedName); - context.RegisterSyntaxNodeAction(f => AnalyzeIdentifierName(f), SyntaxKind.IdentifierName); - context.RegisterSyntaxNodeAction(f => AnalyzeXmlCrefAttribute(f), SyntaxKind.XmlCrefAttribute); - context.RegisterSyntaxNodeAction(f => AnalyzeSimpleMemberAccessExpression(f), SyntaxKind.SimpleMemberAccessExpression); - } - - private static void AnalyzeIdentifierName(SyntaxNodeAnalysisContext context) - { - var identifierName = (IdentifierNameSyntax)context.Node; - if (identifierName.IsVar) - return; - - if (identifierName.IsParentKind( - SyntaxKind.SimpleMemberAccessExpression, - SyntaxKind.QualifiedName, - SyntaxKind.UsingDirective)) + public override void Initialize(AnalysisContext context) { - return; - } + base.Initialize(context); - if (!SupportsPredefinedType(identifierName)) - return; + context.RegisterSyntaxNodeAction(f => AnalyzeQualifiedName(f), SyntaxKind.QualifiedName); + context.RegisterSyntaxNodeAction(f => AnalyzeIdentifierName(f), SyntaxKind.IdentifierName); + context.RegisterSyntaxNodeAction(f => AnalyzeXmlCrefAttribute(f), SyntaxKind.XmlCrefAttribute); + context.RegisterSyntaxNodeAction(f => AnalyzeSimpleMemberAccessExpression(f), SyntaxKind.SimpleMemberAccessExpression); + } - if (identifierName.IsPartOfDocumentationComment()) - return; + private static void AnalyzeIdentifierName(SyntaxNodeAnalysisContext context) + { + var identifierName = (IdentifierNameSyntax)context.Node; - if (IsArgumentExpressionOfNameOfExpression(context, identifierName)) - return; + if (identifierName.IsVar) + return; - if (context.SemanticModel.GetSymbol(identifierName, context.CancellationToken) is not ITypeSymbol typeSymbol) - return; + if (identifierName.IsParentKind( + SyntaxKind.SimpleMemberAccessExpression, + SyntaxKind.QualifiedName, + SyntaxKind.UsingDirective)) + { + return; + } - if (!CSharpFacts.IsPredefinedType(typeSymbol.SpecialType)) - return; + if (!SupportsPredefinedType(identifierName)) + return; - IAliasSymbol aliasSymbol = context.SemanticModel.GetAliasInfo(identifierName, context.CancellationToken); + if (identifierName.IsPartOfDocumentationComment()) + return; - if (aliasSymbol != null) - return; + if (IsArgumentExpressionOfNameOfExpression(context, identifierName)) + return; - ReportDiagnostic(context, identifierName); - } + if (context.SemanticModel.GetSymbol(identifierName, context.CancellationToken) is not ITypeSymbol typeSymbol) + return; - private static void AnalyzeXmlCrefAttribute(SyntaxNodeAnalysisContext context) - { - var xmlCrefAttribute = (XmlCrefAttributeSyntax)context.Node; + if (!CSharpFacts.IsPredefinedType(typeSymbol.SpecialType)) + return; - CrefSyntax cref = xmlCrefAttribute.Cref; + IAliasSymbol aliasSymbol = context.SemanticModel.GetAliasInfo(identifierName, context.CancellationToken); - switch (cref?.Kind()) - { - case SyntaxKind.NameMemberCref: - { - Analyze(context, cref, (NameMemberCrefSyntax)cref); - break; - } - case SyntaxKind.QualifiedCref: - { - var qualifiedCref = (QualifiedCrefSyntax)cref; - - MemberCrefSyntax memberCref = qualifiedCref.Member; - - if (memberCref?.IsKind(SyntaxKind.NameMemberCref) != true) - break; + if (aliasSymbol is not null) + return; - Analyze(context, cref, (NameMemberCrefSyntax)memberCref); - break; - } + ReportDiagnostic(context, identifierName); } - } - - private static void Analyze(SyntaxNodeAnalysisContext context, CrefSyntax cref, NameMemberCrefSyntax nameMemberCref) - { - if (nameMemberCref.Name is not IdentifierNameSyntax identifierName) - return; - if (!SupportsPredefinedType(identifierName)) - return; + private static void AnalyzeXmlCrefAttribute(SyntaxNodeAnalysisContext context) + { + var xmlCrefAttribute = (XmlCrefAttributeSyntax)context.Node; - if (context.SemanticModel.GetSymbol(identifierName, context.CancellationToken) is not ITypeSymbol typeSymbol) - return; + CrefSyntax cref = xmlCrefAttribute.Cref; - if (!CSharpFacts.IsPredefinedType(typeSymbol.SpecialType)) - return; + switch (cref?.Kind()) + { + case SyntaxKind.NameMemberCref: + { + Analyze(context, cref, (NameMemberCrefSyntax)cref); + break; + } + case SyntaxKind.QualifiedCref: + { + var qualifiedCref = (QualifiedCrefSyntax)cref; - IAliasSymbol aliasSymbol = context.SemanticModel.GetAliasInfo(identifierName, context.CancellationToken); + MemberCrefSyntax memberCref = qualifiedCref.Member; - if (aliasSymbol != null) - return; + if (memberCref?.IsKind(SyntaxKind.NameMemberCref) != true) + break; - ReportDiagnostic(context, cref); - } + Analyze(context, cref, (NameMemberCrefSyntax)memberCref); + break; + } + } + } - private static void AnalyzeQualifiedName(SyntaxNodeAnalysisContext context) - { - var qualifiedName = (QualifiedNameSyntax)context.Node; + private static void Analyze(SyntaxNodeAnalysisContext context, CrefSyntax cref, NameMemberCrefSyntax nameMemberCref) + { + if (nameMemberCref.Name is not IdentifierNameSyntax identifierName) + return; - if (qualifiedName.IsParentKind(SyntaxKind.UsingDirective)) - return; + if (!SupportsPredefinedType(identifierName)) + return; - if (qualifiedName.Right is not IdentifierNameSyntax identifierName) - return; + if (context.SemanticModel.GetSymbol(identifierName, context.CancellationToken) is not ITypeSymbol typeSymbol) + return; - if (!SupportsPredefinedType(identifierName)) - return; + if (!CSharpFacts.IsPredefinedType(typeSymbol.SpecialType)) + return; - if (IsArgumentExpressionOfNameOfExpression(context, qualifiedName)) - return; + IAliasSymbol aliasSymbol = context.SemanticModel.GetAliasInfo(identifierName, context.CancellationToken); - if (context.SemanticModel.GetSymbol(qualifiedName, context.CancellationToken) is not ITypeSymbol typeSymbol) - return; + if (aliasSymbol is not null) + return; - if (!CSharpFacts.IsPredefinedType(typeSymbol.SpecialType)) - return; + ReportDiagnostic(context, cref); + } - ReportDiagnostic(context, qualifiedName); - } + private static void AnalyzeQualifiedName(SyntaxNodeAnalysisContext context) + { + var qualifiedName = (QualifiedNameSyntax)context.Node; - private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContext context) - { - var memberAccess = (MemberAccessExpressionSyntax)context.Node; + if (qualifiedName.IsParentKind(SyntaxKind.UsingDirective)) + return; - if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) - return; + if (qualifiedName.Right is not IdentifierNameSyntax identifierName) + return; - ExpressionSyntax expression = memberAccess.Expression; + if (!SupportsPredefinedType(identifierName)) + return; - if (expression == null) - return; + if (IsArgumentExpressionOfNameOfExpression(context, qualifiedName)) + return; - SyntaxKind kind = expression.Kind(); + if (context.SemanticModel.GetSymbol(qualifiedName, context.CancellationToken) is not ITypeSymbol typeSymbol) + return; - if (kind == SyntaxKind.IdentifierName) - { - if (!SupportsPredefinedType((IdentifierNameSyntax)expression)) + if (!CSharpFacts.IsPredefinedType(typeSymbol.SpecialType)) return; + + ReportDiagnostic(context, qualifiedName); } - else if (kind == SyntaxKind.SimpleMemberAccessExpression) + + private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContext context) { - memberAccess = (MemberAccessExpressionSyntax)expression; + var memberAccess = (MemberAccessExpressionSyntax)context.Node; - if (memberAccess.Name is not IdentifierNameSyntax identifierName) + if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) return; - if (!SupportsPredefinedType(identifierName)) + ExpressionSyntax expression = memberAccess.Expression; + + if (expression is null) return; - } - else - { - return; - } - if (context.SemanticModel.GetSymbol(expression, context.CancellationToken) is not ITypeSymbol typeSymbol) - return; + SyntaxKind kind = expression.Kind(); + + if (kind == SyntaxKind.IdentifierName) + { + if (!SupportsPredefinedType((IdentifierNameSyntax)expression)) + return; + } + else if (kind == SyntaxKind.SimpleMemberAccessExpression) + { + memberAccess = (MemberAccessExpressionSyntax)expression; + + if (memberAccess.Name is not IdentifierNameSyntax identifierName) + return; + + if (!SupportsPredefinedType(identifierName)) + return; + } + else + { + return; + } - if (!CSharpFacts.IsPredefinedType(typeSymbol.SpecialType)) - return; + if (context.SemanticModel.GetSymbol(expression, context.CancellationToken) is not ITypeSymbol typeSymbol) + return; - IAliasSymbol aliasSymbol = context.SemanticModel.GetAliasInfo(expression, context.CancellationToken); + if (!CSharpFacts.IsPredefinedType(typeSymbol.SpecialType)) + return; - if (aliasSymbol != null) - return; + IAliasSymbol aliasSymbol = context.SemanticModel.GetAliasInfo(expression, context.CancellationToken); - ReportDiagnostic(context, expression); - } + if (aliasSymbol is not null) + return; - private static bool IsArgumentExpressionOfNameOfExpression(SyntaxNodeAnalysisContext context, SyntaxNode node) - { - SyntaxNode parent = node.Parent; + ReportDiagnostic(context, expression); + } - if (parent?.IsKind(SyntaxKind.Argument) != true) - return false; + private static bool IsArgumentExpressionOfNameOfExpression(SyntaxNodeAnalysisContext context, SyntaxNode node) + { + SyntaxNode parent = node.Parent; - parent = parent.Parent; + if (parent?.IsKind(SyntaxKind.Argument) != true) + return false; - if (parent?.IsKind(SyntaxKind.ArgumentList) != true) - return false; + parent = parent.Parent; - parent = parent.Parent; + if (parent?.IsKind(SyntaxKind.ArgumentList) != true) + return false; - return parent != null - && CSharpUtility.IsNameOfExpression(parent, context.SemanticModel, context.CancellationToken); - } + parent = parent.Parent; - private static bool SupportsPredefinedType(IdentifierNameSyntax identifierName) - { - if (identifierName == null) - return false; + return parent is not null + && CSharpUtility.IsNameOfExpression(parent, context.SemanticModel, context.CancellationToken); + } - switch (identifierName.Identifier.ValueText) + private static bool SupportsPredefinedType(IdentifierNameSyntax identifierName) { - case "Object": - case "Boolean": - case "Char": - case "SByte": - case "Byte": - case "Int16": - case "UInt16": - case "Int32": - case "UInt32": - case "Int64": - case "UInt64": - case "Decimal": - case "Single": - case "Double": - case "String": - return true; - default: + if (identifierName is null) return false; + + switch (identifierName.Identifier.ValueText) + { + case "Object": + case "Boolean": + case "Char": + case "SByte": + case "Byte": + case "Int16": + case "UInt16": + case "Int32": + case "UInt32": + case "Int64": + case "UInt64": + case "Decimal": + case "Single": + case "Double": + case "String": + return true; + default: + return false; + } } - } - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePredefinedType, node); + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePredefinedType, node); + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseRegexInstanceInsteadOfStaticMethodAnalysis.cs b/src/Analyzers/CSharp/Analysis/UseRegexInstanceInsteadOfStaticMethodAnalysis.cs index f57ed33823..325c3c981c 100644 --- a/src/Analyzers/CSharp/Analysis/UseRegexInstanceInsteadOfStaticMethodAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/UseRegexInstanceInsteadOfStaticMethodAnalysis.cs @@ -8,88 +8,89 @@ using Roslynator.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp; -namespace Roslynator.CSharp.Analysis; - -internal static class UseRegexInstanceInsteadOfStaticMethodAnalysis +namespace Roslynator.CSharp.Analysis { - internal static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) + internal static class UseRegexInstanceInsteadOfStaticMethodAnalysis { - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + internal static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) + { + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationInfo.InvocationExpression, cancellationToken); + IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationInfo.InvocationExpression, cancellationToken); - if (!SymbolUtility.IsPublicStaticNonGeneric(methodSymbol)) - return; + if (!SymbolUtility.IsPublicStaticNonGeneric(methodSymbol)) + return; - if (methodSymbol.ContainingType?.HasMetadataName(MetadataNames.System_Text_RegularExpressions_Regex) != true) - return; + if (methodSymbol.ContainingType?.HasMetadataName(MetadataNames.System_Text_RegularExpressions_Regex) != true) + return; - SeparatedSyntaxList arguments = invocationInfo.Arguments; + SeparatedSyntaxList arguments = invocationInfo.Arguments; - if (!ValidateArgument(arguments[1])) - return; + if (!ValidateArgument(arguments[1])) + return; - if (methodSymbol.Name == "Replace") - { - if (arguments.Count == 4 - && !ValidateArgument(arguments[3])) + if (methodSymbol.Name == "Replace") + { + if (arguments.Count == 4 + && !ValidateArgument(arguments[3])) + { + return; + } + } + else if (arguments.Count == 3 + && !ValidateArgument(arguments[2])) { return; } - } - else if (arguments.Count == 3 - && !ValidateArgument(arguments[2])) - { - return; - } - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseRegexInstanceInsteadOfStaticMethod, invocationInfo.Name); + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseRegexInstanceInsteadOfStaticMethod, invocationInfo.Name); - bool ValidateArgument(ArgumentSyntax argument) - { - ExpressionSyntax expression = argument.Expression; + bool ValidateArgument(ArgumentSyntax argument) + { + ExpressionSyntax expression = argument.Expression; - if (expression == null) - return false; + if (expression is null) + return false; - if (expression.WalkDownParentheses() is LiteralExpressionSyntax) - return true; + if (expression.WalkDownParentheses() is LiteralExpressionSyntax) + return true; - if (!semanticModel.HasConstantValue(expression, cancellationToken)) - return false; + if (!semanticModel.HasConstantValue(expression, cancellationToken)) + return false; - ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); + ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); - SyntaxDebug.Assert( - symbol != null || expression.WalkDownParentheses().IsKind(SyntaxKind.InterpolatedStringExpression), - expression); + SyntaxDebug.Assert( + symbol is not null || expression.WalkDownParentheses().IsKind(SyntaxKind.InterpolatedStringExpression), + expression); - if (symbol == null) - return true; + if (symbol is null) + return true; - switch (symbol.Kind) - { - case SymbolKind.Field: - { - return ((IFieldSymbol)symbol).HasConstantValue; - } - case SymbolKind.Method: - { - if (((IMethodSymbol)symbol).MethodKind != MethodKind.BuiltinOperator) - return false; + switch (symbol.Kind) + { + case SymbolKind.Field: + { + return ((IFieldSymbol)symbol).HasConstantValue; + } + case SymbolKind.Method: + { + if (((IMethodSymbol)symbol).MethodKind != MethodKind.BuiltinOperator) + return false; - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (typeSymbol == null) - return false; + if (typeSymbol is null) + return false; - return typeSymbol.HasMetadataName(MetadataNames.System_Text_RegularExpressions_RegexOptions); - } - default: - { - return false; - } + return typeSymbol.HasMetadataName(MetadataNames.System_Text_RegularExpressions_RegexOptions); + } + default: + { + return false; + } + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseStringComparisonAnalysis.cs b/src/Analyzers/CSharp/Analysis/UseStringComparisonAnalysis.cs index 2ae9418e78..fa1b31a030 100644 --- a/src/Analyzers/CSharp/Analysis/UseStringComparisonAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/UseStringComparisonAnalysis.cs @@ -10,273 +10,274 @@ using Roslynator.CSharp; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Analysis; - -internal static class UseStringComparisonAnalysis +namespace Roslynator.CSharp.Analysis { - public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) + internal static class UseStringComparisonAnalysis { - ExpressionSyntax expression = invocationInfo.InvocationExpression.WalkUpParentheses(); + public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) + { + ExpressionSyntax expression = invocationInfo.InvocationExpression.WalkUpParentheses(); - SyntaxNode parent = expression.Parent; + SyntaxNode parent = expression.Parent; - SyntaxKind kind = parent.Kind(); + SyntaxKind kind = parent.Kind(); - if (kind == SyntaxKind.SimpleMemberAccessExpression) - { - SimpleMemberInvocationExpressionInfo invocationInfo2 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(parent.Parent); + if (kind == SyntaxKind.SimpleMemberAccessExpression) + { + SimpleMemberInvocationExpressionInfo invocationInfo2 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(parent.Parent); - if (!invocationInfo2.Success) - return; + if (!invocationInfo2.Success) + return; - Analyze(context, invocationInfo, invocationInfo2); - } - else if (kind == SyntaxKind.Argument) - { - Analyze(context, invocationInfo, (ArgumentSyntax)parent); + Analyze(context, invocationInfo, invocationInfo2); + } + else if (kind == SyntaxKind.Argument) + { + Analyze(context, invocationInfo, (ArgumentSyntax)parent); + } + else if (kind == SyntaxKind.EqualsExpression + || kind == SyntaxKind.NotEqualsExpression) + { + Analyze(context, invocationInfo, expression, (BinaryExpressionSyntax)parent); + } } - else if (kind == SyntaxKind.EqualsExpression - || kind == SyntaxKind.NotEqualsExpression) + + private static void Analyze( + SyntaxNodeAnalysisContext context, + in SimpleMemberInvocationExpressionInfo invocationInfo, + in SimpleMemberInvocationExpressionInfo invocationInfo2) { - Analyze(context, invocationInfo, expression, (BinaryExpressionSyntax)parent); - } - } + if (invocationInfo2.InvocationExpression.SpanContainsDirectives()) + return; - private static void Analyze( - SyntaxNodeAnalysisContext context, - in SimpleMemberInvocationExpressionInfo invocationInfo, - in SimpleMemberInvocationExpressionInfo invocationInfo2) - { - if (invocationInfo2.InvocationExpression.SpanContainsDirectives()) - return; + string name2 = invocationInfo2.NameText; - string name2 = invocationInfo2.NameText; + if (name2 != "Equals" + && name2 != "StartsWith" + && name2 != "EndsWith" + && name2 != "IndexOf" + && name2 != "LastIndexOf" + && name2 != "Contains") + { + return; + } - if (name2 != "Equals" - && name2 != "StartsWith" - && name2 != "EndsWith" - && name2 != "IndexOf" - && name2 != "LastIndexOf" - && name2 != "Contains") - { - return; - } + SeparatedSyntaxList arguments = invocationInfo2.Arguments; - SeparatedSyntaxList arguments = invocationInfo2.Arguments; + if (arguments.Count != 1) + return; - if (arguments.Count != 1) - return; + ExpressionSyntax argumentExpression = arguments[0].Expression.WalkDownParentheses(); - ExpressionSyntax argumentExpression = arguments[0].Expression.WalkDownParentheses(); + string name = invocationInfo.NameText; - string name = invocationInfo.NameText; + SimpleMemberInvocationExpressionInfo invocationInfo3; - SimpleMemberInvocationExpressionInfo invocationInfo3; + bool isStringLiteral = argumentExpression.IsKind(SyntaxKind.StringLiteralExpression); - bool isStringLiteral = argumentExpression.IsKind(SyntaxKind.StringLiteralExpression); + if (!isStringLiteral) + { + invocationInfo3 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(argumentExpression); - if (!isStringLiteral) - { - invocationInfo3 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(argumentExpression); + if (!invocationInfo3.Success) + return; - if (!invocationInfo3.Success) - return; + string name3 = invocationInfo3.NameText; + + if (name != name3) + return; + } - string name3 = invocationInfo3.NameText; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (name != name3) + if (!CheckSymbol(invocationInfo, semanticModel, cancellationToken)) return; - } - - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; - if (!CheckSymbol(invocationInfo, semanticModel, cancellationToken)) - return; + IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationInfo2.InvocationExpression, cancellationToken); - IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationInfo2.InvocationExpression, cancellationToken); + if (!SymbolUtility.IsPublicInstanceNonGeneric(methodSymbol, name2)) + return; - if (!SymbolUtility.IsPublicInstanceNonGeneric(methodSymbol, name2)) - return; + if (!methodSymbol.IsContainingType(SpecialType.System_String)) + return; - if (!methodSymbol.IsContainingType(SpecialType.System_String)) - return; + SpecialType returnType = (name2.EndsWith("IndexOf", StringComparison.Ordinal)) + ? SpecialType.System_Int32 + : SpecialType.System_Boolean; - SpecialType returnType = (name2.EndsWith("IndexOf", StringComparison.Ordinal)) - ? SpecialType.System_Int32 - : SpecialType.System_Boolean; + if (!methodSymbol.IsReturnType(returnType)) + return; - if (!methodSymbol.IsReturnType(returnType)) - return; + if (!methodSymbol.HasSingleParameter(SpecialType.System_String)) + return; - if (!methodSymbol.HasSingleParameter(SpecialType.System_String)) - return; + if (!isStringLiteral + && !CheckSymbol(invocationInfo3, semanticModel, cancellationToken)) + { + return; + } - if (!isStringLiteral - && !CheckSymbol(invocationInfo3, semanticModel, cancellationToken)) - { - return; + ReportDiagnostic(context, invocationInfo2); } - ReportDiagnostic(context, invocationInfo2); - } - - private static void Analyze( - SyntaxNodeAnalysisContext context, - in SimpleMemberInvocationExpressionInfo invocationInfo, - ArgumentSyntax argument) - { - if (argument.Parent is not ArgumentListSyntax argumentList) - return; + private static void Analyze( + SyntaxNodeAnalysisContext context, + in SimpleMemberInvocationExpressionInfo invocationInfo, + ArgumentSyntax argument) + { + if (argument.Parent is not ArgumentListSyntax argumentList) + return; - SeparatedSyntaxList arguments = argumentList.Arguments; + SeparatedSyntaxList arguments = argumentList.Arguments; - if (arguments.Count != 2) - return; + if (arguments.Count != 2) + return; - SimpleMemberInvocationExpressionInfo equalsInvocation = SyntaxInfo.SimpleMemberInvocationExpressionInfo(argumentList.Parent); + SimpleMemberInvocationExpressionInfo equalsInvocation = SyntaxInfo.SimpleMemberInvocationExpressionInfo(argumentList.Parent); - if (!equalsInvocation.Success) - return; + if (!equalsInvocation.Success) + return; - if (equalsInvocation.NameText != "Equals") - return; + if (equalsInvocation.NameText != "Equals") + return; - if (!IsFixable(context, invocationInfo, argument, arguments)) - return; + if (!IsFixable(context, invocationInfo, argument, arguments)) + return; - IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(equalsInvocation.InvocationExpression, context.CancellationToken); + IMethodSymbol methodSymbol = context.SemanticModel.GetMethodSymbol(equalsInvocation.InvocationExpression, context.CancellationToken); - if (!SymbolUtility.IsPublicStaticNonGeneric(methodSymbol, "Equals")) - return; + if (!SymbolUtility.IsPublicStaticNonGeneric(methodSymbol, "Equals")) + return; - if (!methodSymbol.IsContainingType(SpecialType.System_String)) - return; + if (!methodSymbol.IsContainingType(SpecialType.System_String)) + return; - if (!methodSymbol.IsReturnType(SpecialType.System_Boolean)) - return; + if (!methodSymbol.IsReturnType(SpecialType.System_Boolean)) + return; - if (!methodSymbol.HasTwoParameters(SpecialType.System_String, SpecialType.System_String)) - return; + if (!methodSymbol.HasTwoParameters(SpecialType.System_String, SpecialType.System_String)) + return; - ReportDiagnostic(context, equalsInvocation); - } + ReportDiagnostic(context, equalsInvocation); + } - private static bool IsFixable( - SyntaxNodeAnalysisContext context, - in SimpleMemberInvocationExpressionInfo invocationInfo, - ArgumentSyntax argument, - SeparatedSyntaxList arguments) - { - if (object.ReferenceEquals(argument, arguments[0])) + private static bool IsFixable( + SyntaxNodeAnalysisContext context, + in SimpleMemberInvocationExpressionInfo invocationInfo, + ArgumentSyntax argument, + SeparatedSyntaxList arguments) { - ExpressionSyntax expression = arguments[1].Expression?.WalkDownParentheses(); - - if (expression != null) + if (object.ReferenceEquals(argument, arguments[0])) { - SyntaxKind kind = expression.Kind(); + ExpressionSyntax expression = arguments[1].Expression?.WalkDownParentheses(); - if (kind == SyntaxKind.InvocationExpression) + if (expression is not null) { - return TryCreateCaseChangingInvocation(expression, out SimpleMemberInvocationExpressionInfo invocationInfo2) - && invocationInfo.NameText == invocationInfo2.NameText - && CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken) - && CheckSymbol(invocationInfo2, context.SemanticModel, context.CancellationToken); - } - else if (kind == SyntaxKind.StringLiteralExpression) - { - return CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken); + SyntaxKind kind = expression.Kind(); + + if (kind == SyntaxKind.InvocationExpression) + { + return TryCreateCaseChangingInvocation(expression, out SimpleMemberInvocationExpressionInfo invocationInfo2) + && invocationInfo.NameText == invocationInfo2.NameText + && CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken) + && CheckSymbol(invocationInfo2, context.SemanticModel, context.CancellationToken); + } + else if (kind == SyntaxKind.StringLiteralExpression) + { + return CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken); + } } } - } - else - { - return arguments[0].Expression?.WalkDownParentheses().Kind() == SyntaxKind.StringLiteralExpression - && CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken); - } + else + { + return arguments[0].Expression?.WalkDownParentheses().Kind() == SyntaxKind.StringLiteralExpression + && CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken); + } - return false; - } + return false; + } - private static void Analyze( - SyntaxNodeAnalysisContext context, - in SimpleMemberInvocationExpressionInfo invocationInfo, - ExpressionSyntax leftOrRight, - BinaryExpressionSyntax binaryExpression) - { - if (object.ReferenceEquals(leftOrRight, binaryExpression.Left)) + private static void Analyze( + SyntaxNodeAnalysisContext context, + in SimpleMemberInvocationExpressionInfo invocationInfo, + ExpressionSyntax leftOrRight, + BinaryExpressionSyntax binaryExpression) { - ExpressionSyntax right = binaryExpression.Right?.WalkDownParentheses(); - - if (right != null) + if (object.ReferenceEquals(leftOrRight, binaryExpression.Left)) { - SyntaxKind kind = right.Kind(); + ExpressionSyntax right = binaryExpression.Right?.WalkDownParentheses(); - if (kind == SyntaxKind.InvocationExpression) + if (right is not null) { - if (TryCreateCaseChangingInvocation(right, out SimpleMemberInvocationExpressionInfo invocationInfo2) - && invocationInfo.NameText == invocationInfo2.NameText - && CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken) - && CheckSymbol(invocationInfo2, context.SemanticModel, context.CancellationToken)) + SyntaxKind kind = right.Kind(); + + if (kind == SyntaxKind.InvocationExpression) { - ReportDiagnostic(context, binaryExpression); + if (TryCreateCaseChangingInvocation(right, out SimpleMemberInvocationExpressionInfo invocationInfo2) + && invocationInfo.NameText == invocationInfo2.NameText + && CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken) + && CheckSymbol(invocationInfo2, context.SemanticModel, context.CancellationToken)) + { + ReportDiagnostic(context, binaryExpression); + } } - } - else if (kind == SyntaxKind.StringLiteralExpression) - { - if (CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken)) + else if (kind == SyntaxKind.StringLiteralExpression) { - ReportDiagnostic(context, binaryExpression); + if (CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken)) + { + ReportDiagnostic(context, binaryExpression); + } } } } + else if (binaryExpression.Left?.WalkDownParentheses().Kind() == SyntaxKind.StringLiteralExpression + && CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken)) + { + ReportDiagnostic(context, binaryExpression); + } } - else if (binaryExpression.Left?.WalkDownParentheses().Kind() == SyntaxKind.StringLiteralExpression - && CheckSymbol(invocationInfo, context.SemanticModel, context.CancellationToken)) + + private static bool TryCreateCaseChangingInvocation(ExpressionSyntax expression, out SimpleMemberInvocationExpressionInfo invocationInfo) { - ReportDiagnostic(context, binaryExpression); - } - } + invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(expression); - private static bool TryCreateCaseChangingInvocation(ExpressionSyntax expression, out SimpleMemberInvocationExpressionInfo invocationInfo) - { - invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(expression); + if (invocationInfo.Success + && !invocationInfo.Arguments.Any()) + { + string name = invocationInfo.NameText; - if (invocationInfo.Success - && !invocationInfo.Arguments.Any()) - { - string name = invocationInfo.NameText; + return name == "ToLower" + || name == "ToLowerInvariant" + || name == "ToUpper" + || name == "ToUpperInvariant"; + } - return name == "ToLower" - || name == "ToLowerInvariant" - || name == "ToUpper" - || name == "ToUpperInvariant"; + invocationInfo = default; + return false; } - invocationInfo = default; - return false; - } - - private static bool CheckSymbol( - in SimpleMemberInvocationExpressionInfo invocationInfo, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationInfo.InvocationExpression, cancellationToken); + private static bool CheckSymbol( + in SimpleMemberInvocationExpressionInfo invocationInfo, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationInfo.InvocationExpression, cancellationToken); - return SymbolUtility.IsPublicInstanceNonGeneric(methodSymbol) - && methodSymbol.IsContainingType(SpecialType.System_String) - && methodSymbol.IsReturnType(SpecialType.System_String) - && !methodSymbol.Parameters.Any(); - } + return SymbolUtility.IsPublicInstanceNonGeneric(methodSymbol) + && methodSymbol.IsContainingType(SpecialType.System_String) + && methodSymbol.IsReturnType(SpecialType.System_String) + && !methodSymbol.Parameters.Any(); + } - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) - { - ReportDiagnostic(context, invocationInfo.InvocationExpression); - } + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, in SimpleMemberInvocationExpressionInfo invocationInfo) + { + ReportDiagnostic(context, invocationInfo.InvocationExpression); + } - private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseStringComparison, node); + private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, SyntaxNode node) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseStringComparison, node); + } } } diff --git a/src/Analyzers/CSharp/Analysis/ValidateArgumentsCorrectlyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ValidateArgumentsCorrectlyAnalyzer.cs index 0bedd75a3d..db479c4c4d 100644 --- a/src/Analyzers/CSharp/Analysis/ValidateArgumentsCorrectlyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ValidateArgumentsCorrectlyAnalyzer.cs @@ -8,103 +8,104 @@ using Microsoft.CodeAnalysis.Text; using Roslynator.CSharp.SyntaxWalkers; -namespace Roslynator.CSharp.Analysis; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class ValidateArgumentsCorrectlyAnalyzer : BaseDiagnosticAnalyzer +namespace Roslynator.CSharp.Analysis { - private static ImmutableArray _supportedDiagnostics; - - public override ImmutableArray SupportedDiagnostics + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class ValidateArgumentsCorrectlyAnalyzer : BaseDiagnosticAnalyzer { - get + private static ImmutableArray _supportedDiagnostics; + + public override ImmutableArray SupportedDiagnostics { - if (_supportedDiagnostics.IsDefault) - Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.ValidateArgumentsCorrectly); + get + { + if (_supportedDiagnostics.IsDefault) + Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.ValidateArgumentsCorrectly); - return _supportedDiagnostics; + return _supportedDiagnostics; + } } - } - public override void Initialize(AnalysisContext context) - { - base.Initialize(context); + public override void Initialize(AnalysisContext context) + { + base.Initialize(context); - context.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); - } + context.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); + } - private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) - { - var methodDeclaration = (MethodDeclarationSyntax)context.Node; + private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) + { + var methodDeclaration = (MethodDeclarationSyntax)context.Node; - BlockSyntax body = methodDeclaration.Body; + BlockSyntax body = methodDeclaration.Body; - if (body == null) - return; + if (body is null) + return; - ParameterListSyntax parameterList = methodDeclaration.ParameterList; + ParameterListSyntax parameterList = methodDeclaration.ParameterList; - if (parameterList == null) - return; + if (parameterList is null) + return; - if (!parameterList.Parameters.Any()) - return; + if (!parameterList.Parameters.Any()) + return; - SyntaxList statements = body.Statements; + SyntaxList statements = body.Statements; - int statementCount = statements.Count; + int statementCount = statements.Count; - int index = -1; - for (int i = 0; i < statementCount; i++) - { - if (IsConditionWithThrow(statements[i]) - || ArgumentNullCheckAnalysis.IsArgumentNullExceptionThrowIfNullCheck(statements[i], context.SemanticModel, context.CancellationToken)) + int index = -1; + for (int i = 0; i < statementCount; i++) { - index++; + if (IsConditionWithThrow(statements[i]) + || ArgumentNullCheckAnalysis.IsArgumentNullExceptionThrowIfNullCheck(statements[i], context.SemanticModel, context.CancellationToken)) + { + index++; + } + else + { + break; + } } - else - { - break; - } - } - if (index == -1) - return; + if (index == -1) + return; - if (index == statementCount - 1) - return; + if (index == statementCount - 1) + return; - TextSpan span = TextSpan.FromBounds(statements[index + 1].SpanStart, statements.Last().Span.End); + TextSpan span = TextSpan.FromBounds(statements[index + 1].SpanStart, statements.Last().Span.End); - if (body.ContainsUnbalancedIfElseDirectives(span)) - return; + if (body.ContainsUnbalancedIfElseDirectives(span)) + return; - context.CancellationToken.ThrowIfCancellationRequested(); + context.CancellationToken.ThrowIfCancellationRequested(); - ContainsYieldWalker walker = ContainsYieldWalker.GetInstance(); + ContainsYieldWalker walker = ContainsYieldWalker.GetInstance(); - walker.VisitBlock(body); + walker.VisitBlock(body); - YieldStatementSyntax yieldStatement = walker.YieldStatement; + YieldStatementSyntax yieldStatement = walker.YieldStatement; - ContainsYieldWalker.Free(walker); + ContainsYieldWalker.Free(walker); - if (yieldStatement == null) - return; + if (yieldStatement is null) + return; - if (yieldStatement.SpanStart < statements[index].Span.End) - return; + if (yieldStatement.SpanStart < statements[index].Span.End) + return; - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.ValidateArgumentsCorrectly, - Location.Create(body.SyntaxTree, new TextSpan(statements[index + 1].SpanStart, 0))); - } + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.ValidateArgumentsCorrectly, + Location.Create(body.SyntaxTree, new TextSpan(statements[index + 1].SpanStart, 0))); + } - private static bool IsConditionWithThrow(StatementSyntax statement) - { - return statement is IfStatementSyntax ifStatement - && ifStatement.IsSimpleIf() - && ifStatement.SingleNonBlockStatementOrDefault().IsKind(SyntaxKind.ThrowStatement); + private static bool IsConditionWithThrow(StatementSyntax statement) + { + return statement is IfStatementSyntax ifStatement + && ifStatement.IsSimpleIf() + && ifStatement.SingleNonBlockStatementOrDefault().IsKind(SyntaxKind.ThrowStatement); + } } } diff --git a/src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs b/src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs index 6f7064639b..d16bec9110 100644 --- a/src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs +++ b/src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs @@ -7,122 +7,123 @@ using Microsoft.CodeAnalysis.Host; using Roslynator.CSharp; -namespace Roslynator.CSharp; - -[Export(typeof(ILanguageService))] -[ExportMetadata("Language", LanguageNames.CSharp)] -[ExportMetadata("ServiceType", "Roslynator.ISyntaxFactsService")] -internal sealed class CSharpSyntaxFactsService : ISyntaxFactsService +namespace Roslynator.CSharp { - public static CSharpSyntaxFactsService Instance { get; } = new(); - - public string SingleLineCommentStart => "//"; - - public bool IsEndOfLineTrivia(SyntaxTrivia trivia) - { - return trivia.IsKind(SyntaxKind.EndOfLineTrivia); - } - - public bool IsComment(SyntaxTrivia trivia) + [Export(typeof(ILanguageService))] + [ExportMetadata("Language", LanguageNames.CSharp)] + [ExportMetadata("ServiceType", "Roslynator.ISyntaxFactsService")] + internal sealed class CSharpSyntaxFactsService : ISyntaxFactsService { - return trivia.IsKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia); - } + public static CSharpSyntaxFactsService Instance { get; } = new(); - public bool IsSingleLineComment(SyntaxTrivia trivia) - { - return trivia.IsKind(SyntaxKind.SingleLineCommentTrivia); - } + public string SingleLineCommentStart => "//"; - public bool IsWhitespaceTrivia(SyntaxTrivia trivia) - { - return trivia.IsKind(SyntaxKind.WhitespaceTrivia); - } + public bool IsEndOfLineTrivia(SyntaxTrivia trivia) + { + return trivia.IsKind(SyntaxKind.EndOfLineTrivia); + } - public SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0) - { - return SyntaxFactory.ParseLeadingTrivia(text, offset); - } + public bool IsComment(SyntaxTrivia trivia) + { + return trivia.IsKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia); + } - public SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0) - { - return SyntaxFactory.ParseTrailingTrivia(text, offset); - } + public bool IsSingleLineComment(SyntaxTrivia trivia) + { + return trivia.IsKind(SyntaxKind.SingleLineCommentTrivia); + } - public bool BeginsWithAutoGeneratedComment(SyntaxNode root) - { - return GeneratedCodeUtility.BeginsWithAutoGeneratedComment( - root, - f => f.IsKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia)); - } + public bool IsWhitespaceTrivia(SyntaxTrivia trivia) + { + return trivia.IsKind(SyntaxKind.WhitespaceTrivia); + } - public bool AreEquivalent(SyntaxTree oldTree, SyntaxTree newTree) - { - return SyntaxFactory.AreEquivalent(oldTree, newTree, topLevel: false); - } + public SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0) + { + return SyntaxFactory.ParseLeadingTrivia(text, offset); + } - public SyntaxNode GetSymbolDeclaration(SyntaxToken identifier) - { - SyntaxNode parent = identifier.Parent; + public SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0) + { + return SyntaxFactory.ParseTrailingTrivia(text, offset); + } - if (!identifier.IsKind(SyntaxKind.IdentifierToken)) - return null; + public bool BeginsWithAutoGeneratedComment(SyntaxNode root) + { + return GeneratedCodeUtility.BeginsWithAutoGeneratedComment( + root, + f => f.IsKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia)); + } - if (parent == null) - return null; + public bool AreEquivalent(SyntaxTree oldTree, SyntaxTree newTree) + { + return SyntaxFactory.AreEquivalent(oldTree, newTree, topLevel: false); + } - switch (parent.Kind()) + public SyntaxNode GetSymbolDeclaration(SyntaxToken identifier) { - case SyntaxKind.TupleElement: - case SyntaxKind.LocalFunctionStatement: - case SyntaxKind.VariableDeclarator: - case SyntaxKind.SingleVariableDesignation: - case SyntaxKind.CatchDeclaration: - case SyntaxKind.TypeParameter: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.StructDeclaration: - case SyntaxKind.RecordStructDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.RecordDeclaration: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.DelegateDeclaration: - case SyntaxKind.EnumMemberDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.EventDeclaration: - case SyntaxKind.Parameter: - case SyntaxKind.ForEachStatement: - { - return parent; - } - case SyntaxKind.IdentifierName: - { - parent = parent.Parent; - - if (parent.IsKind(SyntaxKind.NameEquals)) + SyntaxNode parent = identifier.Parent; + + if (!identifier.IsKind(SyntaxKind.IdentifierToken)) + return null; + + if (parent is null) + return null; + + switch (parent.Kind()) + { + case SyntaxKind.TupleElement: + case SyntaxKind.LocalFunctionStatement: + case SyntaxKind.VariableDeclarator: + case SyntaxKind.SingleVariableDesignation: + case SyntaxKind.CatchDeclaration: + case SyntaxKind.TypeParameter: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.RecordStructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.DelegateDeclaration: + case SyntaxKind.EnumMemberDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.Parameter: + case SyntaxKind.ForEachStatement: + { + return parent; + } + case SyntaxKind.IdentifierName: { parent = parent.Parent; - if (parent.IsKind( - SyntaxKind.UsingDirective, - SyntaxKind.AnonymousObjectMemberDeclarator)) + if (parent.IsKind(SyntaxKind.NameEquals)) { - return parent; + parent = parent.Parent; + + if (parent.IsKind( + SyntaxKind.UsingDirective, + SyntaxKind.AnonymousObjectMemberDeclarator)) + { + return parent; + } + + SyntaxDebug.Fail(parent); + return null; } - SyntaxDebug.Fail(parent); - return null; + return parent; } + } - return parent; - } + SyntaxDebug.Fail(parent); + return null; } - SyntaxDebug.Fail(parent); - return null; - } - - public bool IsValidIdentifier(string name) - { - return SyntaxFacts.IsValidIdentifier(name); + public bool IsValidIdentifier(string name) + { + return SyntaxFacts.IsValidIdentifier(name); + } } } diff --git a/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceExtensions.cs b/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceExtensions.cs index fd810278c8..ea0bb0a3a4 100644 --- a/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceExtensions.cs +++ b/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceExtensions.cs @@ -12,524 +12,525 @@ using Roslynator.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Roslynator.CSharp; - -/// -/// A set of extension methods for the workspace layer. -/// -public static class WorkspaceExtensions +namespace Roslynator.CSharp { - internal static bool SupportsLanguageFeature(this Document document, CSharpLanguageFeature feature) - { - switch (feature) - { - case CSharpLanguageFeature.Unknown: - return false; - case CSharpLanguageFeature.NameOf: - return SupportsLanguageVersion(document, LanguageVersion.CSharp6); - case CSharpLanguageFeature.AsyncMain: - case CSharpLanguageFeature.DefaultLiteral: - case CSharpLanguageFeature.InferredTupleElementNames: - case CSharpLanguageFeature.PatternMatchingWithGenerics: - return SupportsLanguageVersion(document, LanguageVersion.CSharp7_1); - case CSharpLanguageFeature.NullCoalescingAssignmentOperator: - return SupportsLanguageVersion(document, LanguageVersion.CSharp8); - case CSharpLanguageFeature.NotPattern: - return SupportsLanguageVersion(document, LanguageVersion.CSharp9); - } - - throw new ArgumentException($"Unknown enum value '{feature}'.", nameof(feature)); - } - - internal static bool SupportsLanguageVersion(this Document document, LanguageVersion languageVersion) - { - return ((CSharpParseOptions)document.Project.ParseOptions).LanguageVersion >= languageVersion; - } - - internal static DefaultSyntaxOptions GetDefaultSyntaxOptions(this Document document, DefaultSyntaxOptions options = DefaultSyntaxOptions.None) - { - return (document.SupportsLanguageFeature(CSharpLanguageFeature.DefaultLiteral)) - ? options | DefaultSyntaxOptions.AllowDefaultLiteral - : options; - } - - internal static Task RemoveNodeAsync( - this Document document, - SyntaxNode node, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); - - if (node == null) - throw new ArgumentNullException(nameof(node)); - - return document.RemoveNodeAsync(node, SyntaxRefactorings.GetRemoveOptions(node), cancellationToken); - } - /// - /// Create a new document with the specified member declaration removed. + /// A set of extension methods for the workspace layer. /// - /// - /// - /// - internal static Task RemoveMemberAsync( - this Document document, - MemberDeclarationSyntax member, - CancellationToken cancellationToken = default) + public static class WorkspaceExtensions { - if (document == null) - throw new ArgumentNullException(nameof(document)); + internal static bool SupportsLanguageFeature(this Document document, CSharpLanguageFeature feature) + { + switch (feature) + { + case CSharpLanguageFeature.Unknown: + return false; + case CSharpLanguageFeature.NameOf: + return SupportsLanguageVersion(document, LanguageVersion.CSharp6); + case CSharpLanguageFeature.AsyncMain: + case CSharpLanguageFeature.DefaultLiteral: + case CSharpLanguageFeature.InferredTupleElementNames: + case CSharpLanguageFeature.PatternMatchingWithGenerics: + return SupportsLanguageVersion(document, LanguageVersion.CSharp7_1); + case CSharpLanguageFeature.NullCoalescingAssignmentOperator: + return SupportsLanguageVersion(document, LanguageVersion.CSharp8); + case CSharpLanguageFeature.NotPattern: + return SupportsLanguageVersion(document, LanguageVersion.CSharp9); + } - if (member == null) - throw new ArgumentNullException(nameof(member)); + throw new ArgumentException($"Unknown enum value '{feature}'.", nameof(feature)); + } - SyntaxNode parent = member.Parent; + internal static bool SupportsLanguageVersion(this Document document, LanguageVersion languageVersion) + { + return ((CSharpParseOptions)document.Project.ParseOptions).LanguageVersion >= languageVersion; + } - switch (parent?.Kind()) + internal static DefaultSyntaxOptions GetDefaultSyntaxOptions(this Document document, DefaultSyntaxOptions options = DefaultSyntaxOptions.None) { - case SyntaxKind.CompilationUnit: - { - var compilationUnit = (CompilationUnitSyntax)parent; + return (document.SupportsLanguageFeature(CSharpLanguageFeature.DefaultLiteral)) + ? options | DefaultSyntaxOptions.AllowDefaultLiteral + : options; + } - return document.ReplaceNodeAsync(compilationUnit, SyntaxRefactorings.RemoveMember(compilationUnit, member), cancellationToken); - } - case SyntaxKind.NamespaceDeclaration: - case SyntaxKind.FileScopedNamespaceDeclaration: - { - var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)parent; + internal static Task RemoveNodeAsync( + this Document document, + SyntaxNode node, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - return document.ReplaceNodeAsync(namespaceDeclaration, SyntaxRefactorings.RemoveMember(namespaceDeclaration, member), cancellationToken); - } - case SyntaxKind.ClassDeclaration: - { - var classDeclaration = (ClassDeclarationSyntax)parent; + if (node is null) + throw new ArgumentNullException(nameof(node)); - return document.ReplaceNodeAsync(classDeclaration, SyntaxRefactorings.RemoveMember(classDeclaration, member), cancellationToken); - } - case SyntaxKind.StructDeclaration: - { - var structDeclaration = (StructDeclarationSyntax)parent; + return document.RemoveNodeAsync(node, SyntaxRefactorings.GetRemoveOptions(node), cancellationToken); + } - return document.ReplaceNodeAsync(structDeclaration, SyntaxRefactorings.RemoveMember(structDeclaration, member), cancellationToken); - } - case SyntaxKind.InterfaceDeclaration: - { - var interfaceDeclaration = (InterfaceDeclarationSyntax)parent; + /// + /// Create a new document with the specified member declaration removed. + /// + /// + /// + /// + internal static Task RemoveMemberAsync( + this Document document, + MemberDeclarationSyntax member, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - return document.ReplaceNodeAsync(interfaceDeclaration, SyntaxRefactorings.RemoveMember(interfaceDeclaration, member), cancellationToken); - } - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - { - var recordDeclaration = (RecordDeclarationSyntax)parent; + if (member is null) + throw new ArgumentNullException(nameof(member)); - return document.ReplaceNodeAsync(recordDeclaration, SyntaxRefactorings.RemoveMember(recordDeclaration, member), cancellationToken); - } - default: - { - SyntaxDebug.Assert(parent == null, parent); + SyntaxNode parent = member.Parent; - return document.RemoveNodeAsync(member, SyntaxRefactorings.DefaultRemoveOptions, cancellationToken); - } + switch (parent?.Kind()) + { + case SyntaxKind.CompilationUnit: + { + var compilationUnit = (CompilationUnitSyntax)parent; + + return document.ReplaceNodeAsync(compilationUnit, SyntaxRefactorings.RemoveMember(compilationUnit, member), cancellationToken); + } + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.FileScopedNamespaceDeclaration: + { + var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)parent; + + return document.ReplaceNodeAsync(namespaceDeclaration, SyntaxRefactorings.RemoveMember(namespaceDeclaration, member), cancellationToken); + } + case SyntaxKind.ClassDeclaration: + { + var classDeclaration = (ClassDeclarationSyntax)parent; + + return document.ReplaceNodeAsync(classDeclaration, SyntaxRefactorings.RemoveMember(classDeclaration, member), cancellationToken); + } + case SyntaxKind.StructDeclaration: + { + var structDeclaration = (StructDeclarationSyntax)parent; + + return document.ReplaceNodeAsync(structDeclaration, SyntaxRefactorings.RemoveMember(structDeclaration, member), cancellationToken); + } + case SyntaxKind.InterfaceDeclaration: + { + var interfaceDeclaration = (InterfaceDeclarationSyntax)parent; + + return document.ReplaceNodeAsync(interfaceDeclaration, SyntaxRefactorings.RemoveMember(interfaceDeclaration, member), cancellationToken); + } + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + { + var recordDeclaration = (RecordDeclarationSyntax)parent; + + return document.ReplaceNodeAsync(recordDeclaration, SyntaxRefactorings.RemoveMember(recordDeclaration, member), cancellationToken); + } + default: + { + SyntaxDebug.Assert(parent is null, parent); + + return document.RemoveNodeAsync(member, SyntaxRefactorings.DefaultRemoveOptions, cancellationToken); + } + } } - } - internal static Task RemoveStatementAsync( - this Document document, - StatementSyntax statement, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); - - if (statement == null) - throw new ArgumentNullException(nameof(statement)); + internal static Task RemoveStatementAsync( + this Document document, + StatementSyntax statement, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - return document.RemoveNodeAsync(statement, cancellationToken); - } + if (statement is null) + throw new ArgumentNullException(nameof(statement)); - /// - /// Creates a new document with comments of the specified kind removed. - /// - /// - /// - /// - public static async Task RemoveCommentsAsync( - this Document document, - CommentFilter comments, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.RemoveNodeAsync(statement, cancellationToken); + } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + /// + /// Creates a new document with comments of the specified kind removed. + /// + /// + /// + /// + public static async Task RemoveCommentsAsync( + this Document document, + CommentFilter comments, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode newRoot = SyntaxRefactorings.RemoveComments(root, comments) - .WithFormatterAnnotation(); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = SyntaxRefactorings.RemoveComments(root, comments) + .WithFormatterAnnotation(); - /// - /// Creates a new document with comments of the specified kind removed. - /// - /// - /// - /// - /// - public static async Task RemoveCommentsAsync( - this Document document, - TextSpan span, - CommentFilter comments, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + /// + /// Creates a new document with comments of the specified kind removed. + /// + /// + /// + /// + /// + public static async Task RemoveCommentsAsync( + this Document document, + TextSpan span, + CommentFilter comments, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode newRoot = SyntaxRefactorings.RemoveComments(root, span, comments) - .WithFormatterAnnotation(); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = SyntaxRefactorings.RemoveComments(root, span, comments) + .WithFormatterAnnotation(); - /// - /// Creates a new document with trivia inside the specified span removed. - /// - /// - /// - /// - public static async Task RemoveTriviaAsync( - this Document document, - TextSpan span, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + /// + /// Creates a new document with trivia inside the specified span removed. + /// + /// + /// + /// + public static async Task RemoveTriviaAsync( + this Document document, + TextSpan span, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode newRoot = SyntaxRefactorings.RemoveTrivia(root, span); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = SyntaxRefactorings.RemoveTrivia(root, span); - /// - /// Creates a new document with preprocessor directives of the specified kind removed. - /// - /// - /// - /// - public static async Task RemovePreprocessorDirectivesAsync( - this Document document, - PreprocessorDirectiveFilter directiveFilter, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + /// + /// Creates a new document with preprocessor directives of the specified kind removed. + /// + /// + /// + /// + public static async Task RemovePreprocessorDirectivesAsync( + this Document document, + PreprocessorDirectiveFilter directiveFilter, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - SourceText newSourceText = RemovePreprocessorDirectives(sourceText, root.DescendantPreprocessorDirectives(), directiveFilter); + SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); - return document.WithText(newSourceText); - } + SourceText newSourceText = RemovePreprocessorDirectives(sourceText, root.DescendantPreprocessorDirectives(), directiveFilter); - /// - /// Creates a new document with preprocessor directives of the specified kind removed. - /// - /// - /// - /// - /// - public static async Task RemovePreprocessorDirectivesAsync( - this Document document, - TextSpan span, - PreprocessorDirectiveFilter directiveFilter, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithText(newSourceText); + } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + /// + /// Creates a new document with preprocessor directives of the specified kind removed. + /// + /// + /// + /// + /// + public static async Task RemovePreprocessorDirectivesAsync( + this Document document, + TextSpan span, + PreprocessorDirectiveFilter directiveFilter, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - SourceText newSourceText = RemovePreprocessorDirectives(sourceText, root.DescendantPreprocessorDirectives(span), directiveFilter); + SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); - return document.WithText(newSourceText); - } + SourceText newSourceText = RemovePreprocessorDirectives(sourceText, root.DescendantPreprocessorDirectives(span), directiveFilter); - internal static async Task RemovePreprocessorDirectivesAsync( - this Document document, - IEnumerable directives, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithText(newSourceText); + } - if (directives == null) - throw new ArgumentNullException(nameof(directives)); + internal static async Task RemovePreprocessorDirectivesAsync( + this Document document, + IEnumerable directives, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + if (directives is null) + throw new ArgumentNullException(nameof(directives)); - SourceText newSourceText = sourceText.WithChanges(GetTextChanges()); + SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); - return document.WithText(newSourceText); + SourceText newSourceText = sourceText.WithChanges(GetTextChanges()); - IEnumerable GetTextChanges() - { - TextLineCollection lines = sourceText.Lines; + return document.WithText(newSourceText); - foreach (DirectiveTriviaSyntax directive in directives) + IEnumerable GetTextChanges() { - int startLine = directive.GetSpanStartLine(); + TextLineCollection lines = sourceText.Lines; + + foreach (DirectiveTriviaSyntax directive in directives) + { + int startLine = directive.GetSpanStartLine(); - yield return new TextChange(lines[startLine].SpanIncludingLineBreak, ""); + yield return new TextChange(lines[startLine].SpanIncludingLineBreak, ""); + } } } - } - - private static SourceText RemovePreprocessorDirectives( - SourceText sourceText, - IEnumerable directives, - PreprocessorDirectiveFilter directiveFilter) - { - return sourceText.WithChanges(GetTextChanges()); - IEnumerable GetTextChanges() + private static SourceText RemovePreprocessorDirectives( + SourceText sourceText, + IEnumerable directives, + PreprocessorDirectiveFilter directiveFilter) { - TextLineCollection lines = sourceText.Lines; + return sourceText.WithChanges(GetTextChanges()); - foreach (DirectiveTriviaSyntax directive in directives) + IEnumerable GetTextChanges() { - if (ShouldRemoveDirective(directive)) + TextLineCollection lines = sourceText.Lines; + + foreach (DirectiveTriviaSyntax directive in directives) { - int startLine = directive.GetSpanStartLine(); + if (ShouldRemoveDirective(directive)) + { + int startLine = directive.GetSpanStartLine(); - yield return new TextChange(lines[startLine].SpanIncludingLineBreak, ""); + yield return new TextChange(lines[startLine].SpanIncludingLineBreak, ""); + } } } - } - bool ShouldRemoveDirective(DirectiveTriviaSyntax directive) - { - switch (directive.Kind()) + bool ShouldRemoveDirective(DirectiveTriviaSyntax directive) { - case SyntaxKind.IfDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.If) != 0; - case SyntaxKind.ElifDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Elif) != 0; - case SyntaxKind.ElseDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Else) != 0; - case SyntaxKind.EndIfDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.EndIf) != 0; - case SyntaxKind.RegionDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Region) != 0; - case SyntaxKind.EndRegionDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.EndRegion) != 0; - case SyntaxKind.DefineDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Define) != 0; - case SyntaxKind.UndefDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Undef) != 0; - case SyntaxKind.ErrorDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Error) != 0; - case SyntaxKind.WarningDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Warning) != 0; - case SyntaxKind.LineDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Line) != 0; - case SyntaxKind.PragmaWarningDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.PragmaWarning) != 0; - case SyntaxKind.PragmaChecksumDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.PragmaChecksum) != 0; - case SyntaxKind.ReferenceDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Reference) != 0; - case SyntaxKind.BadDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Bad) != 0; - case SyntaxKind.ShebangDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Shebang) != 0; - case SyntaxKind.LoadDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Load) != 0; - case SyntaxKind.NullableDirectiveTrivia: - return (directiveFilter & PreprocessorDirectiveFilter.Nullable) != 0; - } + switch (directive.Kind()) + { + case SyntaxKind.IfDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.If) != 0; + case SyntaxKind.ElifDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Elif) != 0; + case SyntaxKind.ElseDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Else) != 0; + case SyntaxKind.EndIfDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.EndIf) != 0; + case SyntaxKind.RegionDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Region) != 0; + case SyntaxKind.EndRegionDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.EndRegion) != 0; + case SyntaxKind.DefineDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Define) != 0; + case SyntaxKind.UndefDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Undef) != 0; + case SyntaxKind.ErrorDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Error) != 0; + case SyntaxKind.WarningDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Warning) != 0; + case SyntaxKind.LineDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Line) != 0; + case SyntaxKind.PragmaWarningDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.PragmaWarning) != 0; + case SyntaxKind.PragmaChecksumDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.PragmaChecksum) != 0; + case SyntaxKind.ReferenceDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Reference) != 0; + case SyntaxKind.BadDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Bad) != 0; + case SyntaxKind.ShebangDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Shebang) != 0; + case SyntaxKind.LoadDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Load) != 0; + case SyntaxKind.NullableDirectiveTrivia: + return (directiveFilter & PreprocessorDirectiveFilter.Nullable) != 0; + } - SyntaxDebug.Fail(directive); - return false; + SyntaxDebug.Fail(directive); + return false; + } } - } - /// - /// Creates a new document with the specified region removed. - /// - /// - /// - /// - public static async Task RemoveRegionAsync( - this Document document, - RegionInfo region, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + /// + /// Creates a new document with the specified region removed. + /// + /// + /// + /// + public static async Task RemoveRegionAsync( + this Document document, + RegionInfo region, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - if (!region.Success) - throw new ArgumentException($"{nameof(RegionInfo)} is not initialized.", nameof(region)); + if (!region.Success) + throw new ArgumentException($"{nameof(RegionInfo)} is not initialized.", nameof(region)); - SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); - int startLine = region.Directive.GetSpanStartLine(); - int endLine = region.EndDirective.GetSpanEndLine(); + int startLine = region.Directive.GetSpanStartLine(); + int endLine = region.EndDirective.GetSpanEndLine(); - TextLineCollection lines = sourceText.Lines; + TextLineCollection lines = sourceText.Lines; - TextSpan span = TextSpan.FromBounds( - lines[startLine].Start, - lines[endLine].EndIncludingLineBreak); + TextSpan span = TextSpan.FromBounds( + lines[startLine].Start, + lines[endLine].EndIncludingLineBreak); - SourceText newSourceText = sourceText.WithChange(span, ""); + SourceText newSourceText = sourceText.WithChange(span, ""); - return document.WithText(newSourceText); - } + return document.WithText(newSourceText); + } - internal static Task RemoveSingleLineDocumentationComment( - this Document document, - DocumentationCommentTriviaSyntax documentationComment, - CancellationToken cancellationToken = default) - { - SyntaxNode node = documentationComment.ParentTrivia.Token.Parent; - SyntaxNode newNode = SyntaxRefactorings.RemoveSingleLineDocumentationComment(node, documentationComment); + internal static Task RemoveSingleLineDocumentationComment( + this Document document, + DocumentationCommentTriviaSyntax documentationComment, + CancellationToken cancellationToken = default) + { + SyntaxNode node = documentationComment.ParentTrivia.Token.Parent; + SyntaxNode newNode = SyntaxRefactorings.RemoveSingleLineDocumentationComment(node, documentationComment); - return document.ReplaceNodeAsync(node, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(node, newNode, cancellationToken); + } - /// - /// Creates a new document with the specified statements replaced with new statements. - /// - /// - /// - /// - /// - public static Task ReplaceStatementsAsync( - this Document document, - StatementListInfo statementsInfo, - IEnumerable newStatements, - CancellationToken cancellationToken = default) - { - return ReplaceStatementsAsync(document, statementsInfo, List(newStatements), cancellationToken); - } + /// + /// Creates a new document with the specified statements replaced with new statements. + /// + /// + /// + /// + /// + public static Task ReplaceStatementsAsync( + this Document document, + StatementListInfo statementsInfo, + IEnumerable newStatements, + CancellationToken cancellationToken = default) + { + return ReplaceStatementsAsync(document, statementsInfo, List(newStatements), cancellationToken); + } - /// - /// Creates a new document with the specified statements replaced with new statements. - /// - /// - /// - /// - /// - public static Task ReplaceStatementsAsync( - this Document document, - StatementListInfo statementsInfo, - SyntaxList newStatements, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + /// + /// Creates a new document with the specified statements replaced with new statements. + /// + /// + /// + /// + /// + public static Task ReplaceStatementsAsync( + this Document document, + StatementListInfo statementsInfo, + SyntaxList newStatements, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - return document.ReplaceNodeAsync(statementsInfo.Parent, statementsInfo.WithStatements(newStatements).Parent, cancellationToken); - } + return document.ReplaceNodeAsync(statementsInfo.Parent, statementsInfo.WithStatements(newStatements).Parent, cancellationToken); + } - internal static Task ReplaceStatementsAsync( - this Document document, - StatementListInfo statementsInfo, - StatementListInfo newStatementsInfo, - CancellationToken cancellationToken = default) - { - return document.ReplaceNodeAsync(statementsInfo.Parent, newStatementsInfo.Parent, cancellationToken); - } + internal static Task ReplaceStatementsAsync( + this Document document, + StatementListInfo statementsInfo, + StatementListInfo newStatementsInfo, + CancellationToken cancellationToken = default) + { + return document.ReplaceNodeAsync(statementsInfo.Parent, newStatementsInfo.Parent, cancellationToken); + } - /// - /// Creates a new document with the specified members replaced with new members. - /// - /// - /// - /// - /// - public static Task ReplaceMembersAsync( - this Document document, - MemberDeclarationListInfo info, - IEnumerable newMembers, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + /// + /// Creates a new document with the specified members replaced with new members. + /// + /// + /// + /// + /// + public static Task ReplaceMembersAsync( + this Document document, + MemberDeclarationListInfo info, + IEnumerable newMembers, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - return document.ReplaceNodeAsync( - info.Parent, - info.WithMembers(newMembers).Parent, - cancellationToken); - } + return document.ReplaceNodeAsync( + info.Parent, + info.WithMembers(newMembers).Parent, + cancellationToken); + } - /// - /// Creates a new document with the specified members replaced with new members. - /// - /// - /// - /// - /// - /// - public static Task ReplaceMembersAsync( - this Document document, - MemberDeclarationListInfo info, - SyntaxList newMembers, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + /// + /// Creates a new document with the specified members replaced with new members. + /// + /// + /// + /// + /// + /// + public static Task ReplaceMembersAsync( + this Document document, + MemberDeclarationListInfo info, + SyntaxList newMembers, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - return document.ReplaceNodeAsync( - info.Parent, - info.WithMembers(newMembers).Parent, - cancellationToken); - } + return document.ReplaceNodeAsync( + info.Parent, + info.WithMembers(newMembers).Parent, + cancellationToken); + } - /// - /// Creates a new document with the specified modifiers replaced with new modifiers. - /// - /// - /// - /// - /// - /// - public static Task ReplaceModifiersAsync( - this Document document, - ModifierListInfo modifiersInfo, - IEnumerable newModifiers, - CancellationToken cancellationToken = default) - { - return ReplaceModifiersAsync(document, modifiersInfo, TokenList(newModifiers), cancellationToken); - } + /// + /// Creates a new document with the specified modifiers replaced with new modifiers. + /// + /// + /// + /// + /// + /// + public static Task ReplaceModifiersAsync( + this Document document, + ModifierListInfo modifiersInfo, + IEnumerable newModifiers, + CancellationToken cancellationToken = default) + { + return ReplaceModifiersAsync(document, modifiersInfo, TokenList(newModifiers), cancellationToken); + } - /// - /// Creates a new document with the specified modifiers replaced with new modifiers. - /// - /// - /// - /// - /// - /// - public static Task ReplaceModifiersAsync( - this Document document, - ModifierListInfo modifiersInfo, - SyntaxTokenList newModifiers, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + /// + /// Creates a new document with the specified modifiers replaced with new modifiers. + /// + /// + /// + /// + /// + /// + public static Task ReplaceModifiersAsync( + this Document document, + ModifierListInfo modifiersInfo, + SyntaxTokenList newModifiers, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - return document.ReplaceNodeAsync(modifiersInfo.Parent, modifiersInfo.WithModifiers(newModifiers).Parent, cancellationToken); + return document.ReplaceNodeAsync(modifiersInfo.Parent, modifiersInfo.WithModifiers(newModifiers).Parent, cancellationToken); + } } } diff --git a/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceSymbolExtensions.cs b/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceSymbolExtensions.cs index 5c0cd6e25e..23edf1c25f 100644 --- a/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceSymbolExtensions.cs +++ b/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceSymbolExtensions.cs @@ -6,162 +6,163 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp; - -public static class WorkspaceSymbolExtensions +namespace Roslynator.CSharp { - /// - /// Creates a new that represents default value of the specified type symbol. - /// - /// - /// - /// - public static ExpressionSyntax GetDefaultValueSyntax( - this ITypeSymbol typeSymbol, - DefaultSyntaxOptions options = DefaultSyntaxOptions.None, - SymbolDisplayFormat format = null) - { - return GetDefaultValueSyntax(typeSymbol, options, default(TypeSyntax), format); - } - - /// - /// Creates a new that represents default value of the specified type symbol. - /// - /// - /// - /// - public static ExpressionSyntax GetDefaultValueSyntax( - this ITypeSymbol typeSymbol, - TypeSyntax type, - DefaultSyntaxOptions options = DefaultSyntaxOptions.None) - { - return GetDefaultValueSyntax(typeSymbol, options, type, default(SymbolDisplayFormat)); - } - - // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table - private static ExpressionSyntax GetDefaultValueSyntax( - this ITypeSymbol typeSymbol, - DefaultSyntaxOptions options = DefaultSyntaxOptions.None, - TypeSyntax type = null, - SymbolDisplayFormat format = null) + public static class WorkspaceSymbolExtensions { - if (typeSymbol == null) - throw new ArgumentNullException(nameof(typeSymbol)); - - if ((options & DefaultSyntaxOptions.UseDefault) != 0) - return CreateDefault(); - - if (typeSymbol.IsReferenceType - || typeSymbol.TypeKind == TypeKind.Pointer - || typeSymbol.IsNullableType()) + /// + /// Creates a new that represents default value of the specified type symbol. + /// + /// + /// + /// + public static ExpressionSyntax GetDefaultValueSyntax( + this ITypeSymbol typeSymbol, + DefaultSyntaxOptions options = DefaultSyntaxOptions.None, + SymbolDisplayFormat format = null) { - return NullLiteralExpression(); + return GetDefaultValueSyntax(typeSymbol, options, default(TypeSyntax), format); } - if (typeSymbol.TypeKind == TypeKind.Enum) + /// + /// Creates a new that represents default value of the specified type symbol. + /// + /// + /// + /// + public static ExpressionSyntax GetDefaultValueSyntax( + this ITypeSymbol typeSymbol, + TypeSyntax type, + DefaultSyntaxOptions options = DefaultSyntaxOptions.None) { - IFieldSymbol fieldSymbol = CSharpUtility.FindEnumDefaultField((INamedTypeSymbol)typeSymbol); - - if (fieldSymbol != null) - return SimpleMemberAccessExpression(GetTypeSyntax(), IdentifierName(fieldSymbol.Name)); - - return CastExpression(GetTypeSyntax(), NumericLiteralExpression(0)).WithSimplifierAnnotation(); + return GetDefaultValueSyntax(typeSymbol, options, type, default(SymbolDisplayFormat)); } - switch (typeSymbol.SpecialType) + // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table + private static ExpressionSyntax GetDefaultValueSyntax( + this ITypeSymbol typeSymbol, + DefaultSyntaxOptions options = DefaultSyntaxOptions.None, + TypeSyntax type = null, + SymbolDisplayFormat format = null) { - case SpecialType.System_Boolean: - return FalseLiteralExpression(); - case SpecialType.System_Char: - return CharacterLiteralExpression('\0'); - case SpecialType.System_SByte: - case SpecialType.System_Byte: - 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_Decimal: - case SpecialType.System_Single: - case SpecialType.System_Double: - return NumericLiteralExpression(0); - } + if (typeSymbol is null) + throw new ArgumentNullException(nameof(typeSymbol)); - return CreateDefault(); + if ((options & DefaultSyntaxOptions.UseDefault) != 0) + return CreateDefault(); - TypeSyntax GetTypeSyntax() - { - return type ?? typeSymbol.ToTypeSyntax(format).WithSimplifierAnnotation(); - } + if (typeSymbol.IsReferenceType + || typeSymbol.TypeKind == TypeKind.Pointer + || typeSymbol.IsNullableType()) + { + return NullLiteralExpression(); + } - ExpressionSyntax CreateDefault() - { - if ((options & DefaultSyntaxOptions.AllowDefaultLiteral) != 0) - return DefaultLiteralExpression(); + if (typeSymbol.TypeKind == TypeKind.Enum) + { + IFieldSymbol fieldSymbol = CSharpUtility.FindEnumDefaultField((INamedTypeSymbol)typeSymbol); - return DefaultExpression(GetTypeSyntax()); - } - } + if (fieldSymbol is not null) + return SimpleMemberAccessExpression(GetTypeSyntax(), IdentifierName(fieldSymbol.Name)); - internal static ExpressionSyntax GetDefaultValueSyntax( - this IParameterSymbol parameterSymbol, - SymbolDisplayFormat format = null) - { - if (parameterSymbol == null) - throw new ArgumentNullException(nameof(parameterSymbol)); + return CastExpression(GetTypeSyntax(), NumericLiteralExpression(0)).WithSimplifierAnnotation(); + } - if (!parameterSymbol.HasExplicitDefaultValue) - throw new ArgumentException("Parameter does not specify default value.", nameof(parameterSymbol)); + switch (typeSymbol.SpecialType) + { + case SpecialType.System_Boolean: + return FalseLiteralExpression(); + case SpecialType.System_Char: + return CharacterLiteralExpression('\0'); + case SpecialType.System_SByte: + case SpecialType.System_Byte: + 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_Decimal: + case SpecialType.System_Single: + case SpecialType.System_Double: + return NumericLiteralExpression(0); + } - object value = parameterSymbol.ExplicitDefaultValue; + return CreateDefault(); - ITypeSymbol typeSymbol = parameterSymbol.Type; + TypeSyntax GetTypeSyntax() + { + return type ?? typeSymbol.ToTypeSyntax(format).WithSimplifierAnnotation(); + } + + ExpressionSyntax CreateDefault() + { + if ((options & DefaultSyntaxOptions.AllowDefaultLiteral) != 0) + return DefaultLiteralExpression(); + + return DefaultExpression(GetTypeSyntax()); + } + } - if (typeSymbol.TypeKind == TypeKind.Enum) + internal static ExpressionSyntax GetDefaultValueSyntax( + this IParameterSymbol parameterSymbol, + SymbolDisplayFormat format = null) { - if (value == null) - return NullLiteralExpression(); + if (parameterSymbol is null) + throw new ArgumentNullException(nameof(parameterSymbol)); + + if (!parameterSymbol.HasExplicitDefaultValue) + throw new ArgumentException("Parameter does not specify default value.", nameof(parameterSymbol)); - IFieldSymbol fieldSymbol = FindFieldWithConstantValue(); + object value = parameterSymbol.ExplicitDefaultValue; - TypeSyntax type = typeSymbol.ToTypeSyntax(format); + ITypeSymbol typeSymbol = parameterSymbol.Type; - if (fieldSymbol != null) + if (typeSymbol.TypeKind == TypeKind.Enum) { - return SimpleMemberAccessExpression(type, IdentifierName(fieldSymbol.Name)); + if (value is null) + return NullLiteralExpression(); + + IFieldSymbol fieldSymbol = FindFieldWithConstantValue(); + + TypeSyntax type = typeSymbol.ToTypeSyntax(format); + + if (fieldSymbol is not null) + { + return SimpleMemberAccessExpression(type, IdentifierName(fieldSymbol.Name)); + } + else + { + return CastExpression(type, LiteralExpression(value)); + } } - else + + if (value is null + && !typeSymbol.IsReferenceTypeOrNullableType()) { - return CastExpression(type, LiteralExpression(value)); + return DefaultExpression(typeSymbol.ToTypeSyntax(format)); } - } - if (value == null - && !typeSymbol.IsReferenceTypeOrNullableType()) - { - return DefaultExpression(typeSymbol.ToTypeSyntax(format)); - } + return LiteralExpression(value); - return LiteralExpression(value); - - IFieldSymbol FindFieldWithConstantValue() - { - foreach (ISymbol symbol in typeSymbol.GetMembers()) + IFieldSymbol FindFieldWithConstantValue() { - if (symbol.Kind == SymbolKind.Field) + foreach (ISymbol symbol in typeSymbol.GetMembers()) { - var fieldSymbol = (IFieldSymbol)symbol; - - if (fieldSymbol.HasConstantValue - && object.Equals(fieldSymbol.ConstantValue, value)) + if (symbol.Kind == SymbolKind.Field) { - return fieldSymbol; + var fieldSymbol = (IFieldSymbol)symbol; + + if (fieldSymbol.HasConstantValue + && object.Equals(fieldSymbol.ConstantValue, value)) + { + return fieldSymbol; + } } } - } - return null; + return null; + } } } } diff --git a/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceSyntaxExtensions.cs b/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceSyntaxExtensions.cs index b4685b40da..6a469d58ad 100644 --- a/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceSyntaxExtensions.cs +++ b/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceSyntaxExtensions.cs @@ -11,163 +11,164 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp; - -/// -/// A set of extension methods for syntax. These methods are dependent on the workspace layer. -/// -public static class WorkspaceSyntaxExtensions +namespace Roslynator.CSharp { - private static readonly SyntaxAnnotation[] _formatterAnnotationArray = new SyntaxAnnotation[] { Formatter.Annotation }; + /// + /// A set of extension methods for syntax. These methods are dependent on the workspace layer. + /// + public static class WorkspaceSyntaxExtensions + { + private static readonly SyntaxAnnotation[] _formatterAnnotationArray = new SyntaxAnnotation[] { Formatter.Annotation }; - private static readonly SyntaxAnnotation[] _simplifierAnnotationArray = new SyntaxAnnotation[] { Simplifier.Annotation }; + private static readonly SyntaxAnnotation[] _simplifierAnnotationArray = new SyntaxAnnotation[] { Simplifier.Annotation }; - private static readonly SyntaxAnnotation[] _renameAnnotationArray = new SyntaxAnnotation[] { RenameAnnotation.Create() }; + private static readonly SyntaxAnnotation[] _renameAnnotationArray = new SyntaxAnnotation[] { RenameAnnotation.Create() }; - private static readonly SyntaxAnnotation[] _navigationAnnotationArray = new SyntaxAnnotation[] { NavigationAnnotation.Annotation }; + private static readonly SyntaxAnnotation[] _navigationAnnotationArray = new SyntaxAnnotation[] { NavigationAnnotation.Annotation }; - private static readonly SyntaxAnnotation[] _formatterAndSimplifierAnnotationArray = new SyntaxAnnotation[] { Formatter.Annotation, Simplifier.Annotation }; + private static readonly SyntaxAnnotation[] _formatterAndSimplifierAnnotationArray = new SyntaxAnnotation[] { Formatter.Annotation, Simplifier.Annotation }; - #region ExpressionSyntax - /// - /// Creates parenthesized expression that is parenthesizing the specified expression. - /// - /// - /// If true, add elastic trivia. - /// If true, attach to the parenthesized expression. - public static ParenthesizedExpressionSyntax Parenthesize( - this ExpressionSyntax expression, - bool includeElasticTrivia = true, - bool simplifiable = true) - { - ParenthesizedExpressionSyntax parenthesizedExpression; - - if (includeElasticTrivia) + #region ExpressionSyntax + /// + /// Creates parenthesized expression that is parenthesizing the specified expression. + /// + /// + /// If true, add elastic trivia. + /// If true, attach to the parenthesized expression. + public static ParenthesizedExpressionSyntax Parenthesize( + this ExpressionSyntax expression, + bool includeElasticTrivia = true, + bool simplifiable = true) { - parenthesizedExpression = ParenthesizedExpression(expression.WithoutTrivia()); + ParenthesizedExpressionSyntax parenthesizedExpression; + + if (includeElasticTrivia) + { + parenthesizedExpression = ParenthesizedExpression(expression.WithoutTrivia()); + } + else + { + parenthesizedExpression = ParenthesizedExpression( + Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), + expression.WithoutTrivia(), + Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); + } + + return parenthesizedExpression + .WithTriviaFrom(expression) + .WithSimplifierAnnotationIf(simplifiable); } - else + + internal static ExpressionSyntax ParenthesizeIf( + this ExpressionSyntax expression, + bool condition, + bool includeElasticTrivia = true, + bool simplifiable = true) { - parenthesizedExpression = ParenthesizedExpression( - Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), - expression.WithoutTrivia(), - Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); + return (condition) ? Parenthesize(expression, includeElasticTrivia, simplifiable) : expression; } + #endregion ExpressionSyntax - return parenthesizedExpression - .WithTriviaFrom(expression) - .WithSimplifierAnnotationIf(simplifiable); - } - - internal static ExpressionSyntax ParenthesizeIf( - this ExpressionSyntax expression, - bool condition, - bool includeElasticTrivia = true, - bool simplifiable = true) - { - return (condition) ? Parenthesize(expression, includeElasticTrivia, simplifiable) : expression; - } - #endregion ExpressionSyntax - - #region SimpleNameSyntax - internal static MemberAccessExpressionSyntax QualifyWithThis(this SimpleNameSyntax simpleName, bool simplifiable = true) - { - return SimpleMemberAccessExpression(ThisExpression(), simpleName).WithSimplifierAnnotationIf(simplifiable); - } - #endregion SimpleNameSyntax - - #region SyntaxNode - /// - /// Creates a new node with the attached. - /// - /// - /// - public static TNode WithFormatterAnnotation(this TNode node) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + #region SimpleNameSyntax + internal static MemberAccessExpressionSyntax QualifyWithThis(this SimpleNameSyntax simpleName, bool simplifiable = true) + { + return SimpleMemberAccessExpression(ThisExpression(), simpleName).WithSimplifierAnnotationIf(simplifiable); + } + #endregion SimpleNameSyntax + + #region SyntaxNode + /// + /// Creates a new node with the attached. + /// + /// + /// + public static TNode WithFormatterAnnotation(this TNode node) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - return node.WithAdditionalAnnotations(_formatterAnnotationArray); - } + return node.WithAdditionalAnnotations(_formatterAnnotationArray); + } - /// - /// Creates a new node with the attached. - /// - /// - /// - public static TNode WithSimplifierAnnotation(this TNode node) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + /// + /// Creates a new node with the attached. + /// + /// + /// + public static TNode WithSimplifierAnnotation(this TNode node) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - return node.WithAdditionalAnnotations(_simplifierAnnotationArray); - } + return node.WithAdditionalAnnotations(_simplifierAnnotationArray); + } - internal static TNode WithNavigationAnnotation(this TNode node) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + internal static TNode WithNavigationAnnotation(this TNode node) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - SyntaxToken token = node.GetFirstToken(); + SyntaxToken token = node.GetFirstToken(); - if (token.IsKind(SyntaxKind.None)) - return node; + if (token.IsKind(SyntaxKind.None)) + return node; - return node.ReplaceToken(token, token.WithNavigationAnnotation()); - } - - internal static TNode WithSimplifierAnnotationIf(this TNode node, bool condition) where TNode : SyntaxNode - { - return (condition) ? node.WithAdditionalAnnotations(_simplifierAnnotationArray) : node; - } + return node.ReplaceToken(token, token.WithNavigationAnnotation()); + } - internal static TNode WithFormatterAndSimplifierAnnotation(this TNode node) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + internal static TNode WithSimplifierAnnotationIf(this TNode node, bool condition) where TNode : SyntaxNode + { + return (condition) ? node.WithAdditionalAnnotations(_simplifierAnnotationArray) : node; + } - return node.WithAdditionalAnnotations(_formatterAndSimplifierAnnotationArray); - } - #endregion SyntaxNode + internal static TNode WithFormatterAndSimplifierAnnotation(this TNode node) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - #region SyntaxToken - /// - /// Adds to the specified token, creating a new token of the same type with the on it. - /// - /// - public static SyntaxToken WithFormatterAnnotation(this SyntaxToken token) - { - return token.WithAdditionalAnnotations(_formatterAnnotationArray); - } + return node.WithAdditionalAnnotations(_formatterAndSimplifierAnnotationArray); + } + #endregion SyntaxNode + + #region SyntaxToken + /// + /// Adds to the specified token, creating a new token of the same type with the on it. + /// + /// + public static SyntaxToken WithFormatterAnnotation(this SyntaxToken token) + { + return token.WithAdditionalAnnotations(_formatterAnnotationArray); + } - /// - /// Adds to the specified token, creating a new token of the same type with the on it. - /// "Rename" annotation is specified by . - /// - /// - public static SyntaxToken WithSimplifierAnnotation(this SyntaxToken token) - { - return token.WithAdditionalAnnotations(_simplifierAnnotationArray); - } + /// + /// Adds to the specified token, creating a new token of the same type with the on it. + /// "Rename" annotation is specified by . + /// + /// + public static SyntaxToken WithSimplifierAnnotation(this SyntaxToken token) + { + return token.WithAdditionalAnnotations(_simplifierAnnotationArray); + } - /// - /// Adds navigation annotation to the specified token, creating a new token of the same type with the navigation annotation on it. - /// Navigation annotation allows to mark a token that should be selected after the code action is applied. - /// - /// - public static SyntaxToken WithNavigationAnnotation(this SyntaxToken token) - { - return token.WithAdditionalAnnotations(_navigationAnnotationArray); - } + /// + /// Adds navigation annotation to the specified token, creating a new token of the same type with the navigation annotation on it. + /// Navigation annotation allows to mark a token that should be selected after the code action is applied. + /// + /// + public static SyntaxToken WithNavigationAnnotation(this SyntaxToken token) + { + return token.WithAdditionalAnnotations(_navigationAnnotationArray); + } - /// - /// Adds "rename" annotation to the specified token, creating a new token of the same type with the "rename" annotation on it. - /// "Rename" annotation is specified by . - /// - /// - public static SyntaxToken WithRenameAnnotation(this SyntaxToken token) - { - return token.WithAdditionalAnnotations(_renameAnnotationArray); + /// + /// Adds "rename" annotation to the specified token, creating a new token of the same type with the "rename" annotation on it. + /// "Rename" annotation is specified by . + /// + /// + public static SyntaxToken WithRenameAnnotation(this SyntaxToken token) + { + return token.WithAdditionalAnnotations(_renameAnnotationArray); + } + #endregion SyntaxToken } - #endregion SyntaxToken } diff --git a/src/CSharp.Workspaces/CSharp/FindSymbols/LocalSymbolFinder.cs b/src/CSharp.Workspaces/CSharp/FindSymbols/LocalSymbolFinder.cs index f01770accd..1d90117415 100644 --- a/src/CSharp.Workspaces/CSharp/FindSymbols/LocalSymbolFinder.cs +++ b/src/CSharp.Workspaces/CSharp/FindSymbols/LocalSymbolFinder.cs @@ -7,172 +7,173 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp.FindSymbols; - -internal static class LocalSymbolFinder +namespace Roslynator.CSharp.FindSymbols { - public static ImmutableArray FindLocalSymbols( - SyntaxNode node, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) + internal static class LocalSymbolFinder { - var walker = new LocalSymbolCollector(semanticModel, cancellationToken); - - switch (node.Kind()) + public static ImmutableArray FindLocalSymbols( + SyntaxNode node, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) { - case SyntaxKind.ConstructorDeclaration: - { - var constructor = (ConstructorDeclarationSyntax)node; - walker.Visit(constructor.BodyOrExpressionBody()); - - break; - } - case SyntaxKind.EventDeclaration: - { - var eventDeclaration = (EventDeclarationSyntax)node; + var walker = new LocalSymbolCollector(semanticModel, cancellationToken); - foreach (AccessorDeclarationSyntax accessor in eventDeclaration.AccessorList.Accessors) - walker.Visit(accessor.BodyOrExpressionBody()); + switch (node.Kind()) + { + case SyntaxKind.ConstructorDeclaration: + { + var constructor = (ConstructorDeclarationSyntax)node; + walker.Visit(constructor.BodyOrExpressionBody()); - break; - } - case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)node; + break; + } + case SyntaxKind.EventDeclaration: + { + var eventDeclaration = (EventDeclarationSyntax)node; - foreach (AccessorDeclarationSyntax accessor in indexerDeclaration.AccessorList.Accessors) - walker.Visit(accessor.BodyOrExpressionBody()); + foreach (AccessorDeclarationSyntax accessor in eventDeclaration.AccessorList.Accessors) + walker.Visit(accessor.BodyOrExpressionBody()); - break; - } - case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)node; + break; + } + case SyntaxKind.IndexerDeclaration: + { + var indexerDeclaration = (IndexerDeclarationSyntax)node; - walker.Visit(methodDeclaration.BodyOrExpressionBody()); + foreach (AccessorDeclarationSyntax accessor in indexerDeclaration.AccessorList.Accessors) + walker.Visit(accessor.BodyOrExpressionBody()); - break; - } - case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; + break; + } + case SyntaxKind.MethodDeclaration: + { + var methodDeclaration = (MethodDeclarationSyntax)node; - ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; + walker.Visit(methodDeclaration.BodyOrExpressionBody()); - if (expressionBody != null) - { - walker.Visit(expressionBody); + break; } - else + case SyntaxKind.PropertyDeclaration: { - foreach (AccessorDeclarationSyntax accessor in propertyDeclaration.AccessorList.Accessors) - walker.Visit(accessor.BodyOrExpressionBody()); - } + var propertyDeclaration = (PropertyDeclarationSyntax)node; - break; - } - case SyntaxKind.VariableDeclarator: - { - var declarator = (VariableDeclaratorSyntax)node; + ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - ExpressionSyntax expression = declarator.Initializer?.Value; + if (expressionBody is not null) + { + walker.Visit(expressionBody); + } + else + { + foreach (AccessorDeclarationSyntax accessor in propertyDeclaration.AccessorList.Accessors) + walker.Visit(accessor.BodyOrExpressionBody()); + } - if (expression != null) - walker.Visit(expression); + break; + } + case SyntaxKind.VariableDeclarator: + { + var declarator = (VariableDeclaratorSyntax)node; - break; - } - case SyntaxKind.OperatorDeclaration: - { - var declaration = (OperatorDeclarationSyntax)node; + ExpressionSyntax expression = declarator.Initializer?.Value; - walker.Visit(declaration.BodyOrExpressionBody()); - break; - } - case SyntaxKind.ConversionOperatorDeclaration: - { - var declaration = (ConversionOperatorDeclarationSyntax)node; + if (expression is not null) + walker.Visit(expression); - walker.Visit(declaration.BodyOrExpressionBody()); - break; - } - case SyntaxKind.Parameter: - case SyntaxKind.RecordDeclaration: - { - break; - } - default: - { - SyntaxDebug.Fail(node); + break; + } + case SyntaxKind.OperatorDeclaration: + { + var declaration = (OperatorDeclarationSyntax)node; - walker.Visit(node); - break; - } - } + walker.Visit(declaration.BodyOrExpressionBody()); + break; + } + case SyntaxKind.ConversionOperatorDeclaration: + { + var declaration = (ConversionOperatorDeclarationSyntax)node; - return walker.Definitions.ToImmutableArray(); - } + walker.Visit(declaration.BodyOrExpressionBody()); + break; + } + case SyntaxKind.Parameter: + case SyntaxKind.RecordDeclaration: + { + break; + } + default: + { + SyntaxDebug.Fail(node); - private class LocalSymbolCollector : LocalWalker - { - public LocalSymbolCollector( - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - SemanticModel = semanticModel; - CancellationToken = cancellationToken; + walker.Visit(node); + break; + } + } - Definitions = ImmutableArray.CreateBuilder(); + return walker.Definitions.ToImmutableArray(); } - public SemanticModel SemanticModel { get; } + private class LocalSymbolCollector : LocalWalker + { + public LocalSymbolCollector( + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + SemanticModel = semanticModel; + CancellationToken = cancellationToken; + + Definitions = ImmutableArray.CreateBuilder(); + } - public CancellationToken CancellationToken { get; } + public SemanticModel SemanticModel { get; } - public ImmutableArray.Builder Definitions { get; } + public CancellationToken CancellationToken { get; } - public override void VisitLocal(SyntaxNode node) - { - ISymbol symbol = SemanticModel.GetDeclaredSymbol(node, CancellationToken); + public ImmutableArray.Builder Definitions { get; } - if (symbol != null) + public override void VisitLocal(SyntaxNode node) { - Debug.Assert(symbol.IsKind(SymbolKind.Local, SymbolKind.Method), symbol.Kind.ToString()); + ISymbol symbol = SemanticModel.GetDeclaredSymbol(node, CancellationToken); - if (symbol.Kind == SymbolKind.Local) + if (symbol is not null) { - VisitSymbol(symbol); - } - else if (symbol is IMethodSymbol methodSymbol - && methodSymbol.MethodKind == MethodKind.LocalFunction) - { - VisitSymbol(symbol); + Debug.Assert(symbol.IsKind(SymbolKind.Local, SymbolKind.Method), symbol.Kind.ToString()); - foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) - VisitSymbol(parameterSymbol); + if (symbol.Kind == SymbolKind.Local) + { + VisitSymbol(symbol); + } + else if (symbol is IMethodSymbol methodSymbol + && methodSymbol.MethodKind == MethodKind.LocalFunction) + { + VisitSymbol(symbol); - foreach (ITypeParameterSymbol typeParameterSymbol in methodSymbol.TypeParameters) - VisitSymbol(typeParameterSymbol); - } - } - else - { - symbol = SemanticModel.GetSymbol(node, CancellationToken); + foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) + VisitSymbol(parameterSymbol); - if (symbol is IMethodSymbol methodSymbol - && methodSymbol.MethodKind == MethodKind.AnonymousFunction) + foreach (ITypeParameterSymbol typeParameterSymbol in methodSymbol.TypeParameters) + VisitSymbol(typeParameterSymbol); + } + } + else { - foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) - VisitSymbol(parameterSymbol); + symbol = SemanticModel.GetSymbol(node, CancellationToken); + + if (symbol is IMethodSymbol methodSymbol + && methodSymbol.MethodKind == MethodKind.AnonymousFunction) + { + foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) + VisitSymbol(parameterSymbol); + } } } - } - private void VisitSymbol(ISymbol symbol) - { - CancellationToken.ThrowIfCancellationRequested(); + private void VisitSymbol(ISymbol symbol) + { + CancellationToken.ThrowIfCancellationRequested(); - Definitions.Add(symbol); + Definitions.Add(symbol); + } } } } diff --git a/src/CSharp.Workspaces/CSharp/Spelling/CSharpSpellingWalker.cs b/src/CSharp.Workspaces/CSharp/Spelling/CSharpSpellingWalker.cs index 52c9a95ace..afabf0aa12 100644 --- a/src/CSharp.Workspaces/CSharp/Spelling/CSharpSpellingWalker.cs +++ b/src/CSharp.Workspaces/CSharp/Spelling/CSharpSpellingWalker.cs @@ -8,593 +8,594 @@ using Microsoft.CodeAnalysis.Text; using Roslynator.Spelling; -namespace Roslynator.CSharp.Spelling; - -internal sealed class CSharpSpellingWalker : CSharpSyntaxWalker +namespace Roslynator.CSharp.Spelling { - private readonly SpellingAnalysisContext _analysisContext; - private readonly Stack _stack = new(); - - private SpellingFixerOptions Options => _analysisContext.Options; - - private CSharpSpellingWalker(SpellingAnalysisContext analysisContext, SyntaxWalkerDepth depth) - : base(depth) + internal sealed class CSharpSpellingWalker : CSharpSyntaxWalker { - _analysisContext = analysisContext; - } + private readonly SpellingAnalysisContext _analysisContext; + private readonly Stack _stack = new(); - public static CSharpSpellingWalker Create(SpellingAnalysisContext context) - { - return new CSharpSpellingWalker(context, GetWalkerDepth(context)); + private SpellingFixerOptions Options => _analysisContext.Options; + + private CSharpSpellingWalker(SpellingAnalysisContext analysisContext, SyntaxWalkerDepth depth) + : base(depth) + { + _analysisContext = analysisContext; + } - static SyntaxWalkerDepth GetWalkerDepth(SpellingAnalysisContext context) + public static CSharpSpellingWalker Create(SpellingAnalysisContext context) { - if ((context.Options.ScopeFilter & (SpellingScopeFilter.DocumentationComment | SpellingScopeFilter.Region)) != 0) - return SyntaxWalkerDepth.StructuredTrivia; + return new CSharpSpellingWalker(context, GetWalkerDepth(context)); - if ((context.Options.ScopeFilter & SpellingScopeFilter.NonDocumentationComment) != 0) - return SyntaxWalkerDepth.Trivia; + static SyntaxWalkerDepth GetWalkerDepth(SpellingAnalysisContext context) + { + if ((context.Options.ScopeFilter & (SpellingScopeFilter.DocumentationComment | SpellingScopeFilter.Region)) != 0) + return SyntaxWalkerDepth.StructuredTrivia; + + if ((context.Options.ScopeFilter & SpellingScopeFilter.NonDocumentationComment) != 0) + return SyntaxWalkerDepth.Trivia; - return SyntaxWalkerDepth.Token; + return SyntaxWalkerDepth.Token; + } } - } - private void AnalyzeText(string value, SyntaxTree syntaxTree, TextSpan textSpan) - { - _analysisContext.CancellationToken.ThrowIfCancellationRequested(); + private void AnalyzeText(string value, SyntaxTree syntaxTree, TextSpan textSpan) + { + _analysisContext.CancellationToken.ThrowIfCancellationRequested(); - _analysisContext.AnalyzeText(value, textSpan, syntaxTree); - } + _analysisContext.AnalyzeText(value, textSpan, syntaxTree); + } - private void AnalyzeIdentifier(SyntaxToken identifier, int prefixLength = 0) - { - _analysisContext.CancellationToken.ThrowIfCancellationRequested(); + private void AnalyzeIdentifier(SyntaxToken identifier, int prefixLength = 0) + { + _analysisContext.CancellationToken.ThrowIfCancellationRequested(); - _analysisContext.AnalyzeIdentifier(identifier, prefixLength); - } + _analysisContext.AnalyzeIdentifier(identifier, prefixLength); + } - public override void VisitTrivia(SyntaxTrivia trivia) - { - switch (trivia.Kind()) + public override void VisitTrivia(SyntaxTrivia trivia) { - case SyntaxKind.SingleLineCommentTrivia: - case SyntaxKind.MultiLineCommentTrivia: - { - if (ShouldVisit(SpellingScopeFilter.NonDocumentationComment)) + switch (trivia.Kind()) + { + case SyntaxKind.SingleLineCommentTrivia: + case SyntaxKind.MultiLineCommentTrivia: + { + if (ShouldVisit(SpellingScopeFilter.NonDocumentationComment)) + AnalyzeText(trivia.ToString(), trivia.SyntaxTree, trivia.Span); + + break; + } + case SyntaxKind.SingleLineDocumentationCommentTrivia: + case SyntaxKind.MultiLineDocumentationCommentTrivia: + { + if (ShouldVisit(SpellingScopeFilter.DocumentationComment)) + base.VisitTrivia(trivia); + + break; + } + case SyntaxKind.RegionDirectiveTrivia: + case SyntaxKind.EndRegionDirectiveTrivia: + { + if (ShouldVisit(SpellingScopeFilter.Region)) + base.VisitTrivia(trivia); + + break; + } + case SyntaxKind.PreprocessingMessageTrivia: + { + Debug.Assert(ShouldVisit(SpellingScopeFilter.Region)); + AnalyzeText(trivia.ToString(), trivia.SyntaxTree, trivia.Span); + break; + } + } + } - break; - } - case SyntaxKind.SingleLineDocumentationCommentTrivia: - case SyntaxKind.MultiLineDocumentationCommentTrivia: - { - if (ShouldVisit(SpellingScopeFilter.DocumentationComment)) - base.VisitTrivia(trivia); + public override void VisitTupleType(TupleTypeSyntax node) + { + if (node.Elements.All(f => f.Identifier.IsKind(SyntaxKind.None))) + return; - break; - } - case SyntaxKind.RegionDirectiveTrivia: - case SyntaxKind.EndRegionDirectiveTrivia: - { - if (ShouldVisit(SpellingScopeFilter.Region)) - base.VisitTrivia(trivia); + if (!ShouldVisit(SpellingScopeFilter.LocalVariable + | SpellingScopeFilter.Field + | SpellingScopeFilter.Constant + | SpellingScopeFilter.ReturnType + | SpellingScopeFilter.Class + | SpellingScopeFilter.Struct + | SpellingScopeFilter.Interface + | SpellingScopeFilter.Record)) + { + return; + } - break; - } - case SyntaxKind.PreprocessingMessageTrivia: - { - Debug.Assert(ShouldVisit(SpellingScopeFilter.Region)); + if (_stack.Count == 0) + { + SyntaxDebug.Fail(node); + return; + } - AnalyzeText(trivia.ToString(), trivia.SyntaxTree, trivia.Span); - break; - } - } - } + SyntaxNode containingNode = _stack.Peek(); - public override void VisitTupleType(TupleTypeSyntax node) - { - if (node.Elements.All(f => f.Identifier.IsKind(SyntaxKind.None))) - return; + switch (containingNode.Kind()) + { + case SyntaxKind.LocalDeclarationStatement: + case SyntaxKind.UsingStatement: + { + if (ShouldVisit(SpellingScopeFilter.LocalVariable)) + base.VisitTupleType(node); + + break; + } + case SyntaxKind.FieldDeclaration: + { + if (ShouldVisitFieldDeclaration(containingNode)) + base.VisitTupleType(node); + + 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); + + break; + } + case SyntaxKind.EventDeclaration: + case SyntaxKind.EventFieldDeclaration: + { + if (ShouldVisit(SpellingScopeFilter.Event)) + base.VisitTupleType(node); + + break; + } + case SyntaxKind.ClassDeclaration: + { + if (ShouldVisit(SpellingScopeFilter.Class)) + base.VisitTupleType(node); + + break; + } + case SyntaxKind.StructDeclaration: + { + if (ShouldVisit(SpellingScopeFilter.Struct)) + base.VisitTupleType(node); + + break; + } + case SyntaxKind.InterfaceDeclaration: + { + if (ShouldVisit(SpellingScopeFilter.Interface)) + base.VisitTupleType(node); + + break; + } + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + { + if (ShouldVisit(SpellingScopeFilter.Record)) + base.VisitTupleType(node); + + break; + } + case SyntaxKind.Parameter: + { + if (ShouldVisit(SpellingScopeFilter.Parameter)) + base.VisitTupleType(node); + + break; + } + default: + { + SyntaxDebug.Fail(containingNode); + break; + } + } + } - if (!ShouldVisit(SpellingScopeFilter.LocalVariable - | SpellingScopeFilter.Field - | SpellingScopeFilter.Constant - | SpellingScopeFilter.ReturnType - | SpellingScopeFilter.Class - | SpellingScopeFilter.Struct - | SpellingScopeFilter.Interface - | SpellingScopeFilter.Record)) + public override void VisitTupleElement(TupleElementSyntax node) { - return; + if (node.Identifier.Parent is not null) + AnalyzeIdentifier(node.Identifier); + + base.VisitTupleElement(node); } - if (_stack.Count == 0) + public override void VisitArgument(ArgumentSyntax node) { - SyntaxDebug.Fail(node); - return; + if (node.Expression is DeclarationExpressionSyntax declarationExpression) + VisitDeclarationExpression(declarationExpression); } - SyntaxNode containingNode = _stack.Peek(); - - switch (containingNode.Kind()) + public override void VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) { - case SyntaxKind.LocalDeclarationStatement: - case SyntaxKind.UsingStatement: - { - if (ShouldVisit(SpellingScopeFilter.LocalVariable)) - base.VisitTupleType(node); + if (node.NameEquals is not null + && ShouldVisit(SpellingScopeFilter.LocalVariable)) + { + AnalyzeIdentifier(node.NameEquals.Name.Identifier); + } - break; - } - case SyntaxKind.FieldDeclaration: - { - if (ShouldVisitFieldDeclaration(containingNode)) - base.VisitTupleType(node); + base.VisitAnonymousObjectMemberDeclarator(node); + } - 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); + public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.LocalFunction)) + AnalyzeIdentifier(node.Identifier); - break; - } - case SyntaxKind.EventDeclaration: - case SyntaxKind.EventFieldDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Event)) - base.VisitTupleType(node); + _stack.Push(node); + base.VisitLocalFunctionStatement(node); + _stack.Pop(); + } - break; - } - case SyntaxKind.ClassDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Class)) - base.VisitTupleType(node); + public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) + { + SyntaxDebug.Assert(node.IsParentKind(SyntaxKind.VariableDeclaration), node.Parent); - break; - } - case SyntaxKind.StructDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Struct)) - base.VisitTupleType(node); + SyntaxNode containingNode = _stack.Peek(); - break; - } - case SyntaxKind.InterfaceDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Interface)) - base.VisitTupleType(node); + switch (containingNode.Kind()) + { + case SyntaxKind.LocalDeclarationStatement: + case SyntaxKind.UsingStatement: + case SyntaxKind.ForStatement: + case SyntaxKind.FixedStatement: + { + if (ShouldVisit(SpellingScopeFilter.LocalVariable)) + AnalyzeIdentifier(node.Identifier); + + break; + } + case SyntaxKind.FieldDeclaration: + { + if (ShouldVisitFieldDeclaration(containingNode)) + AnalyzeIdentifier(node.Identifier); + + break; + } + case SyntaxKind.EventFieldDeclaration: + { + if (ShouldVisit(SpellingScopeFilter.Event)) + AnalyzeIdentifier(node.Identifier); + + break; + } + default: + { + SyntaxDebug.Fail(containingNode); + break; + } + } - break; - } - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Record)) - base.VisitTupleType(node); + base.VisitVariableDeclarator(node); + } - break; - } - case SyntaxKind.Parameter: - { - if (ShouldVisit(SpellingScopeFilter.Parameter)) - base.VisitTupleType(node); + public override void VisitSingleVariableDesignation(SingleVariableDesignationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.LocalVariable)) + AnalyzeIdentifier(node.Identifier); - break; - } - default: - { - SyntaxDebug.Fail(containingNode); - break; - } + base.VisitSingleVariableDesignation(node); } - } - public override void VisitTupleElement(TupleElementSyntax node) - { - if (node.Identifier.Parent != null) - AnalyzeIdentifier(node.Identifier); - - base.VisitTupleElement(node); - } + public override void VisitCatchDeclaration(CatchDeclarationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.LocalVariable)) + AnalyzeIdentifier(node.Identifier); - public override void VisitArgument(ArgumentSyntax node) - { - if (node.Expression is DeclarationExpressionSyntax declarationExpression) - VisitDeclarationExpression(declarationExpression); - } + base.VisitCatchDeclaration(node); + } - public override void VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) - { - if (node.NameEquals != null - && ShouldVisit(SpellingScopeFilter.LocalVariable)) + public override void VisitUsingDirective(UsingDirectiveSyntax node) { - AnalyzeIdentifier(node.NameEquals.Name.Identifier); + if (node.Alias is not null + && ShouldVisit(SpellingScopeFilter.UsingAlias)) + { + AnalyzeIdentifier(node.Alias.Name.Identifier); + } + + base.VisitUsingDirective(node); } - base.VisitAnonymousObjectMemberDeclarator(node); - } + public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.Namespace)) + VisitName(node.Name); - public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.LocalFunction)) - AnalyzeIdentifier(node.Identifier); + base.VisitNamespaceDeclaration(node); + } - _stack.Push(node); - base.VisitLocalFunctionStatement(node); - _stack.Pop(); - } + private void VisitName(NameSyntax node) + { + switch (node) + { + case IdentifierNameSyntax identifierName: + { + AnalyzeIdentifier(identifierName.Identifier); + break; + } + case QualifiedNameSyntax qualifiedName: + { + VisitName(qualifiedName.Left); - public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) - { - SyntaxDebug.Assert(node.IsParentKind(SyntaxKind.VariableDeclaration), node.Parent); + if (qualifiedName.Right is IdentifierNameSyntax identifierName) + AnalyzeIdentifier(identifierName.Identifier); - SyntaxNode containingNode = _stack.Peek(); + break; + } + } + } - switch (containingNode.Kind()) + public override void VisitTypeParameter(TypeParameterSyntax node) { - case SyntaxKind.LocalDeclarationStatement: - case SyntaxKind.UsingStatement: - case SyntaxKind.ForStatement: - case SyntaxKind.FixedStatement: - { - if (ShouldVisit(SpellingScopeFilter.LocalVariable)) - AnalyzeIdentifier(node.Identifier); - - break; - } - case SyntaxKind.FieldDeclaration: - { - if (ShouldVisitFieldDeclaration(containingNode)) - AnalyzeIdentifier(node.Identifier); - - break; - } - case SyntaxKind.EventFieldDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Event)) - AnalyzeIdentifier(node.Identifier); + if (ShouldVisit(SpellingScopeFilter.TypeParameter)) + { + SyntaxToken identifier = node.Identifier; + string value = identifier.ValueText; - break; - } - default: + int prefixLength = 0; + if (value.Length > 1 + && value[0] == 'T' + && char.IsUpper(value[1])) { - SyntaxDebug.Fail(containingNode); - break; + prefixLength = 1; } - } - base.VisitVariableDeclarator(node); - } - - public override void VisitSingleVariableDesignation(SingleVariableDesignationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.LocalVariable)) - AnalyzeIdentifier(node.Identifier); - - base.VisitSingleVariableDesignation(node); - } - - public override void VisitCatchDeclaration(CatchDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.LocalVariable)) - AnalyzeIdentifier(node.Identifier); + AnalyzeIdentifier(identifier, prefixLength: prefixLength); + } - base.VisitCatchDeclaration(node); - } + base.VisitTypeParameter(node); + } - public override void VisitUsingDirective(UsingDirectiveSyntax node) - { - if (node.Alias != null - && ShouldVisit(SpellingScopeFilter.UsingAlias)) + public override void VisitClassDeclaration(ClassDeclarationSyntax node) { - AnalyzeIdentifier(node.Alias.Name.Identifier); - } + if (ShouldVisit(SpellingScopeFilter.Class)) + AnalyzeIdentifier(node.Identifier); - base.VisitUsingDirective(node); - } + _stack.Push(node); + base.VisitClassDeclaration(node); + _stack.Pop(); + } - public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Namespace)) - VisitName(node.Name); + public override void VisitStructDeclaration(StructDeclarationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.Struct)) + AnalyzeIdentifier(node.Identifier); - base.VisitNamespaceDeclaration(node); - } + _stack.Push(node); + base.VisitStructDeclaration(node); + _stack.Pop(); + } - private void VisitName(NameSyntax node) - { - switch (node) + public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { - case IdentifierNameSyntax identifierName: + if (ShouldVisit(SpellingScopeFilter.Interface)) + { + SyntaxToken identifier = node.Identifier; + string value = identifier.ValueText; + + int prefixLength = 0; + if (value.Length > 1 + && value[0] == 'I' + && char.IsUpper(value[1])) { - AnalyzeIdentifier(identifierName.Identifier); - break; + prefixLength = 1; } - case QualifiedNameSyntax qualifiedName: - { - VisitName(qualifiedName.Left); - if (qualifiedName.Right is IdentifierNameSyntax identifierName) - AnalyzeIdentifier(identifierName.Identifier); + AnalyzeIdentifier(identifier, prefixLength: prefixLength); + } - break; - } + _stack.Push(node); + base.VisitInterfaceDeclaration(node); + _stack.Pop(); } - } - public override void VisitTypeParameter(TypeParameterSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.TypeParameter)) + public override void VisitRecordDeclaration(RecordDeclarationSyntax node) { - SyntaxToken identifier = node.Identifier; - string value = identifier.ValueText; - - int prefixLength = 0; - if (value.Length > 1 - && value[0] == 'T' - && char.IsUpper(value[1])) - { - prefixLength = 1; - } + if (ShouldVisit(SpellingScopeFilter.Record)) + AnalyzeIdentifier(node.Identifier); - AnalyzeIdentifier(identifier, prefixLength: prefixLength); + _stack.Push(node); + base.VisitRecordDeclaration(node); + _stack.Pop(); } - base.VisitTypeParameter(node); - } - - public override void VisitClassDeclaration(ClassDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Class)) - AnalyzeIdentifier(node.Identifier); - - _stack.Push(node); - base.VisitClassDeclaration(node); - _stack.Pop(); - } - - public override void VisitStructDeclaration(StructDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Struct)) - AnalyzeIdentifier(node.Identifier); + public override void VisitEnumDeclaration(EnumDeclarationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.Enum)) + AnalyzeIdentifier(node.Identifier); - _stack.Push(node); - base.VisitStructDeclaration(node); - _stack.Pop(); - } + base.VisitEnumDeclaration(node); + } - public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Interface)) + public override void VisitDelegateDeclaration(DelegateDeclarationSyntax node) { - SyntaxToken identifier = node.Identifier; - string value = identifier.ValueText; - - int prefixLength = 0; - if (value.Length > 1 - && value[0] == 'I' - && char.IsUpper(value[1])) - { - prefixLength = 1; - } + if (ShouldVisit(SpellingScopeFilter.Delegate)) + AnalyzeIdentifier(node.Identifier); - AnalyzeIdentifier(identifier, prefixLength: prefixLength); + _stack.Push(node); + base.VisitDelegateDeclaration(node); + _stack.Pop(); } - _stack.Push(node); - base.VisitInterfaceDeclaration(node); - _stack.Pop(); - } - - public override void VisitRecordDeclaration(RecordDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Record)) - AnalyzeIdentifier(node.Identifier); + public override void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.Field)) + AnalyzeIdentifier(node.Identifier); - _stack.Push(node); - base.VisitRecordDeclaration(node); - _stack.Pop(); - } + base.VisitEnumMemberDeclaration(node); + } - public override void VisitEnumDeclaration(EnumDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Enum)) - AnalyzeIdentifier(node.Identifier); + public override void VisitMethodDeclaration(MethodDeclarationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.Method)) + AnalyzeIdentifier(node.Identifier); - base.VisitEnumDeclaration(node); - } + _stack.Push(node); + base.VisitMethodDeclaration(node); + _stack.Pop(); + } - public override void VisitDelegateDeclaration(DelegateDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Delegate)) - AnalyzeIdentifier(node.Identifier); + public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.Property)) + AnalyzeIdentifier(node.Identifier); - _stack.Push(node); - base.VisitDelegateDeclaration(node); - _stack.Pop(); - } + _stack.Push(node); + base.VisitPropertyDeclaration(node); + _stack.Pop(); + } - public override void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Field)) - AnalyzeIdentifier(node.Identifier); + public override void VisitEventDeclaration(EventDeclarationSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.Event)) + AnalyzeIdentifier(node.Identifier); - base.VisitEnumMemberDeclaration(node); - } + base.VisitEventDeclaration(node); + } - public override void VisitMethodDeclaration(MethodDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Method)) - AnalyzeIdentifier(node.Identifier); + public override void VisitParameter(ParameterSyntax node) + { + if (node.Identifier.IsKind(SyntaxKind.ArgListKeyword)) + return; - _stack.Push(node); - base.VisitMethodDeclaration(node); - _stack.Pop(); - } + if (ShouldVisit(SpellingScopeFilter.Parameter)) + AnalyzeIdentifier(node.Identifier); - public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Property)) - AnalyzeIdentifier(node.Identifier); + _stack.Push(node); + base.VisitParameter(node); + _stack.Pop(); + } - _stack.Push(node); - base.VisitPropertyDeclaration(node); - _stack.Pop(); - } + public override void VisitForEachStatement(ForEachStatementSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.LocalVariable)) + AnalyzeIdentifier(node.Identifier); - public override void VisitEventDeclaration(EventDeclarationSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Event)) - AnalyzeIdentifier(node.Identifier); + base.VisitForEachStatement(node); + } - base.VisitEventDeclaration(node); - } + public override void VisitXmlElement(XmlElementSyntax node) + { + switch (node.StartTag.Name.LocalName.ValueText) + { + case "c": + case "code": + return; + } - public override void VisitParameter(ParameterSyntax node) - { - if (node.Identifier.IsKind(SyntaxKind.ArgListKeyword)) - return; + base.VisitXmlElement(node); + } - if (ShouldVisit(SpellingScopeFilter.Parameter)) - AnalyzeIdentifier(node.Identifier); + public override void VisitXmlText(XmlTextSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.DocumentationComment)) + { + foreach (SyntaxToken token in node.TextTokens) + { + if (token.IsKind(SyntaxKind.XmlTextLiteralToken)) + AnalyzeText(token.ValueText, node.SyntaxTree, token.Span); + } + } - _stack.Push(node); - base.VisitParameter(node); - _stack.Pop(); - } + base.VisitXmlText(node); + } - public override void VisitForEachStatement(ForEachStatementSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.LocalVariable)) - AnalyzeIdentifier(node.Identifier); + public override void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + _stack.Push(node); + base.VisitLocalDeclarationStatement(node); + _stack.Pop(); + } - base.VisitForEachStatement(node); - } + public override void VisitUsingStatement(UsingStatementSyntax node) + { + _stack.Push(node); + base.VisitUsingStatement(node); + _stack.Pop(); + } - public override void VisitXmlElement(XmlElementSyntax node) - { - switch (node.StartTag.Name.LocalName.ValueText) + public override void VisitForStatement(ForStatementSyntax node) { - case "c": - case "code": - return; + _stack.Push(node); + base.VisitForStatement(node); + _stack.Pop(); } - base.VisitXmlElement(node); - } + public override void VisitFixedStatement(FixedStatementSyntax node) + { + _stack.Push(node); + base.VisitFixedStatement(node); + _stack.Pop(); + } - public override void VisitXmlText(XmlTextSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.DocumentationComment)) + public override void VisitFieldDeclaration(FieldDeclarationSyntax node) { - foreach (SyntaxToken token in node.TextTokens) - { - if (token.IsKind(SyntaxKind.XmlTextLiteralToken)) - AnalyzeText(token.ValueText, node.SyntaxTree, token.Span); - } + _stack.Push(node); + base.VisitFieldDeclaration(node); + _stack.Pop(); } - base.VisitXmlText(node); - } + public override void VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) + { + _stack.Push(node); + base.VisitEventFieldDeclaration(node); + _stack.Pop(); + } - public override void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) - { - _stack.Push(node); - base.VisitLocalDeclarationStatement(node); - _stack.Pop(); - } + public override void VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) + { + _stack.Push(node); + base.VisitConversionOperatorDeclaration(node); + _stack.Pop(); + } - public override void VisitUsingStatement(UsingStatementSyntax node) - { - _stack.Push(node); - base.VisitUsingStatement(node); - _stack.Pop(); - } + public override void VisitIndexerDeclaration(IndexerDeclarationSyntax node) + { + _stack.Push(node); + base.VisitIndexerDeclaration(node); + _stack.Pop(); + } - public override void VisitForStatement(ForStatementSyntax node) - { - _stack.Push(node); - base.VisitForStatement(node); - _stack.Pop(); - } + public override void VisitLiteralExpression(LiteralExpressionSyntax node) + { + if (node.IsKind(SyntaxKind.StringLiteralExpression) + && ShouldVisit(SpellingScopeFilter.Literal)) + { + SyntaxToken token = node.Token; - public override void VisitFixedStatement(FixedStatementSyntax node) - { - _stack.Push(node); - base.VisitFixedStatement(node); - _stack.Pop(); - } + AnalyzeText(token.Text, node.SyntaxTree, token.Span); + } - public override void VisitFieldDeclaration(FieldDeclarationSyntax node) - { - _stack.Push(node); - base.VisitFieldDeclaration(node); - _stack.Pop(); - } + base.VisitLiteralExpression(node); + } - public override void VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) - { - _stack.Push(node); - base.VisitEventFieldDeclaration(node); - _stack.Pop(); - } + public override void VisitInterpolatedStringText(InterpolatedStringTextSyntax node) + { + if (ShouldVisit(SpellingScopeFilter.Literal)) + { + SyntaxToken token = node.TextToken; - public override void VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) - { - _stack.Push(node); - base.VisitConversionOperatorDeclaration(node); - _stack.Pop(); - } + AnalyzeText(token.Text, node.SyntaxTree, token.Span); + } - public override void VisitIndexerDeclaration(IndexerDeclarationSyntax node) - { - _stack.Push(node); - base.VisitIndexerDeclaration(node); - _stack.Pop(); - } + base.VisitInterpolatedStringText(node); + } - public override void VisitLiteralExpression(LiteralExpressionSyntax node) - { - if (node.IsKind(SyntaxKind.StringLiteralExpression) - && ShouldVisit(SpellingScopeFilter.Literal)) + private bool ShouldVisit(SpellingScopeFilter filter) { - SyntaxToken token = node.Token; - - AnalyzeText(token.Text, node.SyntaxTree, token.Span); + return (Options.ScopeFilter & filter) != 0; } - base.VisitLiteralExpression(node); - } - - public override void VisitInterpolatedStringText(InterpolatedStringTextSyntax node) - { - if (ShouldVisit(SpellingScopeFilter.Literal)) + private bool ShouldVisitFieldDeclaration(SyntaxNode fieldDeclaration) { - SyntaxToken token = node.TextToken; - - AnalyzeText(token.Text, node.SyntaxTree, token.Span); + return ShouldVisit((((FieldDeclarationSyntax)fieldDeclaration).Modifiers.Contains(SyntaxKind.ConstKeyword)) + ? SpellingScopeFilter.Constant + : SpellingScopeFilter.Field); } - - base.VisitInterpolatedStringText(node); - } - - private bool ShouldVisit(SpellingScopeFilter filter) - { - return (Options.ScopeFilter & filter) != 0; - } - - private bool ShouldVisitFieldDeclaration(SyntaxNode fieldDeclaration) - { - return ShouldVisit((((FieldDeclarationSyntax)fieldDeclaration).Modifiers.Contains(SyntaxKind.ConstKeyword)) - ? SpellingScopeFilter.Constant - : SpellingScopeFilter.Field); } } diff --git a/src/CSharp.Workspaces/CSharp/SyntaxFormatter.cs b/src/CSharp.Workspaces/CSharp/SyntaxFormatter.cs index 81f60d8e6e..4e7cfb3d48 100644 --- a/src/CSharp.Workspaces/CSharp/SyntaxFormatter.cs +++ b/src/CSharp.Workspaces/CSharp/SyntaxFormatter.cs @@ -15,532 +15,533 @@ using static Roslynator.CSharp.CSharpFactory; using static Roslynator.CSharp.SyntaxTriviaAnalysis; -namespace Roslynator.CSharp; - -internal static class SyntaxFormatter +namespace Roslynator.CSharp { - public static Task UnwrapExpressionAsync( - Document document, - TNode node, - CancellationToken cancellationToken = default) where TNode : SyntaxNode + internal static class SyntaxFormatter { - TextSpan span = (node.GetTrailingTrivia().IsEmptyOrWhitespace()) - ? TextSpan.FromBounds(node.SpanStart, node.FullSpan.End) - : node.Span; + public static Task UnwrapExpressionAsync( + Document document, + TNode node, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + TextSpan span = (node.GetTrailingTrivia().IsEmptyOrWhitespace()) + ? TextSpan.FromBounds(node.SpanStart, node.FullSpan.End) + : node.Span; - TNode newNode = node.ReplaceWhitespace(ElasticSpace, span).WithFormatterAnnotation(); + TNode newNode = node.ReplaceWhitespace(ElasticSpace, span).WithFormatterAnnotation(); - return document.ReplaceNodeAsync(node, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(node, newNode, cancellationToken); + } - public static Task ToSingleLineAsync( - Document document, - TNode node, - TextSpan span, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - TNode newNode = node.ReplaceWhitespace(ElasticSpace, span).WithFormatterAnnotation(); + public static Task ToSingleLineAsync( + Document document, + TNode node, + TextSpan span, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + TNode newNode = node.ReplaceWhitespace(ElasticSpace, span).WithFormatterAnnotation(); - return document.ReplaceNodeAsync(node, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(node, newNode, cancellationToken); + } - public static Task ToSingleLineAsync( - Document document, - InitializerExpressionSyntax initializer, - bool removeTrailingComma = false, - CancellationToken cancellationToken = default) - { - InitializerExpressionSyntax newInitializer = initializer - .ReplaceWhitespace(ElasticSpace, TextSpan.FromBounds(initializer.SpanStart, initializer.Span.End)) - .WithFormatterAnnotation(); + public static Task ToSingleLineAsync( + Document document, + InitializerExpressionSyntax initializer, + bool removeTrailingComma = false, + CancellationToken cancellationToken = default) + { + InitializerExpressionSyntax newInitializer = initializer + .ReplaceWhitespace(ElasticSpace, TextSpan.FromBounds(initializer.SpanStart, initializer.Span.End)) + .WithFormatterAnnotation(); - newInitializer = newInitializer.WithOpenBraceToken(newInitializer.OpenBraceToken.WithoutLeadingTrivia().WithTrailingTrivia(Space)); + newInitializer = newInitializer.WithOpenBraceToken(newInitializer.OpenBraceToken.WithoutLeadingTrivia().WithTrailingTrivia(Space)); - newInitializer = newInitializer.WithCloseBraceToken(newInitializer.CloseBraceToken.WithoutLeadingTrivia()); + newInitializer = newInitializer.WithCloseBraceToken(newInitializer.CloseBraceToken.WithoutLeadingTrivia()); - SeparatedSyntaxList expressions = newInitializer.Expressions; + SeparatedSyntaxList expressions = newInitializer.Expressions; - if (expressions.Any()) - { - ExpressionSyntax firstExpression = expressions[0]; + if (expressions.Any()) + { + ExpressionSyntax firstExpression = expressions[0]; - newInitializer = newInitializer.WithExpressions(expressions.Replace(firstExpression, firstExpression.WithoutLeadingTrivia())); + newInitializer = newInitializer.WithExpressions(expressions.Replace(firstExpression, firstExpression.WithoutLeadingTrivia())); - expressions = newInitializer.Expressions; + expressions = newInitializer.Expressions; - SyntaxToken trailingComma = expressions.GetTrailingSeparator(); + SyntaxToken trailingComma = expressions.GetTrailingSeparator(); - if (trailingComma.IsKind(SyntaxKind.CommaToken)) - { - if (removeTrailingComma) + if (trailingComma.IsKind(SyntaxKind.CommaToken)) { - expressions = expressions.ReplaceSeparator(trailingComma, MissingToken(SyntaxKind.CommaToken)); + if (removeTrailingComma) + { + expressions = expressions.ReplaceSeparator(trailingComma, MissingToken(SyntaxKind.CommaToken)); - ExpressionSyntax lastExpression = expressions.Last(); + ExpressionSyntax lastExpression = expressions.Last(); - expressions = expressions.Replace(lastExpression, lastExpression.WithTrailingTrivia(Space)); + expressions = expressions.Replace(lastExpression, lastExpression.WithTrailingTrivia(Space)); - newInitializer = newInitializer.WithExpressions(expressions); + newInitializer = newInitializer.WithExpressions(expressions); + } + else + { + newInitializer = newInitializer.WithExpressions(expressions.ReplaceSeparator(trailingComma, trailingComma.WithTrailingTrivia(Space))); + } } else { - newInitializer = newInitializer.WithExpressions(expressions.ReplaceSeparator(trailingComma, trailingComma.WithTrailingTrivia(Space))); + ExpressionSyntax lastExpression = expressions.Last(); + + newInitializer = newInitializer.WithExpressions(expressions.Replace(lastExpression, lastExpression.WithTrailingTrivia(Space))); } } - else - { - ExpressionSyntax lastExpression = expressions.Last(); - newInitializer = newInitializer.WithExpressions(expressions.Replace(lastExpression, lastExpression.WithTrailingTrivia(Space))); - } - } + SyntaxNode parent = initializer.Parent; - SyntaxNode parent = initializer.Parent; + SyntaxNode newParent; - SyntaxNode newParent; + switch (parent.Kind()) + { + case SyntaxKind.ObjectCreationExpression: + { + var expression = (ObjectCreationExpressionSyntax)parent; - switch (parent.Kind()) - { - case SyntaxKind.ObjectCreationExpression: - { - var expression = (ObjectCreationExpressionSyntax)parent; + expression = expression.WithInitializer(newInitializer); - expression = expression.WithInitializer(newInitializer); + ArgumentListSyntax argumentList = expression.ArgumentList; - ArgumentListSyntax argumentList = expression.ArgumentList; + if (argumentList is not null) + { + newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); + } + else + { + newParent = expression.WithType(expression.Type.WithTrailingTrivia(Space)); + } - if (argumentList != null) - { - newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); + break; } - else + case SyntaxKind.ImplicitObjectCreationExpression: { - newParent = expression.WithType(expression.Type.WithTrailingTrivia(Space)); - } + var expression = (ImplicitObjectCreationExpressionSyntax)parent; - break; - } - case SyntaxKind.ImplicitObjectCreationExpression: - { - var expression = (ImplicitObjectCreationExpressionSyntax)parent; + expression = expression.WithInitializer(newInitializer); - expression = expression.WithInitializer(newInitializer); + ArgumentListSyntax argumentList = expression.ArgumentList; - ArgumentListSyntax argumentList = expression.ArgumentList; + if (argumentList is not null) + { + newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); + } + else + { + newParent = expression.WithNewKeyword(expression.NewKeyword.WithTrailingTrivia(Space)); + } - if (argumentList != null) - { - newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); + break; } - else + case SyntaxKind.ArrayCreationExpression: { - newParent = expression.WithNewKeyword(expression.NewKeyword.WithTrailingTrivia(Space)); - } + var expression = (ArrayCreationExpressionSyntax)parent; - break; - } - case SyntaxKind.ArrayCreationExpression: - { - var expression = (ArrayCreationExpressionSyntax)parent; + newParent = expression + .WithInitializer(newInitializer) + .WithType(expression.Type.WithTrailingTrivia(Space)); - newParent = expression - .WithInitializer(newInitializer) - .WithType(expression.Type.WithTrailingTrivia(Space)); + break; + } + case SyntaxKind.ImplicitArrayCreationExpression: + { + var expression = (ImplicitArrayCreationExpressionSyntax)parent; - break; - } - case SyntaxKind.ImplicitArrayCreationExpression: - { - var expression = (ImplicitArrayCreationExpressionSyntax)parent; + newParent = expression + .WithInitializer(newInitializer) + .WithCloseBracketToken(expression.CloseBracketToken.WithTrailingTrivia(Space)); - newParent = expression - .WithInitializer(newInitializer) - .WithCloseBracketToken(expression.CloseBracketToken.WithTrailingTrivia(Space)); + break; + } + case SyntaxKind.EqualsValueClause: + { + var equalsValueClause = (EqualsValueClauseSyntax)parent; - break; - } - case SyntaxKind.EqualsValueClause: - { - var equalsValueClause = (EqualsValueClauseSyntax)parent; + newParent = equalsValueClause + .WithValue(newInitializer) + .WithEqualsToken(equalsValueClause.EqualsToken.WithTrailingTrivia(Space)); - newParent = equalsValueClause - .WithValue(newInitializer) - .WithEqualsToken(equalsValueClause.EqualsToken.WithTrailingTrivia(Space)); + break; + } + case SyntaxKind.SimpleAssignmentExpression: + { + var simpleAssignment = (AssignmentExpressionSyntax)parent; - break; - } - case SyntaxKind.SimpleAssignmentExpression: - { - var simpleAssignment = (AssignmentExpressionSyntax)parent; + newParent = simpleAssignment + .WithRight(newInitializer) + .WithOperatorToken(simpleAssignment.OperatorToken.WithTrailingTrivia(Space)); - newParent = simpleAssignment - .WithRight(newInitializer) - .WithOperatorToken(simpleAssignment.OperatorToken.WithTrailingTrivia(Space)); + break; + } + default: + { + SyntaxDebug.Fail(parent); - break; - } - default: - { - SyntaxDebug.Fail(parent); + return document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken); + } + } - return document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken); - } + return document.ReplaceNodeAsync(parent, newParent, cancellationToken); } - return document.ReplaceNodeAsync(parent, newParent, cancellationToken); - } - - public static Task WrapConditionalExpressionAsync( - Document document, - ConditionalExpressionSyntax conditionalExpression, - CancellationToken cancellationToken = default) - { - ConditionalExpressionSyntax newNode = ToMultiLine(conditionalExpression, cancellationToken); - - return document.ReplaceNodeAsync(conditionalExpression, newNode, cancellationToken); - } + public static Task WrapConditionalExpressionAsync( + Document document, + ConditionalExpressionSyntax conditionalExpression, + CancellationToken cancellationToken = default) + { + ConditionalExpressionSyntax newNode = ToMultiLine(conditionalExpression, cancellationToken); - public static ConditionalExpressionSyntax ToMultiLine(ConditionalExpressionSyntax conditionalExpression, CancellationToken cancellationToken = default) - { - SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(conditionalExpression, cancellationToken); + return document.ReplaceNodeAsync(conditionalExpression, newNode, cancellationToken); + } - leadingTrivia = leadingTrivia.Insert(0, DetermineEndOfLine(conditionalExpression)); + public static ConditionalExpressionSyntax ToMultiLine(ConditionalExpressionSyntax conditionalExpression, CancellationToken cancellationToken = default) + { + SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(conditionalExpression, cancellationToken); - return ConditionalExpression( - conditionalExpression.Condition.WithoutTrailingTrivia(), - Token(leadingTrivia, SyntaxKind.QuestionToken, TriviaList(Space)), - conditionalExpression.WhenTrue.WithoutTrailingTrivia(), - Token(leadingTrivia, SyntaxKind.ColonToken, TriviaList(Space)), - conditionalExpression.WhenFalse.WithoutTrailingTrivia()); - } + leadingTrivia = leadingTrivia.Insert(0, DetermineEndOfLine(conditionalExpression)); - public static Task WrapParametersAsync( - Document document, - ParameterListSyntax parameterList, - CancellationToken cancellationToken = default) - { - ParameterListSyntax newNode = WrapParameters(parameterList); + return ConditionalExpression( + conditionalExpression.Condition.WithoutTrailingTrivia(), + Token(leadingTrivia, SyntaxKind.QuestionToken, TriviaList(Space)), + conditionalExpression.WhenTrue.WithoutTrailingTrivia(), + Token(leadingTrivia, SyntaxKind.ColonToken, TriviaList(Space)), + conditionalExpression.WhenFalse.WithoutTrailingTrivia()); + } - return document.ReplaceNodeAsync(parameterList, newNode, cancellationToken); - } + public static Task WrapParametersAsync( + Document document, + ParameterListSyntax parameterList, + CancellationToken cancellationToken = default) + { + ParameterListSyntax newNode = WrapParameters(parameterList); - public static ParameterListSyntax WrapParameters(ParameterListSyntax parameterList, CancellationToken cancellationToken = default) - { - SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(parameterList, cancellationToken); + return document.ReplaceNodeAsync(parameterList, newNode, cancellationToken); + } - var nodesAndTokens = new List(); + public static ParameterListSyntax WrapParameters(ParameterListSyntax parameterList, CancellationToken cancellationToken = default) + { + SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(parameterList, cancellationToken); - SeparatedSyntaxList.Enumerator en = parameterList.Parameters.GetEnumerator(); + var nodesAndTokens = new List(); - SyntaxTrivia endOfLine = DetermineEndOfLine(parameterList); + SeparatedSyntaxList.Enumerator en = parameterList.Parameters.GetEnumerator(); - if (en.MoveNext()) - { - nodesAndTokens.Add(en.Current.WithLeadingTrivia(leadingTrivia)); + SyntaxTrivia endOfLine = DetermineEndOfLine(parameterList); - while (en.MoveNext()) + if (en.MoveNext()) { - nodesAndTokens.Add(CommaToken().WithTrailingTrivia(endOfLine)); - nodesAndTokens.Add(en.Current.WithLeadingTrivia(leadingTrivia)); - } - } - return ParameterList( - OpenParenToken().WithTrailingTrivia(endOfLine), - SeparatedList(nodesAndTokens), - parameterList.CloseParenToken); - } - - public static Task WrapParametersAsync( - Document document, - BracketedParameterListSyntax parameterList, - CancellationToken cancellationToken = default) - { - BracketedParameterListSyntax newNode = WrapParameters(parameterList); - - return document.ReplaceNodeAsync(parameterList, newNode, cancellationToken); - } + while (en.MoveNext()) + { + nodesAndTokens.Add(CommaToken().WithTrailingTrivia(endOfLine)); - public static BracketedParameterListSyntax WrapParameters(BracketedParameterListSyntax parameterList, CancellationToken cancellationToken = default) - { - SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(parameterList, cancellationToken); + nodesAndTokens.Add(en.Current.WithLeadingTrivia(leadingTrivia)); + } + } - var nodesAndTokens = new List(); + return ParameterList( + OpenParenToken().WithTrailingTrivia(endOfLine), + SeparatedList(nodesAndTokens), + parameterList.CloseParenToken); + } - SeparatedSyntaxList.Enumerator en = parameterList.Parameters.GetEnumerator(); + public static Task WrapParametersAsync( + Document document, + BracketedParameterListSyntax parameterList, + CancellationToken cancellationToken = default) + { + BracketedParameterListSyntax newNode = WrapParameters(parameterList); - SyntaxTrivia endOfLine = DetermineEndOfLine(parameterList); + return document.ReplaceNodeAsync(parameterList, newNode, cancellationToken); + } - if (en.MoveNext()) + public static BracketedParameterListSyntax WrapParameters(BracketedParameterListSyntax parameterList, CancellationToken cancellationToken = default) { - nodesAndTokens.Add(en.Current.WithLeadingTrivia(leadingTrivia)); + SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(parameterList, cancellationToken); - while (en.MoveNext()) - { - nodesAndTokens.Add(CommaToken().WithTrailingTrivia(endOfLine)); + var nodesAndTokens = new List(); - nodesAndTokens.Add(en.Current.WithLeadingTrivia(leadingTrivia)); - } - } + SeparatedSyntaxList.Enumerator en = parameterList.Parameters.GetEnumerator(); - return BracketedParameterList( - OpenParenToken().WithTrailingTrivia(endOfLine), - SeparatedList(nodesAndTokens), - parameterList.CloseBracketToken); - } + SyntaxTrivia endOfLine = DetermineEndOfLine(parameterList); - public static Task ToMultiLineAsync( - Document document, - InitializerExpressionSyntax initializer, - CancellationToken cancellationToken = default) - { - InitializerExpressionSyntax newNode = ToMultiLine(initializer, cancellationToken) - .WithFormatterAnnotation(); + if (en.MoveNext()) + { + nodesAndTokens.Add(en.Current.WithLeadingTrivia(leadingTrivia)); - return document.ReplaceNodeAsync(initializer, newNode, cancellationToken); - } + while (en.MoveNext()) + { + nodesAndTokens.Add(CommaToken().WithTrailingTrivia(endOfLine)); - public static InitializerExpressionSyntax ToMultiLine(InitializerExpressionSyntax initializer, CancellationToken cancellationToken) - { - SyntaxNode parent = initializer.Parent; + nodesAndTokens.Add(en.Current.WithLeadingTrivia(leadingTrivia)); + } + } - SyntaxTrivia endOfLine = DetermineEndOfLine(initializer); + return BracketedParameterList( + OpenParenToken().WithTrailingTrivia(endOfLine), + SeparatedList(nodesAndTokens), + parameterList.CloseBracketToken); + } - if (parent.IsKind(SyntaxKind.ObjectCreationExpression) - && !initializer.IsKind(SyntaxKind.CollectionInitializerExpression)) + public static Task ToMultiLineAsync( + Document document, + InitializerExpressionSyntax initializer, + CancellationToken cancellationToken = default) { - return initializer - .WithExpressions( - SeparatedList( - initializer.Expressions.Select(expression => expression.WithLeadingTrivia(endOfLine)))); + InitializerExpressionSyntax newNode = ToMultiLine(initializer, cancellationToken) + .WithFormatterAnnotation(); + + return document.ReplaceNodeAsync(initializer, newNode, cancellationToken); } - else + + public static InitializerExpressionSyntax ToMultiLine(InitializerExpressionSyntax initializer, CancellationToken cancellationToken) { - IndentationAnalysis indentationAnalysis = AnalyzeIndentation(initializer, cancellationToken); + SyntaxNode parent = initializer.Parent; - SyntaxTriviaList braceTrivia = TriviaList(endOfLine, indentationAnalysis.Indentation); - SyntaxTriviaList expressionTrivia = TriviaList(endOfLine, indentationAnalysis.GetIncreasedIndentationTrivia()); + SyntaxTrivia endOfLine = DetermineEndOfLine(initializer); - return initializer - .WithExpressions( - SeparatedList( - initializer.Expressions.Select(expression => expression.WithLeadingTrivia(expressionTrivia)))) - .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(braceTrivia)) - .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(braceTrivia)); - } - } + if (parent.IsKind(SyntaxKind.ObjectCreationExpression) + && !initializer.IsKind(SyntaxKind.CollectionInitializerExpression)) + { + return initializer + .WithExpressions( + SeparatedList( + initializer.Expressions.Select(expression => expression.WithLeadingTrivia(endOfLine)))); + } + else + { + IndentationAnalysis indentationAnalysis = AnalyzeIndentation(initializer, cancellationToken); - public static Task WrapArgumentsAsync( - Document document, - ArgumentListSyntax argumentList, - CancellationToken cancellationToken = default) - { - ArgumentListSyntax newNode = ToMultiLine(argumentList); + SyntaxTriviaList braceTrivia = TriviaList(endOfLine, indentationAnalysis.Indentation); + SyntaxTriviaList expressionTrivia = TriviaList(endOfLine, indentationAnalysis.GetIncreasedIndentationTrivia()); - return document.ReplaceNodeAsync(argumentList, newNode, cancellationToken); - } + return initializer + .WithExpressions( + SeparatedList( + initializer.Expressions.Select(expression => expression.WithLeadingTrivia(expressionTrivia)))) + .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(braceTrivia)) + .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(braceTrivia)); + } + } - public static ArgumentListSyntax ToMultiLine(ArgumentListSyntax argumentList, CancellationToken cancellationToken = default) - { - SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(argumentList, cancellationToken); + public static Task WrapArgumentsAsync( + Document document, + ArgumentListSyntax argumentList, + CancellationToken cancellationToken = default) + { + ArgumentListSyntax newNode = ToMultiLine(argumentList); - var nodesAndTokens = new List(); + return document.ReplaceNodeAsync(argumentList, newNode, cancellationToken); + } - SeparatedSyntaxList.Enumerator en = argumentList.Arguments.GetEnumerator(); + public static ArgumentListSyntax ToMultiLine(ArgumentListSyntax argumentList, CancellationToken cancellationToken = default) + { + SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(argumentList, cancellationToken); - SyntaxTrivia endOfLine = DetermineEndOfLine(argumentList); + var nodesAndTokens = new List(); - if (en.MoveNext()) - { - nodesAndTokens.Add(en.Current - .TrimTrailingTrivia() - .WithLeadingTrivia(leadingTrivia)); + SeparatedSyntaxList.Enumerator en = argumentList.Arguments.GetEnumerator(); - while (en.MoveNext()) - { - nodesAndTokens.Add(CommaToken().WithTrailingTrivia(endOfLine)); + SyntaxTrivia endOfLine = DetermineEndOfLine(argumentList); + if (en.MoveNext()) + { nodesAndTokens.Add(en.Current .TrimTrailingTrivia() .WithLeadingTrivia(leadingTrivia)); + + while (en.MoveNext()) + { + nodesAndTokens.Add(CommaToken().WithTrailingTrivia(endOfLine)); + + nodesAndTokens.Add(en.Current + .TrimTrailingTrivia() + .WithLeadingTrivia(leadingTrivia)); + } } - } - return ArgumentList( - OpenParenToken().WithTrailingTrivia(endOfLine), - SeparatedList(nodesAndTokens), - argumentList.CloseParenToken.WithoutLeadingTrivia()); - } + return ArgumentList( + OpenParenToken().WithTrailingTrivia(endOfLine), + SeparatedList(nodesAndTokens), + argumentList.CloseParenToken.WithoutLeadingTrivia()); + } - public static async Task WrapCallChainAsync( - Document document, - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + public static async Task WrapCallChainAsync( + Document document, + ExpressionSyntax expression, + CancellationToken cancellationToken = default) + { + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - return await WrapCallChainAsync(document, expression, semanticModel, cancellationToken).ConfigureAwait(false); - } + return await WrapCallChainAsync(document, expression, semanticModel, cancellationToken).ConfigureAwait(false); + } - public static Task WrapCallChainAsync( - Document document, - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - IndentationAnalysis indentationAnalysis = AnalyzeIndentation(expression, cancellationToken); + public static Task WrapCallChainAsync( + Document document, + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + IndentationAnalysis indentationAnalysis = AnalyzeIndentation(expression, cancellationToken); - string indentation = Environment.NewLine + indentationAnalysis.GetIncreasedIndentation(); + string indentation = Environment.NewLine + indentationAnalysis.GetIncreasedIndentation(); - TextChange? textChange = null; - List textChanges = null; + TextChange? textChange = null; + List textChanges = null; - foreach (SyntaxNode node in new MethodChain(expression)) - { - switch (node.Kind()) + foreach (SyntaxNode node in new MethodChain(expression)) { - case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)node; + switch (node.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + { + var memberAccess = (MemberAccessExpressionSyntax)node; - if (memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) - break; + if (memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) + break; - if (semanticModel - .GetSymbol(memberAccess.Expression, cancellationToken)? - .Kind == SymbolKind.Namespace) - { + if (semanticModel + .GetSymbol(memberAccess.Expression, cancellationToken)? + .Kind == SymbolKind.Namespace) + { + break; + } + + AddTextChange(memberAccess.OperatorToken); break; } + case SyntaxKind.MemberBindingExpression: + { + var memberBinding = (MemberBindingExpressionSyntax)node; - AddTextChange(memberAccess.OperatorToken); - break; - } - case SyntaxKind.MemberBindingExpression: - { - var memberBinding = (MemberBindingExpressionSyntax)node; - - AddTextChange(memberBinding.OperatorToken); - break; - } + AddTextChange(memberBinding.OperatorToken); + break; + } + } } - } - - if (textChanges != null) - { - TextChange[] arr = textChanges.ToArray(); - Array.Reverse(arr); - return document.WithTextChangesAsync(arr, cancellationToken); - } - else - { - return document.WithTextChangeAsync(textChange.Value, cancellationToken); - } - void AddTextChange(SyntaxToken operatorToken) - { - var tc = new TextChange(new TextSpan(operatorToken.SpanStart, 0), indentation); - - if (textChange == null) + if (textChanges is not null) { - textChange = tc; + TextChange[] arr = textChanges.ToArray(); + Array.Reverse(arr); + return document.WithTextChangesAsync(arr, cancellationToken); } else { - (textChanges ??= new List() { textChange.Value }).Add(tc); + return document.WithTextChangeAsync(textChange.Value, cancellationToken); } - } - } - public static Task WrapArgumentsAsync( - Document document, - AttributeArgumentListSyntax argumentList, - CancellationToken cancellationToken = default) - { - AttributeArgumentListSyntax newNode = ToMultiLine(argumentList, cancellationToken); + void AddTextChange(SyntaxToken operatorToken) + { + var tc = new TextChange(new TextSpan(operatorToken.SpanStart, 0), indentation); - return document.ReplaceNodeAsync(argumentList, newNode, cancellationToken); - } + if (textChange is null) + { + textChange = tc; + } + else + { + (textChanges ??= new List() { textChange.Value }).Add(tc); + } + } + } - private static AttributeArgumentListSyntax ToMultiLine(AttributeArgumentListSyntax argumentList, CancellationToken cancellationToken = default) - { - SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(argumentList, cancellationToken); + public static Task WrapArgumentsAsync( + Document document, + AttributeArgumentListSyntax argumentList, + CancellationToken cancellationToken = default) + { + AttributeArgumentListSyntax newNode = ToMultiLine(argumentList, cancellationToken); - var nodesAndTokens = new List(); + return document.ReplaceNodeAsync(argumentList, newNode, cancellationToken); + } - SeparatedSyntaxList.Enumerator en = argumentList.Arguments.GetEnumerator(); + private static AttributeArgumentListSyntax ToMultiLine(AttributeArgumentListSyntax argumentList, CancellationToken cancellationToken = default) + { + SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(argumentList, cancellationToken); - SyntaxTrivia endOfLine = DetermineEndOfLine(argumentList); + var nodesAndTokens = new List(); - if (en.MoveNext()) - { - nodesAndTokens.Add(en.Current - .TrimTrailingTrivia() - .WithLeadingTrivia(leadingTrivia)); + SeparatedSyntaxList.Enumerator en = argumentList.Arguments.GetEnumerator(); - while (en.MoveNext()) - { - nodesAndTokens.Add(CommaToken().WithTrailingTrivia(endOfLine)); + SyntaxTrivia endOfLine = DetermineEndOfLine(argumentList); + if (en.MoveNext()) + { nodesAndTokens.Add(en.Current .TrimTrailingTrivia() .WithLeadingTrivia(leadingTrivia)); - } - } - return AttributeArgumentList( - OpenParenToken().WithTrailingTrivia(endOfLine), - SeparatedList(nodesAndTokens), - argumentList.CloseParenToken.WithoutLeadingTrivia()); - } + while (en.MoveNext()) + { + nodesAndTokens.Add(CommaToken().WithTrailingTrivia(endOfLine)); - public static Task WrapBinaryExpressionAsync( - Document document, - BinaryExpressionSyntax condition, - CancellationToken cancellationToken = default) - { - SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(condition, cancellationToken); + nodesAndTokens.Add(en.Current + .TrimTrailingTrivia() + .WithLeadingTrivia(leadingTrivia)); + } + } - leadingTrivia = leadingTrivia.Insert(0, DetermineEndOfLine(condition)); + return AttributeArgumentList( + OpenParenToken().WithTrailingTrivia(endOfLine), + SeparatedList(nodesAndTokens), + argumentList.CloseParenToken.WithoutLeadingTrivia()); + } - var rewriter = new BinaryExpressionToMultiLineRewriter(leadingTrivia); + public static Task WrapBinaryExpressionAsync( + Document document, + BinaryExpressionSyntax condition, + CancellationToken cancellationToken = default) + { + SyntaxTriviaList leadingTrivia = GetIncreasedIndentationTriviaList(condition, cancellationToken); - var newCondition = (ExpressionSyntax)rewriter.Visit(condition); + leadingTrivia = leadingTrivia.Insert(0, DetermineEndOfLine(condition)); - return document.ReplaceNodeAsync(condition, newCondition, cancellationToken); - } + var rewriter = new BinaryExpressionToMultiLineRewriter(leadingTrivia); - public static Task ToMultiLineAsync( - Document document, - AccessorDeclarationSyntax accessor, - CancellationToken cancellationToken = default) - { - AccessorDeclarationSyntax newAccessor = ToMultiLine(accessor); + var newCondition = (ExpressionSyntax)rewriter.Visit(condition); - return document.ReplaceNodeAsync(accessor, newAccessor, cancellationToken); - } + return document.ReplaceNodeAsync(condition, newCondition, cancellationToken); + } - private static AccessorDeclarationSyntax ToMultiLine(AccessorDeclarationSyntax accessor) - { - BlockSyntax body = accessor.Body; + public static Task ToMultiLineAsync( + Document document, + AccessorDeclarationSyntax accessor, + CancellationToken cancellationToken = default) + { + AccessorDeclarationSyntax newAccessor = ToMultiLine(accessor); - if (body != null) + return document.ReplaceNodeAsync(accessor, newAccessor, cancellationToken); + } + + private static AccessorDeclarationSyntax ToMultiLine(AccessorDeclarationSyntax accessor) { - SyntaxToken closeBrace = body.CloseBraceToken; + BlockSyntax body = accessor.Body; - if (!closeBrace.IsMissing) + if (body is not null) { - AccessorDeclarationSyntax newAccessor = accessor - .WithBody( - body.WithCloseBraceToken( - closeBrace.WithLeadingTrivia( - closeBrace.LeadingTrivia.Add(DetermineEndOfLine(accessor))))); + SyntaxToken closeBrace = body.CloseBraceToken; + + if (!closeBrace.IsMissing) + { + AccessorDeclarationSyntax newAccessor = accessor + .WithBody( + body.WithCloseBraceToken( + closeBrace.WithLeadingTrivia( + closeBrace.LeadingTrivia.Add(DetermineEndOfLine(accessor))))); - return newAccessor.WithFormatterAnnotation(); + return newAccessor.WithFormatterAnnotation(); + } } - } - return accessor; + return accessor; + } } } diff --git a/src/CSharp.Workspaces/CSharp/SyntaxInverter.cs b/src/CSharp.Workspaces/CSharp/SyntaxInverter.cs index bfb9b8b433..948ae0cd62 100644 --- a/src/CSharp.Workspaces/CSharp/SyntaxInverter.cs +++ b/src/CSharp.Workspaces/CSharp/SyntaxInverter.cs @@ -9,412 +9,413 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp; - -/// -/// Provides static methods for syntax inversion. -/// -[Obsolete("SyntaxInverter is obsolete, use SyntaxLogicalInverter instead.")] -public static class SyntaxInverter +namespace Roslynator.CSharp { /// - /// Returns new expression that represents logical inversion of the specified expression. + /// Provides static methods for syntax inversion. /// - /// - /// - public static ExpressionSyntax LogicallyInvert( - ExpressionSyntax expression, - CancellationToken cancellationToken = default) + [Obsolete("SyntaxInverter is obsolete, use SyntaxLogicalInverter instead.")] + public static class SyntaxInverter { - return LogicallyInvert(expression, semanticModel: null, cancellationToken); - } + /// + /// Returns new expression that represents logical inversion of the specified expression. + /// + /// + /// + public static ExpressionSyntax LogicallyInvert( + ExpressionSyntax expression, + CancellationToken cancellationToken = default) + { + return LogicallyInvert(expression, semanticModel: null, cancellationToken); + } - /// - /// Returns new expression that represents logical inversion of the specified expression. - /// - /// - /// - /// - public static ExpressionSyntax LogicallyInvert( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (expression == null) - throw new ArgumentNullException(nameof(expression)); + /// + /// Returns new expression that represents logical inversion of the specified expression. + /// + /// + /// + /// + public static ExpressionSyntax LogicallyInvert( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (expression is null) + throw new ArgumentNullException(nameof(expression)); - ExpressionSyntax newExpression = LogicallyInvertImpl(expression, semanticModel, cancellationToken); + ExpressionSyntax newExpression = LogicallyInvertImpl(expression, semanticModel, cancellationToken); - return newExpression.WithTriviaFrom(expression); - } + return newExpression.WithTriviaFrom(expression); + } - private static ParenthesizedExpressionSyntax LogicallyInvertAndParenthesize( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - if (expression == null) - return null; + private static ParenthesizedExpressionSyntax LogicallyInvertAndParenthesize( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + if (expression is null) + return null; - return LogicallyInvertImpl(expression, semanticModel, cancellationToken).Parenthesize(); - } + return LogicallyInvertImpl(expression, semanticModel, cancellationToken).Parenthesize(); + } - private static ExpressionSyntax LogicallyInvertImpl( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - if (expression == null) - return expression; + private static ExpressionSyntax LogicallyInvertImpl( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + if (expression is null) + return expression; - switch (expression.Kind()) + switch (expression.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.InvocationExpression: + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.PostIncrementExpression: + case SyntaxKind.PostDecrementExpression: + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.AnonymousObjectCreationExpression: + case SyntaxKind.TypeOfExpression: + case SyntaxKind.DefaultExpression: + case SyntaxKind.CheckedExpression: + case SyntaxKind.UncheckedExpression: + case SyntaxKind.IdentifierName: + { + return DefaultInvert(expression); + } + case SyntaxKind.LogicalNotExpression: + { + return ((PrefixUnaryExpressionSyntax)expression).Operand; + } + case SyntaxKind.CastExpression: + { + 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); + } + case SyntaxKind.IsExpression: + case SyntaxKind.AsExpression: + case SyntaxKind.IsPatternExpression: + { + return DefaultInvert(expression); + } + case SyntaxKind.EqualsExpression: + case SyntaxKind.NotEqualsExpression: + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression); + } + case SyntaxKind.BitwiseAndExpression: + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); + } + case SyntaxKind.ExclusiveOrExpression: + { + return DefaultInvert(expression); + } + case SyntaxKind.BitwiseOrExpression: + case SyntaxKind.LogicalOrExpression: + case SyntaxKind.LogicalAndExpression: + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); + } + case SyntaxKind.ConditionalExpression: + { + return InvertConditionalExpression((ConditionalExpressionSyntax)expression, semanticModel, cancellationToken); + } + case SyntaxKind.SimpleAssignmentExpression: + case SyntaxKind.AddAssignmentExpression: + case SyntaxKind.SubtractAssignmentExpression: + case SyntaxKind.MultiplyAssignmentExpression: + case SyntaxKind.DivideAssignmentExpression: + case SyntaxKind.ModuloAssignmentExpression: + case SyntaxKind.AndAssignmentExpression: + case SyntaxKind.ExclusiveOrAssignmentExpression: + case SyntaxKind.OrAssignmentExpression: + case SyntaxKind.LeftShiftAssignmentExpression: + case SyntaxKind.RightShiftAssignmentExpression: + { + return DefaultInvert(expression); + } + case SyntaxKind.TrueLiteralExpression: + { + return FalseLiteralExpression(); + } + case SyntaxKind.FalseLiteralExpression: + { + return TrueLiteralExpression(); + } + case SyntaxKind.ParenthesizedExpression: + { + var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; + + ExpressionSyntax expression2 = parenthesizedExpression.Expression; + + if (expression2 is null) + return parenthesizedExpression; + + if (expression2.IsMissing) + return parenthesizedExpression; + + ExpressionSyntax newExpression = LogicallyInvertImpl(expression2, semanticModel, cancellationToken); + + newExpression = newExpression.WithTriviaFrom(expression2); + + return parenthesizedExpression.WithExpression(newExpression); + } + case SyntaxKind.AwaitExpression: + { + return DefaultInvert(expression); + } + } + + Debug.Fail($"Logical inversion of unknown kind '{expression.Kind()}'"); + + return DefaultInvert(expression); + } + + private static ExpressionSyntax InvertLessThanOrGreaterThan( + BinaryExpressionSyntax binaryExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - case SyntaxKind.SimpleMemberAccessExpression: - case SyntaxKind.InvocationExpression: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.PostIncrementExpression: - case SyntaxKind.PostDecrementExpression: - case SyntaxKind.ObjectCreationExpression: - case SyntaxKind.AnonymousObjectCreationExpression: - case SyntaxKind.TypeOfExpression: - case SyntaxKind.DefaultExpression: - case SyntaxKind.CheckedExpression: - case SyntaxKind.UncheckedExpression: - case SyntaxKind.IdentifierName: - { - return DefaultInvert(expression); - } - case SyntaxKind.LogicalNotExpression: - { - return ((PrefixUnaryExpressionSyntax)expression).Operand; - } - case SyntaxKind.CastExpression: - { - return DefaultInvert(expression); - } - case SyntaxKind.LessThanExpression: - case SyntaxKind.LessThanOrEqualExpression: - case SyntaxKind.GreaterThanExpression: - case SyntaxKind.GreaterThanOrEqualExpression: - { - return (semanticModel != null) - ? InvertLessThanOrGreaterThan((BinaryExpressionSyntax)expression, semanticModel, cancellationToken) - : DefaultInvert(expression); - } - case SyntaxKind.IsExpression: - case SyntaxKind.AsExpression: - case SyntaxKind.IsPatternExpression: - { - return DefaultInvert(expression); - } - case SyntaxKind.EqualsExpression: - case SyntaxKind.NotEqualsExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression); - } - case SyntaxKind.BitwiseAndExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); - } - case SyntaxKind.ExclusiveOrExpression: - { - return DefaultInvert(expression); - } - case SyntaxKind.BitwiseOrExpression: - case SyntaxKind.LogicalOrExpression: - case SyntaxKind.LogicalAndExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); - } - case SyntaxKind.ConditionalExpression: - { - return InvertConditionalExpression((ConditionalExpressionSyntax)expression, semanticModel, cancellationToken); - } - case SyntaxKind.SimpleAssignmentExpression: - case SyntaxKind.AddAssignmentExpression: - case SyntaxKind.SubtractAssignmentExpression: - case SyntaxKind.MultiplyAssignmentExpression: - case SyntaxKind.DivideAssignmentExpression: - case SyntaxKind.ModuloAssignmentExpression: - case SyntaxKind.AndAssignmentExpression: - case SyntaxKind.ExclusiveOrAssignmentExpression: - case SyntaxKind.OrAssignmentExpression: - case SyntaxKind.LeftShiftAssignmentExpression: - case SyntaxKind.RightShiftAssignmentExpression: - { - return DefaultInvert(expression); - } - case SyntaxKind.TrueLiteralExpression: + ExpressionSyntax left = binaryExpression.Left; + ExpressionSyntax right = binaryExpression.Right; + + if (IsConstructedFromNullableOfT(left)) + { + if (!IsConstructedFromNullableOfT(right)) { - return FalseLiteralExpression(); + return InvertLessThanGreaterThan(binaryExpression, left, right, isLeft: true); } - case SyntaxKind.FalseLiteralExpression: + else { - return TrueLiteralExpression(); + return DefaultInvert(binaryExpression); } - case SyntaxKind.ParenthesizedExpression: + } + else if (IsConstructedFromNullableOfT(right)) + { + if (semanticModel.HasConstantValue(left, cancellationToken)) { - var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; - - ExpressionSyntax expression2 = parenthesizedExpression.Expression; - - if (expression2 == null) - return parenthesizedExpression; - - if (expression2.IsMissing) - return parenthesizedExpression; - - ExpressionSyntax newExpression = LogicallyInvertImpl(expression2, semanticModel, cancellationToken); - - newExpression = newExpression.WithTriviaFrom(expression2); - - return parenthesizedExpression.WithExpression(newExpression); + return InvertLessThanGreaterThan(binaryExpression, right, left, isLeft: false); } - case SyntaxKind.AwaitExpression: + else { - return DefaultInvert(expression); + return DefaultInvert(binaryExpression); } - } - - Debug.Fail($"Logical inversion of unknown kind '{expression.Kind()}'"); - - return DefaultInvert(expression); - } + } - private static ExpressionSyntax InvertLessThanOrGreaterThan( - BinaryExpressionSyntax binaryExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ExpressionSyntax left = binaryExpression.Left; - ExpressionSyntax right = binaryExpression.Right; + return InvertBinaryExpression(binaryExpression); - if (IsConstructedFromNullableOfT(left)) - { - if (!IsConstructedFromNullableOfT(right)) - { - return InvertLessThanGreaterThan(binaryExpression, left, right, isLeft: true); - } - else + bool IsConstructedFromNullableOfT(ExpressionSyntax expression) { - return DefaultInvert(binaryExpression); + return expression?.IsMissing == false + && expression.Kind() != SyntaxKind.NumericLiteralExpression + && semanticModel + .GetTypeSymbol(expression, cancellationToken)? + .IsNullableType() == true; } } - else if (IsConstructedFromNullableOfT(right)) + + private static ExpressionSyntax InvertLessThanGreaterThan( + BinaryExpressionSyntax binaryExpression, + ExpressionSyntax expression, + ExpressionSyntax otherExpression, + bool isLeft) { - if (semanticModel.HasConstantValue(left, cancellationToken)) + if (expression.Kind() == SyntaxKind.IdentifierName) { - return InvertLessThanGreaterThan(binaryExpression, right, left, isLeft: false); + return LogicalOrExpression( + EqualsExpression(expression, NullLiteralExpression()), + InvertBinaryExpression(binaryExpression)); } - else - { + + if (expression is not ConditionalAccessExpressionSyntax conditionalAccess) return DefaultInvert(binaryExpression); - } - } - return InvertBinaryExpression(binaryExpression); + if (conditionalAccess.Expression.Kind() != SyntaxKind.IdentifierName) + return DefaultInvert(binaryExpression); - bool IsConstructedFromNullableOfT(ExpressionSyntax expression) - { - return expression?.IsMissing == false - && expression.Kind() != SyntaxKind.NumericLiteralExpression - && semanticModel - .GetTypeSymbol(expression, cancellationToken)? - .IsNullableType() == true; - } - } + ExpressionSyntax newExpression = TryCreateExpressionWithoutConditionalAccess(conditionalAccess); + + if (newExpression is null) + return DefaultInvert(binaryExpression); - private static ExpressionSyntax InvertLessThanGreaterThan( - BinaryExpressionSyntax binaryExpression, - ExpressionSyntax expression, - ExpressionSyntax otherExpression, - bool isLeft) - { - if (expression.Kind() == SyntaxKind.IdentifierName) - { return LogicalOrExpression( - EqualsExpression(expression, NullLiteralExpression()), - InvertBinaryExpression(binaryExpression)); + EqualsExpression(conditionalAccess.Expression, NullLiteralExpression()), + binaryExpression.Update( + (isLeft) ? newExpression : otherExpression, + InvertBinaryOperatorToken(binaryExpression.OperatorToken), + (isLeft) ? otherExpression : newExpression)); } - if (expression is not ConditionalAccessExpressionSyntax conditionalAccess) - return DefaultInvert(binaryExpression); - - if (conditionalAccess.Expression.Kind() != SyntaxKind.IdentifierName) - return DefaultInvert(binaryExpression); + private static ExpressionSyntax TryCreateExpressionWithoutConditionalAccess(ConditionalAccessExpressionSyntax conditionalAccess) + { + switch (conditionalAccess.WhenNotNull) + { + case MemberBindingExpressionSyntax memberBinding: + { + return SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name); + } + case ElementBindingExpressionSyntax elementBinding: + { + return ElementAccessExpression(conditionalAccess.Expression, elementBinding.ArgumentList); + } + case InvocationExpressionSyntax invocation: + { + if (invocation.Expression is not MemberBindingExpressionSyntax memberBinding) + return null; + + return InvocationExpression(SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name), invocation.ArgumentList); + } + } - ExpressionSyntax newExpression = TryCreateExpressionWithoutConditionalAccess(conditionalAccess); + return null; + } - if (newExpression == null) - return DefaultInvert(binaryExpression); + internal static BinaryExpressionSyntax InvertBinaryExpression(BinaryExpressionSyntax binaryExpression) + { + SyntaxToken operatorToken = InvertBinaryOperatorToken(binaryExpression.OperatorToken); - return LogicalOrExpression( - EqualsExpression(conditionalAccess.Expression, NullLiteralExpression()), - binaryExpression.Update( - (isLeft) ? newExpression : otherExpression, - InvertBinaryOperatorToken(binaryExpression.OperatorToken), - (isLeft) ? otherExpression : newExpression)); - } + return binaryExpression.WithOperatorToken(operatorToken); + } - private static ExpressionSyntax TryCreateExpressionWithoutConditionalAccess(ConditionalAccessExpressionSyntax conditionalAccess) - { - switch (conditionalAccess.WhenNotNull) + private static SyntaxToken InvertBinaryOperatorToken(SyntaxToken operatorToken) { - case MemberBindingExpressionSyntax memberBinding: - { - return SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name); - } - case ElementBindingExpressionSyntax elementBinding: + return Token( + operatorToken.LeadingTrivia, + InvertBinaryOperator(operatorToken.Kind()), + operatorToken.TrailingTrivia); + + static SyntaxKind InvertBinaryOperator(SyntaxKind kind) + { + switch (kind) { - return ElementAccessExpression(conditionalAccess.Expression, elementBinding.ArgumentList); + case SyntaxKind.LessThanToken: + return SyntaxKind.GreaterThanEqualsToken; + case SyntaxKind.LessThanEqualsToken: + return SyntaxKind.GreaterThanToken; + case SyntaxKind.GreaterThanToken: + return SyntaxKind.LessThanEqualsToken; + case SyntaxKind.GreaterThanEqualsToken: + return SyntaxKind.LessThanToken; + case SyntaxKind.EqualsEqualsToken: + return SyntaxKind.ExclamationEqualsToken; + case SyntaxKind.ExclamationEqualsToken: + return SyntaxKind.EqualsEqualsToken; + case SyntaxKind.AmpersandToken: + return SyntaxKind.BarToken; + case SyntaxKind.BarToken: + return SyntaxKind.AmpersandToken; + case SyntaxKind.BarBarToken: + return SyntaxKind.AmpersandAmpersandToken; + case SyntaxKind.AmpersandAmpersandToken: + return SyntaxKind.BarBarToken; } - case InvocationExpressionSyntax invocation: - { - if (invocation.Expression is not MemberBindingExpressionSyntax memberBinding) - return null; - return InvocationExpression(SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name), invocation.ArgumentList); - } + Debug.Fail(kind.ToString()); + return kind; + } } - return null; - } + private static BinaryExpressionSyntax InvertBinaryExpression( + BinaryExpressionSyntax binaryExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + ExpressionSyntax left = binaryExpression.Left; + ExpressionSyntax right = binaryExpression.Right; + SyntaxToken operatorToken = binaryExpression.OperatorToken; - internal static BinaryExpressionSyntax InvertBinaryExpression(BinaryExpressionSyntax binaryExpression) - { - SyntaxToken operatorToken = InvertBinaryOperatorToken(binaryExpression.OperatorToken); + SyntaxKind kind = InvertBinaryExpressionKind(binaryExpression.Kind()); - return binaryExpression.WithOperatorToken(operatorToken); - } + left = LogicallyInvertAndParenthesize(left, semanticModel, cancellationToken); - private static SyntaxToken InvertBinaryOperatorToken(SyntaxToken operatorToken) - { - return Token( - operatorToken.LeadingTrivia, - InvertBinaryOperator(operatorToken.Kind()), - operatorToken.TrailingTrivia); + right = LogicallyInvertAndParenthesize(right, semanticModel, cancellationToken); + + BinaryExpressionSyntax newBinaryExpression = BinaryExpression( + kind, + left, + InvertBinaryOperatorToken(operatorToken), + right); - static SyntaxKind InvertBinaryOperator(SyntaxKind kind) + return newBinaryExpression.WithTriviaFrom(binaryExpression); + } + + private static SyntaxKind InvertBinaryExpressionKind(SyntaxKind kind) { switch (kind) { - case SyntaxKind.LessThanToken: - return SyntaxKind.GreaterThanEqualsToken; - case SyntaxKind.LessThanEqualsToken: - return SyntaxKind.GreaterThanToken; - case SyntaxKind.GreaterThanToken: - return SyntaxKind.LessThanEqualsToken; - case SyntaxKind.GreaterThanEqualsToken: - return SyntaxKind.LessThanToken; - case SyntaxKind.EqualsEqualsToken: - return SyntaxKind.ExclamationEqualsToken; - case SyntaxKind.ExclamationEqualsToken: - return SyntaxKind.EqualsEqualsToken; - case SyntaxKind.AmpersandToken: - return SyntaxKind.BarToken; - case SyntaxKind.BarToken: - return SyntaxKind.AmpersandToken; - case SyntaxKind.BarBarToken: - return SyntaxKind.AmpersandAmpersandToken; - case SyntaxKind.AmpersandAmpersandToken: - return SyntaxKind.BarBarToken; + case SyntaxKind.LessThanExpression: + return SyntaxKind.GreaterThanOrEqualExpression; + case SyntaxKind.LessThanOrEqualExpression: + return SyntaxKind.GreaterThanExpression; + case SyntaxKind.GreaterThanExpression: + return SyntaxKind.LessThanOrEqualExpression; + case SyntaxKind.GreaterThanOrEqualExpression: + return SyntaxKind.LessThanExpression; + case SyntaxKind.EqualsExpression: + return SyntaxKind.NotEqualsExpression; + case SyntaxKind.NotEqualsExpression: + return SyntaxKind.EqualsExpression; + case SyntaxKind.BitwiseAndExpression: + return SyntaxKind.BitwiseOrExpression; + case SyntaxKind.BitwiseOrExpression: + return SyntaxKind.BitwiseAndExpression; + case SyntaxKind.LogicalOrExpression: + return SyntaxKind.LogicalAndExpression; + case SyntaxKind.LogicalAndExpression: + return SyntaxKind.LogicalOrExpression; } Debug.Fail(kind.ToString()); return kind; } - } - - private static BinaryExpressionSyntax InvertBinaryExpression( - BinaryExpressionSyntax binaryExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ExpressionSyntax left = binaryExpression.Left; - ExpressionSyntax right = binaryExpression.Right; - SyntaxToken operatorToken = binaryExpression.OperatorToken; - - SyntaxKind kind = InvertBinaryExpressionKind(binaryExpression.Kind()); - - left = LogicallyInvertAndParenthesize(left, semanticModel, cancellationToken); - - right = LogicallyInvertAndParenthesize(right, semanticModel, cancellationToken); - BinaryExpressionSyntax newBinaryExpression = BinaryExpression( - kind, - left, - InvertBinaryOperatorToken(operatorToken), - right); - - return newBinaryExpression.WithTriviaFrom(binaryExpression); - } - - private static SyntaxKind InvertBinaryExpressionKind(SyntaxKind kind) - { - switch (kind) + private static ConditionalExpressionSyntax InvertConditionalExpression( + ConditionalExpressionSyntax conditionalExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - case SyntaxKind.LessThanExpression: - return SyntaxKind.GreaterThanOrEqualExpression; - case SyntaxKind.LessThanOrEqualExpression: - return SyntaxKind.GreaterThanExpression; - case SyntaxKind.GreaterThanExpression: - return SyntaxKind.LessThanOrEqualExpression; - case SyntaxKind.GreaterThanOrEqualExpression: - return SyntaxKind.LessThanExpression; - case SyntaxKind.EqualsExpression: - return SyntaxKind.NotEqualsExpression; - case SyntaxKind.NotEqualsExpression: - return SyntaxKind.EqualsExpression; - case SyntaxKind.BitwiseAndExpression: - return SyntaxKind.BitwiseOrExpression; - case SyntaxKind.BitwiseOrExpression: - return SyntaxKind.BitwiseAndExpression; - case SyntaxKind.LogicalOrExpression: - return SyntaxKind.LogicalAndExpression; - case SyntaxKind.LogicalAndExpression: - return SyntaxKind.LogicalOrExpression; - } + ExpressionSyntax whenTrue = conditionalExpression.WhenTrue; + ExpressionSyntax whenFalse = conditionalExpression.WhenFalse; - Debug.Fail(kind.ToString()); - return kind; - } + if (whenTrue?.IsKind(SyntaxKind.ThrowExpression) == false) + { + whenTrue = LogicallyInvertAndParenthesize(whenTrue, semanticModel, cancellationToken); + } - private static ConditionalExpressionSyntax InvertConditionalExpression( - ConditionalExpressionSyntax conditionalExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ExpressionSyntax whenTrue = conditionalExpression.WhenTrue; - ExpressionSyntax whenFalse = conditionalExpression.WhenFalse; + if (whenFalse?.IsKind(SyntaxKind.ThrowExpression) == false) + { + whenFalse = LogicallyInvertAndParenthesize(whenFalse, semanticModel, cancellationToken); + } - if (whenTrue?.IsKind(SyntaxKind.ThrowExpression) == false) - { - whenTrue = LogicallyInvertAndParenthesize(whenTrue, semanticModel, cancellationToken); - } + ConditionalExpressionSyntax newConditionalExpression = conditionalExpression.Update( + conditionalExpression.Condition, + conditionalExpression.QuestionToken, + whenTrue, + conditionalExpression.ColonToken, + whenFalse); - if (whenFalse?.IsKind(SyntaxKind.ThrowExpression) == false) - { - whenFalse = LogicallyInvertAndParenthesize(whenFalse, semanticModel, cancellationToken); + return newConditionalExpression.WithTriviaFrom(conditionalExpression); } - ConditionalExpressionSyntax newConditionalExpression = conditionalExpression.Update( - conditionalExpression.Condition, - conditionalExpression.QuestionToken, - whenTrue, - conditionalExpression.ColonToken, - whenFalse); - - return newConditionalExpression.WithTriviaFrom(conditionalExpression); - } - - private static PrefixUnaryExpressionSyntax DefaultInvert(ExpressionSyntax expression) - { - SyntaxDebug.Assert(expression.Kind() != SyntaxKind.ParenthesizedExpression, expression); + private static PrefixUnaryExpressionSyntax DefaultInvert(ExpressionSyntax expression) + { + SyntaxDebug.Assert(expression.Kind() != SyntaxKind.ParenthesizedExpression, expression); - SyntaxTriviaList leadingTrivia = expression.GetLeadingTrivia(); + SyntaxTriviaList leadingTrivia = expression.GetLeadingTrivia(); - return LogicalNotExpression( - expression.WithoutLeadingTrivia().Parenthesize(), - Token(leadingTrivia, SyntaxKind.ExclamationToken, SyntaxTriviaList.Empty)); + return LogicalNotExpression( + expression.WithoutLeadingTrivia().Parenthesize(), + Token(leadingTrivia, SyntaxKind.ExclamationToken, SyntaxTriviaList.Empty)); + } } } diff --git a/src/CSharp.Workspaces/CSharp/SyntaxLogicalInverter.cs b/src/CSharp.Workspaces/CSharp/SyntaxLogicalInverter.cs index a295334f01..39a6bac844 100644 --- a/src/CSharp.Workspaces/CSharp/SyntaxLogicalInverter.cs +++ b/src/CSharp.Workspaces/CSharp/SyntaxLogicalInverter.cs @@ -11,501 +11,502 @@ #pragma warning disable RCS1223 -namespace Roslynator.CSharp; - -/// -/// Provides static methods for syntax inversion. -/// -public class SyntaxLogicalInverter +namespace Roslynator.CSharp { - public static SyntaxLogicalInverter Default { get; } = new(SyntaxLogicalInverterOptions.Default); + /// + /// Provides static methods for syntax inversion. + /// + public class SyntaxLogicalInverter + { + public static SyntaxLogicalInverter Default { get; } = new(SyntaxLogicalInverterOptions.Default); - internal static SyntaxLogicalInverter CSharp8 { get; } = new(SyntaxLogicalInverterOptions.CSharp8); + internal static SyntaxLogicalInverter CSharp8 { get; } = new(SyntaxLogicalInverterOptions.CSharp8); - public SyntaxLogicalInverter(SyntaxLogicalInverterOptions options) - { - Options = options ?? throw new ArgumentNullException(nameof(options)); - } + public SyntaxLogicalInverter(SyntaxLogicalInverterOptions options) + { + Options = options ?? throw new ArgumentNullException(nameof(options)); + } - public SyntaxLogicalInverterOptions Options { get; } + public SyntaxLogicalInverterOptions Options { get; } - internal static SyntaxLogicalInverter GetInstance(Document document) - { - return (document.SupportsLanguageFeature(CSharpLanguageFeature.NotPattern)) - ? Default - : CSharp8; - } + internal static SyntaxLogicalInverter GetInstance(Document document) + { + return (document.SupportsLanguageFeature(CSharpLanguageFeature.NotPattern)) + ? Default + : CSharp8; + } - /// - /// Returns new expression that represents logical inversion of the specified expression. - /// - /// - /// - public ExpressionSyntax LogicallyInvert( - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - return LogicallyInvert(expression, semanticModel: null, cancellationToken); - } + /// + /// Returns new expression that represents logical inversion of the specified expression. + /// + /// + /// + public ExpressionSyntax LogicallyInvert( + ExpressionSyntax expression, + CancellationToken cancellationToken = default) + { + return LogicallyInvert(expression, semanticModel: null, cancellationToken); + } - /// - /// Returns new expression that represents logical inversion of the specified expression. - /// - /// - /// - /// - public ExpressionSyntax LogicallyInvert( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (expression == null) - throw new ArgumentNullException(nameof(expression)); + /// + /// Returns new expression that represents logical inversion of the specified expression. + /// + /// + /// + /// + public ExpressionSyntax LogicallyInvert( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (expression is null) + throw new ArgumentNullException(nameof(expression)); - ExpressionSyntax newExpression = LogicallyInvertImpl(expression, semanticModel, cancellationToken); + ExpressionSyntax newExpression = LogicallyInvertImpl(expression, semanticModel, cancellationToken); - return newExpression.WithTriviaFrom(expression); - } + return newExpression.WithTriviaFrom(expression); + } - private ParenthesizedExpressionSyntax LogicallyInvertAndParenthesize( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - if (expression == null) - return null; + private ParenthesizedExpressionSyntax LogicallyInvertAndParenthesize( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + if (expression is null) + return null; - return LogicallyInvertImpl(expression, semanticModel, cancellationToken).Parenthesize(); - } + return LogicallyInvertImpl(expression, semanticModel, cancellationToken).Parenthesize(); + } - private ExpressionSyntax LogicallyInvertImpl( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - if (expression == null) - return expression; + private ExpressionSyntax LogicallyInvertImpl( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + if (expression is null) + return expression; + + switch (expression.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.InvocationExpression: + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.PostIncrementExpression: + case SyntaxKind.PostDecrementExpression: + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.AnonymousObjectCreationExpression: + case SyntaxKind.TypeOfExpression: + case SyntaxKind.DefaultExpression: + case SyntaxKind.CheckedExpression: + case SyntaxKind.UncheckedExpression: + case SyntaxKind.IdentifierName: + { + return DefaultInvert(expression); + } + case SyntaxKind.LogicalNotExpression: + { + return ((PrefixUnaryExpressionSyntax)expression).Operand; + } + case SyntaxKind.CastExpression: + { + 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); + } + case SyntaxKind.IsExpression: + { + var isExpression = (BinaryExpressionSyntax)expression; + + return IsPatternExpression( + isExpression.Left, + isExpression.OperatorToken.WithTrailingTrivia(Space), + UnaryPattern( + Token(SyntaxKind.NotKeyword).WithTrailingTrivia(isExpression.OperatorToken.TrailingTrivia), + TypePattern((TypeSyntax)isExpression.Right))); + } + case SyntaxKind.AsExpression: + { + return DefaultInvert(expression); + } + case SyntaxKind.IsPatternExpression: + { + return (Options.UseNotPattern) + ? InvertIsPattern((IsPatternExpressionSyntax)expression) + : DefaultInvert(expression); + } + case SyntaxKind.EqualsExpression: + case SyntaxKind.NotEqualsExpression: + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression); + } + case SyntaxKind.BitwiseAndExpression: + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); + } + case SyntaxKind.ExclusiveOrExpression: + { + return DefaultInvert(expression); + } + case SyntaxKind.BitwiseOrExpression: + case SyntaxKind.LogicalOrExpression: + case SyntaxKind.LogicalAndExpression: + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); + } + case SyntaxKind.ConditionalExpression: + { + return InvertConditionalExpression((ConditionalExpressionSyntax)expression, semanticModel, cancellationToken); + } + case SyntaxKind.SimpleAssignmentExpression: + case SyntaxKind.AddAssignmentExpression: + case SyntaxKind.SubtractAssignmentExpression: + case SyntaxKind.MultiplyAssignmentExpression: + case SyntaxKind.DivideAssignmentExpression: + case SyntaxKind.ModuloAssignmentExpression: + case SyntaxKind.AndAssignmentExpression: + case SyntaxKind.ExclusiveOrAssignmentExpression: + case SyntaxKind.OrAssignmentExpression: + case SyntaxKind.LeftShiftAssignmentExpression: + case SyntaxKind.RightShiftAssignmentExpression: + { + return DefaultInvert(expression); + } + case SyntaxKind.TrueLiteralExpression: + { + return FalseLiteralExpression(); + } + case SyntaxKind.FalseLiteralExpression: + { + return TrueLiteralExpression(); + } + case SyntaxKind.ParenthesizedExpression: + { + var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; + + ExpressionSyntax expression2 = parenthesizedExpression.Expression; + + if (expression2 is null) + return parenthesizedExpression; + + if (expression2.IsMissing) + return parenthesizedExpression; + + ExpressionSyntax newExpression = LogicallyInvertImpl(expression2, semanticModel, cancellationToken); + + newExpression = newExpression.WithTriviaFrom(expression2); + + return parenthesizedExpression.WithExpression(newExpression); + } + case SyntaxKind.AwaitExpression: + { + return DefaultInvert(expression); + } + } - switch (expression.Kind()) + Debug.Fail($"Logical inversion of unknown kind '{expression.Kind()}'"); + + return DefaultInvert(expression); + } + + private ExpressionSyntax InvertLessThanOrGreaterThan( + BinaryExpressionSyntax binaryExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - case SyntaxKind.SimpleMemberAccessExpression: - case SyntaxKind.InvocationExpression: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.PostIncrementExpression: - case SyntaxKind.PostDecrementExpression: - case SyntaxKind.ObjectCreationExpression: - case SyntaxKind.AnonymousObjectCreationExpression: - case SyntaxKind.TypeOfExpression: - case SyntaxKind.DefaultExpression: - case SyntaxKind.CheckedExpression: - case SyntaxKind.UncheckedExpression: - case SyntaxKind.IdentifierName: - { - return DefaultInvert(expression); - } - case SyntaxKind.LogicalNotExpression: - { - return ((PrefixUnaryExpressionSyntax)expression).Operand; - } - case SyntaxKind.CastExpression: - { - return DefaultInvert(expression); - } - case SyntaxKind.LessThanExpression: - case SyntaxKind.LessThanOrEqualExpression: - case SyntaxKind.GreaterThanExpression: - case SyntaxKind.GreaterThanOrEqualExpression: - { - return (semanticModel != null) - ? InvertLessThanOrGreaterThan((BinaryExpressionSyntax)expression, semanticModel, cancellationToken) - : DefaultInvert(expression); - } - case SyntaxKind.IsExpression: - { - var isExpression = (BinaryExpressionSyntax)expression; + ExpressionSyntax left = binaryExpression.Left; + ExpressionSyntax right = binaryExpression.Right; - return IsPatternExpression( - isExpression.Left, - isExpression.OperatorToken.WithTrailingTrivia(Space), - UnaryPattern( - Token(SyntaxKind.NotKeyword).WithTrailingTrivia(isExpression.OperatorToken.TrailingTrivia), - TypePattern((TypeSyntax)isExpression.Right))); - } - case SyntaxKind.AsExpression: - { - return DefaultInvert(expression); - } - case SyntaxKind.IsPatternExpression: - { - return (Options.UseNotPattern) - ? InvertIsPattern((IsPatternExpressionSyntax)expression) - : DefaultInvert(expression); - } - case SyntaxKind.EqualsExpression: - case SyntaxKind.NotEqualsExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression); - } - case SyntaxKind.BitwiseAndExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); - } - case SyntaxKind.ExclusiveOrExpression: - { - return DefaultInvert(expression); - } - case SyntaxKind.BitwiseOrExpression: - case SyntaxKind.LogicalOrExpression: - case SyntaxKind.LogicalAndExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); - } - case SyntaxKind.ConditionalExpression: - { - return InvertConditionalExpression((ConditionalExpressionSyntax)expression, semanticModel, cancellationToken); - } - case SyntaxKind.SimpleAssignmentExpression: - case SyntaxKind.AddAssignmentExpression: - case SyntaxKind.SubtractAssignmentExpression: - case SyntaxKind.MultiplyAssignmentExpression: - case SyntaxKind.DivideAssignmentExpression: - case SyntaxKind.ModuloAssignmentExpression: - case SyntaxKind.AndAssignmentExpression: - case SyntaxKind.ExclusiveOrAssignmentExpression: - case SyntaxKind.OrAssignmentExpression: - case SyntaxKind.LeftShiftAssignmentExpression: - case SyntaxKind.RightShiftAssignmentExpression: - { - return DefaultInvert(expression); - } - case SyntaxKind.TrueLiteralExpression: + if (IsConstructedFromNullableOfT(left)) + { + if (!IsConstructedFromNullableOfT(right)) { - return FalseLiteralExpression(); + return InvertLessThanGreaterThan(binaryExpression, left, right, isLeft: true); } - case SyntaxKind.FalseLiteralExpression: + else { - return TrueLiteralExpression(); + return DefaultInvert(binaryExpression); } - case SyntaxKind.ParenthesizedExpression: + } + else if (IsConstructedFromNullableOfT(right)) + { + if (semanticModel.HasConstantValue(left, cancellationToken)) { - var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; - - ExpressionSyntax expression2 = parenthesizedExpression.Expression; - - if (expression2 == null) - return parenthesizedExpression; - - if (expression2.IsMissing) - return parenthesizedExpression; - - ExpressionSyntax newExpression = LogicallyInvertImpl(expression2, semanticModel, cancellationToken); - - newExpression = newExpression.WithTriviaFrom(expression2); - - return parenthesizedExpression.WithExpression(newExpression); + return InvertLessThanGreaterThan(binaryExpression, right, left, isLeft: false); } - case SyntaxKind.AwaitExpression: + else { - return DefaultInvert(expression); + return DefaultInvert(binaryExpression); } - } - - Debug.Fail($"Logical inversion of unknown kind '{expression.Kind()}'"); - - return DefaultInvert(expression); - } + } - private ExpressionSyntax InvertLessThanOrGreaterThan( - BinaryExpressionSyntax binaryExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ExpressionSyntax left = binaryExpression.Left; - ExpressionSyntax right = binaryExpression.Right; + return InvertBinaryExpression(binaryExpression); - if (IsConstructedFromNullableOfT(left)) - { - if (!IsConstructedFromNullableOfT(right)) + bool IsConstructedFromNullableOfT(ExpressionSyntax expression) { - return InvertLessThanGreaterThan(binaryExpression, left, right, isLeft: true); - } - else - { - return DefaultInvert(binaryExpression); + return expression?.IsMissing == false + && expression.Kind() != SyntaxKind.NumericLiteralExpression + && semanticModel + .GetTypeSymbol(expression, cancellationToken)? + .IsNullableType() == true; } } - else if (IsConstructedFromNullableOfT(right)) + + private ExpressionSyntax InvertLessThanGreaterThan( + BinaryExpressionSyntax binaryExpression, + ExpressionSyntax expression, + ExpressionSyntax otherExpression, + bool isLeft) { - if (semanticModel.HasConstantValue(left, cancellationToken)) + if (expression.Kind() == SyntaxKind.IdentifierName) { - return InvertLessThanGreaterThan(binaryExpression, right, left, isLeft: false); + return LogicalOrExpression( + EqualsExpression(expression, NullLiteralExpression()), + InvertBinaryExpression(binaryExpression)); } - else - { + + if (expression is not ConditionalAccessExpressionSyntax conditionalAccess) return DefaultInvert(binaryExpression); - } - } - return InvertBinaryExpression(binaryExpression); + if (conditionalAccess.Expression.Kind() != SyntaxKind.IdentifierName) + return DefaultInvert(binaryExpression); - bool IsConstructedFromNullableOfT(ExpressionSyntax expression) - { - return expression?.IsMissing == false - && expression.Kind() != SyntaxKind.NumericLiteralExpression - && semanticModel - .GetTypeSymbol(expression, cancellationToken)? - .IsNullableType() == true; - } - } + ExpressionSyntax newExpression = TryCreateExpressionWithoutConditionalAccess(conditionalAccess); + + if (newExpression is null) + return DefaultInvert(binaryExpression); - private ExpressionSyntax InvertLessThanGreaterThan( - BinaryExpressionSyntax binaryExpression, - ExpressionSyntax expression, - ExpressionSyntax otherExpression, - bool isLeft) - { - if (expression.Kind() == SyntaxKind.IdentifierName) - { return LogicalOrExpression( - EqualsExpression(expression, NullLiteralExpression()), - InvertBinaryExpression(binaryExpression)); + EqualsExpression(conditionalAccess.Expression, NullLiteralExpression()), + binaryExpression.Update( + (isLeft) ? newExpression : otherExpression, + InvertBinaryOperatorToken(binaryExpression.OperatorToken), + (isLeft) ? otherExpression : newExpression)); } - if (expression is not ConditionalAccessExpressionSyntax conditionalAccess) - return DefaultInvert(binaryExpression); - - if (conditionalAccess.Expression.Kind() != SyntaxKind.IdentifierName) - return DefaultInvert(binaryExpression); + private static ExpressionSyntax TryCreateExpressionWithoutConditionalAccess(ConditionalAccessExpressionSyntax conditionalAccess) + { + switch (conditionalAccess.WhenNotNull) + { + case MemberBindingExpressionSyntax memberBinding: + { + return SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name); + } + case ElementBindingExpressionSyntax elementBinding: + { + return ElementAccessExpression(conditionalAccess.Expression, elementBinding.ArgumentList); + } + case InvocationExpressionSyntax invocation: + { + if (invocation.Expression is not MemberBindingExpressionSyntax memberBinding) + return null; + + return InvocationExpression(SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name), invocation.ArgumentList); + } + } - ExpressionSyntax newExpression = TryCreateExpressionWithoutConditionalAccess(conditionalAccess); + return null; + } - if (newExpression == null) - return DefaultInvert(binaryExpression); + internal BinaryExpressionSyntax InvertBinaryExpression(BinaryExpressionSyntax binaryExpression) + { + SyntaxToken operatorToken = InvertBinaryOperatorToken(binaryExpression.OperatorToken); - return LogicalOrExpression( - EqualsExpression(conditionalAccess.Expression, NullLiteralExpression()), - binaryExpression.Update( - (isLeft) ? newExpression : otherExpression, - InvertBinaryOperatorToken(binaryExpression.OperatorToken), - (isLeft) ? otherExpression : newExpression)); - } + return binaryExpression.WithOperatorToken(operatorToken); + } - private static ExpressionSyntax TryCreateExpressionWithoutConditionalAccess(ConditionalAccessExpressionSyntax conditionalAccess) - { - switch (conditionalAccess.WhenNotNull) + private static SyntaxToken InvertBinaryOperatorToken(SyntaxToken operatorToken) { - case MemberBindingExpressionSyntax memberBinding: - { - return SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name); - } - case ElementBindingExpressionSyntax elementBinding: + return Token( + operatorToken.LeadingTrivia, + InvertBinaryOperator(operatorToken.Kind()), + operatorToken.TrailingTrivia); + + static SyntaxKind InvertBinaryOperator(SyntaxKind kind) + { + switch (kind) { - return ElementAccessExpression(conditionalAccess.Expression, elementBinding.ArgumentList); + case SyntaxKind.LessThanToken: + return SyntaxKind.GreaterThanEqualsToken; + case SyntaxKind.LessThanEqualsToken: + return SyntaxKind.GreaterThanToken; + case SyntaxKind.GreaterThanToken: + return SyntaxKind.LessThanEqualsToken; + case SyntaxKind.GreaterThanEqualsToken: + return SyntaxKind.LessThanToken; + case SyntaxKind.EqualsEqualsToken: + return SyntaxKind.ExclamationEqualsToken; + case SyntaxKind.ExclamationEqualsToken: + return SyntaxKind.EqualsEqualsToken; + case SyntaxKind.AmpersandToken: + return SyntaxKind.BarToken; + case SyntaxKind.BarToken: + return SyntaxKind.AmpersandToken; + case SyntaxKind.BarBarToken: + return SyntaxKind.AmpersandAmpersandToken; + case SyntaxKind.AmpersandAmpersandToken: + return SyntaxKind.BarBarToken; } - case InvocationExpressionSyntax invocation: - { - if (invocation.Expression is not MemberBindingExpressionSyntax memberBinding) - return null; - return InvocationExpression(SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name), invocation.ArgumentList); - } + Debug.Fail(kind.ToString()); + return kind; + } } - return null; - } + private BinaryExpressionSyntax InvertBinaryExpression( + BinaryExpressionSyntax binaryExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + ExpressionSyntax left = binaryExpression.Left; + ExpressionSyntax right = binaryExpression.Right; + SyntaxToken operatorToken = binaryExpression.OperatorToken; - internal BinaryExpressionSyntax InvertBinaryExpression(BinaryExpressionSyntax binaryExpression) - { - SyntaxToken operatorToken = InvertBinaryOperatorToken(binaryExpression.OperatorToken); + SyntaxKind kind = InvertBinaryExpressionKind(binaryExpression.Kind()); - return binaryExpression.WithOperatorToken(operatorToken); - } + left = LogicallyInvertAndParenthesize(left, semanticModel, cancellationToken); - private static SyntaxToken InvertBinaryOperatorToken(SyntaxToken operatorToken) - { - return Token( - operatorToken.LeadingTrivia, - InvertBinaryOperator(operatorToken.Kind()), - operatorToken.TrailingTrivia); + right = LogicallyInvertAndParenthesize(right, semanticModel, cancellationToken); + + BinaryExpressionSyntax newBinaryExpression = BinaryExpression( + kind, + left, + InvertBinaryOperatorToken(operatorToken), + right); - static SyntaxKind InvertBinaryOperator(SyntaxKind kind) + return newBinaryExpression.WithTriviaFrom(binaryExpression); + } + + private static SyntaxKind InvertBinaryExpressionKind(SyntaxKind kind) { switch (kind) { - case SyntaxKind.LessThanToken: - return SyntaxKind.GreaterThanEqualsToken; - case SyntaxKind.LessThanEqualsToken: - return SyntaxKind.GreaterThanToken; - case SyntaxKind.GreaterThanToken: - return SyntaxKind.LessThanEqualsToken; - case SyntaxKind.GreaterThanEqualsToken: - return SyntaxKind.LessThanToken; - case SyntaxKind.EqualsEqualsToken: - return SyntaxKind.ExclamationEqualsToken; - case SyntaxKind.ExclamationEqualsToken: - return SyntaxKind.EqualsEqualsToken; - case SyntaxKind.AmpersandToken: - return SyntaxKind.BarToken; - case SyntaxKind.BarToken: - return SyntaxKind.AmpersandToken; - case SyntaxKind.BarBarToken: - return SyntaxKind.AmpersandAmpersandToken; - case SyntaxKind.AmpersandAmpersandToken: - return SyntaxKind.BarBarToken; + case SyntaxKind.LessThanExpression: + return SyntaxKind.GreaterThanOrEqualExpression; + case SyntaxKind.LessThanOrEqualExpression: + return SyntaxKind.GreaterThanExpression; + case SyntaxKind.GreaterThanExpression: + return SyntaxKind.LessThanOrEqualExpression; + case SyntaxKind.GreaterThanOrEqualExpression: + return SyntaxKind.LessThanExpression; + case SyntaxKind.EqualsExpression: + return SyntaxKind.NotEqualsExpression; + case SyntaxKind.NotEqualsExpression: + return SyntaxKind.EqualsExpression; + case SyntaxKind.BitwiseAndExpression: + return SyntaxKind.BitwiseOrExpression; + case SyntaxKind.BitwiseOrExpression: + return SyntaxKind.BitwiseAndExpression; + case SyntaxKind.LogicalOrExpression: + return SyntaxKind.LogicalAndExpression; + case SyntaxKind.LogicalAndExpression: + return SyntaxKind.LogicalOrExpression; } Debug.Fail(kind.ToString()); return kind; } - } - private BinaryExpressionSyntax InvertBinaryExpression( - BinaryExpressionSyntax binaryExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ExpressionSyntax left = binaryExpression.Left; - ExpressionSyntax right = binaryExpression.Right; - SyntaxToken operatorToken = binaryExpression.OperatorToken; - - SyntaxKind kind = InvertBinaryExpressionKind(binaryExpression.Kind()); - - left = LogicallyInvertAndParenthesize(left, semanticModel, cancellationToken); - - right = LogicallyInvertAndParenthesize(right, semanticModel, cancellationToken); - - BinaryExpressionSyntax newBinaryExpression = BinaryExpression( - kind, - left, - InvertBinaryOperatorToken(operatorToken), - right); - - return newBinaryExpression.WithTriviaFrom(binaryExpression); - } - - private static SyntaxKind InvertBinaryExpressionKind(SyntaxKind kind) - { - switch (kind) + private ConditionalExpressionSyntax InvertConditionalExpression( + ConditionalExpressionSyntax conditionalExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - case SyntaxKind.LessThanExpression: - return SyntaxKind.GreaterThanOrEqualExpression; - case SyntaxKind.LessThanOrEqualExpression: - return SyntaxKind.GreaterThanExpression; - case SyntaxKind.GreaterThanExpression: - return SyntaxKind.LessThanOrEqualExpression; - case SyntaxKind.GreaterThanOrEqualExpression: - return SyntaxKind.LessThanExpression; - case SyntaxKind.EqualsExpression: - return SyntaxKind.NotEqualsExpression; - case SyntaxKind.NotEqualsExpression: - return SyntaxKind.EqualsExpression; - case SyntaxKind.BitwiseAndExpression: - return SyntaxKind.BitwiseOrExpression; - case SyntaxKind.BitwiseOrExpression: - return SyntaxKind.BitwiseAndExpression; - case SyntaxKind.LogicalOrExpression: - return SyntaxKind.LogicalAndExpression; - case SyntaxKind.LogicalAndExpression: - return SyntaxKind.LogicalOrExpression; - } + ExpressionSyntax whenTrue = conditionalExpression.WhenTrue; + ExpressionSyntax whenFalse = conditionalExpression.WhenFalse; - Debug.Fail(kind.ToString()); - return kind; - } + if (whenTrue?.IsKind(SyntaxKind.ThrowExpression) == false) + { + whenTrue = LogicallyInvertAndParenthesize(whenTrue, semanticModel, cancellationToken); + } - private ConditionalExpressionSyntax InvertConditionalExpression( - ConditionalExpressionSyntax conditionalExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ExpressionSyntax whenTrue = conditionalExpression.WhenTrue; - ExpressionSyntax whenFalse = conditionalExpression.WhenFalse; + if (whenFalse?.IsKind(SyntaxKind.ThrowExpression) == false) + { + whenFalse = LogicallyInvertAndParenthesize(whenFalse, semanticModel, cancellationToken); + } - if (whenTrue?.IsKind(SyntaxKind.ThrowExpression) == false) - { - whenTrue = LogicallyInvertAndParenthesize(whenTrue, semanticModel, cancellationToken); - } + ConditionalExpressionSyntax newConditionalExpression = conditionalExpression.Update( + conditionalExpression.Condition, + conditionalExpression.QuestionToken, + whenTrue, + conditionalExpression.ColonToken, + whenFalse); - if (whenFalse?.IsKind(SyntaxKind.ThrowExpression) == false) - { - whenFalse = LogicallyInvertAndParenthesize(whenFalse, semanticModel, cancellationToken); + return newConditionalExpression.WithTriviaFrom(conditionalExpression); } - ConditionalExpressionSyntax newConditionalExpression = conditionalExpression.Update( - conditionalExpression.Condition, - conditionalExpression.QuestionToken, - whenTrue, - conditionalExpression.ColonToken, - whenFalse); - - return newConditionalExpression.WithTriviaFrom(conditionalExpression); - } - - private ExpressionSyntax InvertIsPattern(IsPatternExpressionSyntax isPattern) - { - PatternSyntax pattern = isPattern.Pattern; - - if (pattern.IsKind(SyntaxKind.NotPattern)) + private ExpressionSyntax InvertIsPattern(IsPatternExpressionSyntax isPattern) { - var notPattern = (UnaryPatternSyntax)pattern; - - pattern = notPattern.Pattern; + PatternSyntax pattern = isPattern.Pattern; - return isPattern.WithPattern(pattern.PrependToLeadingTrivia(notPattern.GetLeadingTrivia())); - } - else if (pattern.IsKind(SyntaxKind.DeclarationPattern)) - { - if (Options.UseNotPattern) + if (pattern.IsKind(SyntaxKind.NotPattern)) { - return IsPatternExpression( - isPattern.Expression, - isPattern.IsKeyword.WithTrailingTrivia(Space), - UnaryPattern( - Token(SyntaxKind.NotKeyword).WithTrailingTrivia(isPattern.IsKeyword.TrailingTrivia), - isPattern.Pattern)); - } - } - else if (pattern is ConstantPatternSyntax constantPattern) - { - ExpressionSyntax constantExpression = constantPattern.Expression; + var notPattern = (UnaryPatternSyntax)pattern; - if (constantExpression.IsKind(SyntaxKind.TrueLiteralExpression)) - { - ConstantPatternSyntax newConstantPattern = ConstantPattern(FalseLiteralExpression() - .WithTriviaFrom(constantExpression)); + pattern = notPattern.Pattern; - return isPattern.WithPattern(newConstantPattern); + return isPattern.WithPattern(pattern.PrependToLeadingTrivia(notPattern.GetLeadingTrivia())); } - else if (constantExpression.IsKind(SyntaxKind.FalseLiteralExpression)) + else if (pattern.IsKind(SyntaxKind.DeclarationPattern)) { - ConstantPatternSyntax newConstantPattern = ConstantPattern(TrueLiteralExpression() - .WithTriviaFrom(constantExpression)); - - return isPattern.WithPattern(newConstantPattern); + if (Options.UseNotPattern) + { + return IsPatternExpression( + isPattern.Expression, + isPattern.IsKeyword.WithTrailingTrivia(Space), + UnaryPattern( + Token(SyntaxKind.NotKeyword).WithTrailingTrivia(isPattern.IsKeyword.TrailingTrivia), + isPattern.Pattern)); + } } - else if (constantExpression.IsKind(SyntaxKind.NullLiteralExpression)) + else if (pattern is ConstantPatternSyntax constantPattern) { - UnaryPatternSyntax notPattern = NotPattern(constantPattern.WithoutTrivia()).WithTriviaFrom(constantPattern); + ExpressionSyntax constantExpression = constantPattern.Expression; - return isPattern.WithPattern(notPattern); - } - else - { - SyntaxDebug.Fail(constantExpression); + if (constantExpression.IsKind(SyntaxKind.TrueLiteralExpression)) + { + ConstantPatternSyntax newConstantPattern = ConstantPattern(FalseLiteralExpression() + .WithTriviaFrom(constantExpression)); + + return isPattern.WithPattern(newConstantPattern); + } + else if (constantExpression.IsKind(SyntaxKind.FalseLiteralExpression)) + { + ConstantPatternSyntax newConstantPattern = ConstantPattern(TrueLiteralExpression() + .WithTriviaFrom(constantExpression)); + + return isPattern.WithPattern(newConstantPattern); + } + else if (constantExpression.IsKind(SyntaxKind.NullLiteralExpression)) + { + UnaryPatternSyntax notPattern = NotPattern(constantPattern.WithoutTrivia()).WithTriviaFrom(constantPattern); + + return isPattern.WithPattern(notPattern); + } + else + { + SyntaxDebug.Fail(constantExpression); + } } - } - return DefaultInvert(isPattern); - } + return DefaultInvert(isPattern); + } - private static PrefixUnaryExpressionSyntax DefaultInvert(ExpressionSyntax expression) - { - SyntaxDebug.Assert(expression.Kind() != SyntaxKind.ParenthesizedExpression, expression); + private static PrefixUnaryExpressionSyntax DefaultInvert(ExpressionSyntax expression) + { + SyntaxDebug.Assert(expression.Kind() != SyntaxKind.ParenthesizedExpression, expression); - SyntaxTriviaList leadingTrivia = expression.GetLeadingTrivia(); + SyntaxTriviaList leadingTrivia = expression.GetLeadingTrivia(); - return LogicalNotExpression( - expression.WithoutLeadingTrivia().Parenthesize(), - Token(leadingTrivia, SyntaxKind.ExclamationToken, SyntaxTriviaList.Empty)); + return LogicalNotExpression( + expression.WithoutLeadingTrivia().Parenthesize(), + Token(leadingTrivia, SyntaxKind.ExclamationToken, SyntaxTriviaList.Empty)); + } } } diff --git a/src/CSharp/CSharp/BracesAnalysis.cs b/src/CSharp/CSharp/BracesAnalysis.cs index 18a3d05f57..f537fff671 100644 --- a/src/CSharp/CSharp/BracesAnalysis.cs +++ b/src/CSharp/CSharp/BracesAnalysis.cs @@ -6,170 +6,171 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -[DebuggerDisplay("{Flags}")] -internal readonly struct BracesAnalysis : IEquatable +namespace Roslynator.CSharp { - private BracesAnalysis(BracesAnalysisFlags flags) + [DebuggerDisplay("{Flags}")] + internal readonly struct BracesAnalysis : IEquatable { - Flags = flags; - } - - public bool AddBraces => Any(BracesAnalysisFlags.AddBraces); - - public bool RemoveBraces => Any(BracesAnalysisFlags.RemoveBraces); + private BracesAnalysis(BracesAnalysisFlags flags) + { + Flags = flags; + } - internal BracesAnalysisFlags Flags { get; } + public bool AddBraces => Any(BracesAnalysisFlags.AddBraces); - public bool Any(BracesAnalysisFlags flags) - { - return (Flags & flags) != 0; - } + public bool RemoveBraces => Any(BracesAnalysisFlags.RemoveBraces); - public static BracesAnalysis AnalyzeBraces(SwitchSectionSyntax switchSection) - { - SyntaxList statements = switchSection.Statements; + internal BracesAnalysisFlags Flags { get; } - int count = statements.Count; + public bool Any(BracesAnalysisFlags flags) + { + return (Flags & flags) != 0; + } - if (count == 0) - return BracesAnalysisFlags.None; + public static BracesAnalysis AnalyzeBraces(SwitchSectionSyntax switchSection) + { + SyntaxList statements = switchSection.Statements; - if (count > 1) - return BracesAnalysisFlags.AddBraces; + int count = statements.Count; - if (statements[0].Kind() == SyntaxKind.Block) - return BracesAnalysisFlags.RemoveBraces; + if (count == 0) + return BracesAnalysisFlags.None; - return BracesAnalysisFlags.AddBraces; - } + if (count > 1) + return BracesAnalysisFlags.AddBraces; - public static BracesAnalysis AnalyzeBraces(IfStatementSyntax ifStatement) - { - var anyHasEmbedded = false; - var anyHasBlock = false; - var allSupportsEmbedded = true; + if (statements[0].Kind() == SyntaxKind.Block) + return BracesAnalysisFlags.RemoveBraces; - int cnt = 0; + return BracesAnalysisFlags.AddBraces; + } - foreach (IfStatementOrElseClause ifOrElse in ifStatement.AsCascade()) + public static BracesAnalysis AnalyzeBraces(IfStatementSyntax ifStatement) { - cnt++; + var anyHasEmbedded = false; + var anyHasBlock = false; + var allSupportsEmbedded = true; - StatementSyntax statement = ifOrElse.Statement; + int cnt = 0; - if (!anyHasEmbedded - && statement.Kind() != SyntaxKind.Block) + foreach (IfStatementOrElseClause ifOrElse in ifStatement.AsCascade()) { - anyHasEmbedded = true; - } + cnt++; - if (!anyHasBlock - && statement.Kind() == SyntaxKind.Block) - { - anyHasBlock = true; - } + StatementSyntax statement = ifOrElse.Statement; - if (allSupportsEmbedded - && !SupportsEmbedded(statement)) - { - allSupportsEmbedded = false; - } + if (!anyHasEmbedded + && statement.Kind() != SyntaxKind.Block) + { + anyHasEmbedded = true; + } - if (cnt > 1 - && anyHasEmbedded - && !allSupportsEmbedded) - { - return BracesAnalysisFlags.AddBraces; - } - } + if (!anyHasBlock + && statement.Kind() == SyntaxKind.Block) + { + anyHasBlock = true; + } - if (cnt > 1 - && allSupportsEmbedded - && anyHasBlock) - { - if (anyHasEmbedded) - { - return BracesAnalysisFlags.AddBraces | BracesAnalysisFlags.RemoveBraces; + if (allSupportsEmbedded + && !SupportsEmbedded(statement)) + { + allSupportsEmbedded = false; + } + + if (cnt > 1 + && anyHasEmbedded + && !allSupportsEmbedded) + { + return BracesAnalysisFlags.AddBraces; + } } - else + + if (cnt > 1 + && allSupportsEmbedded + && anyHasBlock) { - return BracesAnalysisFlags.RemoveBraces; + if (anyHasEmbedded) + { + return BracesAnalysisFlags.AddBraces | BracesAnalysisFlags.RemoveBraces; + } + else + { + return BracesAnalysisFlags.RemoveBraces; + } } - } - return BracesAnalysisFlags.None; + return BracesAnalysisFlags.None; - static bool SupportsEmbedded(StatementSyntax statement) - { - if (statement.IsParentKind(SyntaxKind.IfStatement) - && ((IfStatementSyntax)statement.Parent).Condition?.IsMultiLine() == true) + static bool SupportsEmbedded(StatementSyntax statement) { - return false; - } + if (statement.IsParentKind(SyntaxKind.IfStatement) + && ((IfStatementSyntax)statement.Parent).Condition?.IsMultiLine() == true) + { + return false; + } - if (statement.Kind() == SyntaxKind.Block) - { - var block = (BlockSyntax)statement; + if (statement.Kind() == SyntaxKind.Block) + { + var block = (BlockSyntax)statement; - if (!block.OpenBraceToken.TrailingTrivia.IsEmptyOrWhitespace()) - return false; + if (!block.OpenBraceToken.TrailingTrivia.IsEmptyOrWhitespace()) + return false; - if (!block.CloseBraceToken.LeadingTrivia.IsEmptyOrWhitespace()) - return false; + if (!block.CloseBraceToken.LeadingTrivia.IsEmptyOrWhitespace()) + return false; - statement = block.Statements.SingleOrDefault(shouldThrow: false); + statement = block.Statements.SingleOrDefault(shouldThrow: false); - if (statement == null) - return false; + if (statement is null) + return false; - if (statement.Kind() == SyntaxKind.IfStatement - && block.IsParentKind(SyntaxKind.IfStatement) - && ((IfStatementSyntax)block.Parent).Else != null - && ((IfStatementSyntax)statement).GetCascadeInfo().EndsWithIf) - { - return false; + if (statement.Kind() == SyntaxKind.IfStatement + && block.IsParentKind(SyntaxKind.IfStatement) + && ((IfStatementSyntax)block.Parent).Else is not null + && ((IfStatementSyntax)statement).GetCascadeInfo().EndsWithIf) + { + return false; + } } - } - return !statement.IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.LabeledStatement) - && statement.IsSingleLine(); + return !statement.IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.LabeledStatement) + && statement.IsSingleLine(); + } } - } - public override bool Equals(object obj) - { - return obj is BracesAnalysis other && Equals(other); - } + public override bool Equals(object obj) + { + return obj is BracesAnalysis other && Equals(other); + } - public bool Equals(BracesAnalysis other) - { - return Flags == other.Flags; - } + public bool Equals(BracesAnalysis other) + { + return Flags == other.Flags; + } - public override int GetHashCode() - { - return Flags.GetHashCode(); - } + public override int GetHashCode() + { + return Flags.GetHashCode(); + } - public static implicit operator BracesAnalysis(BracesAnalysisFlags value) - { - return new BracesAnalysis(value); - } + public static implicit operator BracesAnalysis(BracesAnalysisFlags value) + { + return new BracesAnalysis(value); + } - public static implicit operator BracesAnalysisFlags(in BracesAnalysis value) - { - return value.Flags; - } + public static implicit operator BracesAnalysisFlags(in BracesAnalysis value) + { + return value.Flags; + } - public static bool operator ==(in BracesAnalysis analysis1, in BracesAnalysis analysis2) - { - return analysis1.Equals(analysis2); - } + public static bool operator ==(in BracesAnalysis analysis1, in BracesAnalysis analysis2) + { + return analysis1.Equals(analysis2); + } - public static bool operator !=(in BracesAnalysis analysis1, in BracesAnalysis analysis2) - { - return !(analysis1 == analysis2); + public static bool operator !=(in BracesAnalysis analysis1, in BracesAnalysis analysis2) + { + return !(analysis1 == analysis2); + } } } diff --git a/src/CSharp/CSharp/CSharpFactory.cs b/src/CSharp/CSharp/CSharpFactory.cs index e4756e45a5..a9d87c8dfb 100644 --- a/src/CSharp/CSharp/CSharpFactory.cs +++ b/src/CSharp/CSharp/CSharpFactory.cs @@ -10,2068 +10,2069 @@ #pragma warning disable CS1591 -namespace Roslynator.CSharp; - -/// -/// A factory for syntax nodes, tokens and trivia. This class is built on top of members. -/// -public static class CSharpFactory +namespace Roslynator.CSharp { - #region Trivia - public static SyntaxTrivia EmptyWhitespace() + /// + /// A factory for syntax nodes, tokens and trivia. This class is built on top of members. + /// + public static class CSharpFactory { - return SyntaxTrivia(SyntaxKind.WhitespaceTrivia, ""); - } + #region Trivia + public static SyntaxTrivia EmptyWhitespace() + { + return SyntaxTrivia(SyntaxKind.WhitespaceTrivia, ""); + } - public static SyntaxTrivia NewLine() - { - switch (Environment.NewLine) + public static SyntaxTrivia NewLine() { - case "\r": - return CarriageReturn; - case "\n": - return LineFeed; - default: - return CarriageReturnLineFeed; + switch (Environment.NewLine) + { + case "\r": + return CarriageReturn; + case "\n": + return LineFeed; + default: + return CarriageReturnLineFeed; + } } - } - #endregion Trivia + #endregion Trivia - #region Token - internal static SyntaxToken OpenParenToken() - { - return Token(SyntaxKind.OpenParenToken); - } + #region Token + internal static SyntaxToken OpenParenToken() + { + return Token(SyntaxKind.OpenParenToken); + } - internal static SyntaxToken CloseParenToken() - { - return Token(SyntaxKind.CloseParenToken); - } + internal static SyntaxToken CloseParenToken() + { + return Token(SyntaxKind.CloseParenToken); + } - internal static SyntaxToken OpenBraceToken() - { - return Token(SyntaxKind.OpenBraceToken); - } + internal static SyntaxToken OpenBraceToken() + { + return Token(SyntaxKind.OpenBraceToken); + } - internal static SyntaxToken CloseBraceToken() - { - return Token(SyntaxKind.CloseBraceToken); - } + internal static SyntaxToken CloseBraceToken() + { + return Token(SyntaxKind.CloseBraceToken); + } - internal static SyntaxToken OpenBracketToken() - { - return Token(SyntaxKind.OpenBracketToken); - } + internal static SyntaxToken OpenBracketToken() + { + return Token(SyntaxKind.OpenBracketToken); + } - internal static SyntaxToken CloseBracketToken() - { - return Token(SyntaxKind.CloseBracketToken); - } + internal static SyntaxToken CloseBracketToken() + { + return Token(SyntaxKind.CloseBracketToken); + } - internal static SyntaxToken SemicolonToken() - { - return Token(SyntaxKind.SemicolonToken); - } + internal static SyntaxToken SemicolonToken() + { + return Token(SyntaxKind.SemicolonToken); + } - internal static SyntaxToken CommaToken() - { - return Token(SyntaxKind.CommaToken); - } - #endregion Token + internal static SyntaxToken CommaToken() + { + return Token(SyntaxKind.CommaToken); + } + #endregion Token - #region Type - public static PredefinedTypeSyntax PredefinedBoolType() - { - return PredefinedType(SyntaxKind.BoolKeyword); - } + #region Type + public static PredefinedTypeSyntax PredefinedBoolType() + { + return PredefinedType(SyntaxKind.BoolKeyword); + } - public static PredefinedTypeSyntax PredefinedByteType() - { - return PredefinedType(SyntaxKind.ByteKeyword); - } + public static PredefinedTypeSyntax PredefinedByteType() + { + return PredefinedType(SyntaxKind.ByteKeyword); + } - public static PredefinedTypeSyntax PredefinedSByteType() - { - return PredefinedType(SyntaxKind.SByteKeyword); - } + public static PredefinedTypeSyntax PredefinedSByteType() + { + return PredefinedType(SyntaxKind.SByteKeyword); + } - public static PredefinedTypeSyntax PredefinedIntType() - { - return PredefinedType(SyntaxKind.IntKeyword); - } + public static PredefinedTypeSyntax PredefinedIntType() + { + return PredefinedType(SyntaxKind.IntKeyword); + } - public static PredefinedTypeSyntax PredefinedUIntType() - { - return PredefinedType(SyntaxKind.UIntKeyword); - } + public static PredefinedTypeSyntax PredefinedUIntType() + { + return PredefinedType(SyntaxKind.UIntKeyword); + } - public static PredefinedTypeSyntax PredefinedShortType() - { - return PredefinedType(SyntaxKind.ShortKeyword); - } + public static PredefinedTypeSyntax PredefinedShortType() + { + return PredefinedType(SyntaxKind.ShortKeyword); + } - public static PredefinedTypeSyntax PredefinedUShortType() - { - return PredefinedType(SyntaxKind.UShortKeyword); - } + public static PredefinedTypeSyntax PredefinedUShortType() + { + return PredefinedType(SyntaxKind.UShortKeyword); + } - public static PredefinedTypeSyntax PredefinedLongType() - { - return PredefinedType(SyntaxKind.LongKeyword); - } + public static PredefinedTypeSyntax PredefinedLongType() + { + return PredefinedType(SyntaxKind.LongKeyword); + } - public static PredefinedTypeSyntax PredefinedULongType() - { - return PredefinedType(SyntaxKind.ULongKeyword); - } + public static PredefinedTypeSyntax PredefinedULongType() + { + return PredefinedType(SyntaxKind.ULongKeyword); + } - public static PredefinedTypeSyntax PredefinedFloatType() - { - return PredefinedType(SyntaxKind.FloatKeyword); - } + public static PredefinedTypeSyntax PredefinedFloatType() + { + return PredefinedType(SyntaxKind.FloatKeyword); + } - public static PredefinedTypeSyntax PredefinedDoubleType() - { - return PredefinedType(SyntaxKind.DoubleKeyword); - } + public static PredefinedTypeSyntax PredefinedDoubleType() + { + return PredefinedType(SyntaxKind.DoubleKeyword); + } - public static PredefinedTypeSyntax PredefinedDecimalType() - { - return PredefinedType(SyntaxKind.DecimalKeyword); - } + public static PredefinedTypeSyntax PredefinedDecimalType() + { + return PredefinedType(SyntaxKind.DecimalKeyword); + } - public static PredefinedTypeSyntax PredefinedStringType() - { - return PredefinedType(SyntaxKind.StringKeyword); - } + public static PredefinedTypeSyntax PredefinedStringType() + { + return PredefinedType(SyntaxKind.StringKeyword); + } - public static PredefinedTypeSyntax PredefinedCharType() - { - return PredefinedType(SyntaxKind.CharKeyword); - } + public static PredefinedTypeSyntax PredefinedCharType() + { + return PredefinedType(SyntaxKind.CharKeyword); + } - public static PredefinedTypeSyntax PredefinedObjectType() - { - return PredefinedType(SyntaxKind.ObjectKeyword); - } + public static PredefinedTypeSyntax PredefinedObjectType() + { + return PredefinedType(SyntaxKind.ObjectKeyword); + } - public static PredefinedTypeSyntax VoidType() - { - return PredefinedType(SyntaxKind.VoidKeyword); - } + public static PredefinedTypeSyntax VoidType() + { + return PredefinedType(SyntaxKind.VoidKeyword); + } - private static PredefinedTypeSyntax PredefinedType(SyntaxKind syntaxKind) - { - return SyntaxFactory.PredefinedType(Token(syntaxKind)); - } + private static PredefinedTypeSyntax PredefinedType(SyntaxKind syntaxKind) + { + return SyntaxFactory.PredefinedType(Token(syntaxKind)); + } - #endregion Type + #endregion Type - #region List - /// - /// Creates a list of modifiers from the specified accessibility. - /// - /// - public static SyntaxTokenList TokenList(Accessibility accessibility) - { - switch (accessibility) - { - case Accessibility.Public: - return Modifiers.Public(); - case Accessibility.Internal: - return Modifiers.Internal(); - case Accessibility.ProtectedOrInternal: - return Modifiers.Protected_Internal(); - case Accessibility.Protected: - return Modifiers.Protected(); - case Accessibility.ProtectedAndInternal: - return Modifiers.Private_Protected(); - case Accessibility.Private: - return Modifiers.Private(); - case Accessibility.NotApplicable: - return default; - default: - throw new ArgumentException($"Unknown accessibility '{accessibility}'."); + #region List + /// + /// Creates a list of modifiers from the specified accessibility. + /// + /// + public static SyntaxTokenList TokenList(Accessibility accessibility) + { + switch (accessibility) + { + case Accessibility.Public: + return Modifiers.Public(); + case Accessibility.Internal: + return Modifiers.Internal(); + case Accessibility.ProtectedOrInternal: + return Modifiers.Protected_Internal(); + case Accessibility.Protected: + return Modifiers.Protected(); + case Accessibility.ProtectedAndInternal: + return Modifiers.Private_Protected(); + case Accessibility.Private: + return Modifiers.Private(); + case Accessibility.NotApplicable: + return default; + default: + throw new ArgumentException($"Unknown accessibility '{accessibility}'."); + } } - } - - public static SyntaxTokenList TokenList(SyntaxKind kind) - { - return SyntaxFactory.TokenList(Token(kind)); - } - public static SyntaxTokenList TokenList(SyntaxKind kind1, SyntaxKind kind2) - { - return SyntaxFactory.TokenList(Token(kind1), Token(kind2)); - } + public static SyntaxTokenList TokenList(SyntaxKind kind) + { + return SyntaxFactory.TokenList(Token(kind)); + } - public static SyntaxTokenList TokenList(SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) - { - return SyntaxFactory.TokenList(Token(kind1), Token(kind2), Token(kind3)); - } + public static SyntaxTokenList TokenList(SyntaxKind kind1, SyntaxKind kind2) + { + return SyntaxFactory.TokenList(Token(kind1), Token(kind2)); + } - public static ArgumentListSyntax ArgumentList(params ArgumentSyntax[] arguments) - { - return SyntaxFactory.ArgumentList(SeparatedList(arguments)); - } + public static SyntaxTokenList TokenList(SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) + { + return SyntaxFactory.TokenList(Token(kind1), Token(kind2), Token(kind3)); + } - public static ArgumentListSyntax ArgumentList(ArgumentSyntax argument) - { - return SyntaxFactory.ArgumentList(SingletonSeparatedList(argument)); - } + public static ArgumentListSyntax ArgumentList(params ArgumentSyntax[] arguments) + { + return SyntaxFactory.ArgumentList(SeparatedList(arguments)); + } - public static BracketedArgumentListSyntax BracketedArgumentList(params ArgumentSyntax[] arguments) - { - return SyntaxFactory.BracketedArgumentList(SeparatedList(arguments)); - } + public static ArgumentListSyntax ArgumentList(ArgumentSyntax argument) + { + return SyntaxFactory.ArgumentList(SingletonSeparatedList(argument)); + } - public static BracketedArgumentListSyntax BracketedArgumentList(ArgumentSyntax argument) - { - return SyntaxFactory.BracketedArgumentList(SingletonSeparatedList(argument)); - } + public static BracketedArgumentListSyntax BracketedArgumentList(params ArgumentSyntax[] arguments) + { + return SyntaxFactory.BracketedArgumentList(SeparatedList(arguments)); + } - public static AttributeListSyntax AttributeList(AttributeSyntax attribute) - { - return SyntaxFactory.AttributeList(SingletonSeparatedList(attribute)); - } + public static BracketedArgumentListSyntax BracketedArgumentList(ArgumentSyntax argument) + { + return SyntaxFactory.BracketedArgumentList(SingletonSeparatedList(argument)); + } - public static AttributeListSyntax AttributeList(params AttributeSyntax[] attributes) - { - return SyntaxFactory.AttributeList(SeparatedList(attributes)); - } + public static AttributeListSyntax AttributeList(AttributeSyntax attribute) + { + return SyntaxFactory.AttributeList(SingletonSeparatedList(attribute)); + } - public static AttributeArgumentListSyntax AttributeArgumentList(params AttributeArgumentSyntax[] attributeArguments) - { - return SyntaxFactory.AttributeArgumentList(SeparatedList(attributeArguments)); - } + public static AttributeListSyntax AttributeList(params AttributeSyntax[] attributes) + { + return SyntaxFactory.AttributeList(SeparatedList(attributes)); + } - public static AttributeArgumentListSyntax AttributeArgumentList(AttributeArgumentSyntax attributeArgument) - { - return SyntaxFactory.AttributeArgumentList(SingletonSeparatedList(attributeArgument)); - } + public static AttributeArgumentListSyntax AttributeArgumentList(params AttributeArgumentSyntax[] attributeArguments) + { + return SyntaxFactory.AttributeArgumentList(SeparatedList(attributeArguments)); + } - public static AccessorListSyntax AccessorList(params AccessorDeclarationSyntax[] accessors) - { - return SyntaxFactory.AccessorList(List(accessors)); - } + public static AttributeArgumentListSyntax AttributeArgumentList(AttributeArgumentSyntax attributeArgument) + { + return SyntaxFactory.AttributeArgumentList(SingletonSeparatedList(attributeArgument)); + } - public static AccessorListSyntax AccessorList(AccessorDeclarationSyntax accessor) - { - return SyntaxFactory.AccessorList(SingletonList(accessor)); - } + public static AccessorListSyntax AccessorList(params AccessorDeclarationSyntax[] accessors) + { + return SyntaxFactory.AccessorList(List(accessors)); + } - public static ParameterListSyntax ParameterList(ParameterSyntax parameter) - { - return SyntaxFactory.ParameterList(SingletonSeparatedList(parameter)); - } + public static AccessorListSyntax AccessorList(AccessorDeclarationSyntax accessor) + { + return SyntaxFactory.AccessorList(SingletonList(accessor)); + } - public static ParameterListSyntax ParameterList(params ParameterSyntax[] parameters) - { - return SyntaxFactory.ParameterList(SeparatedList(parameters)); - } + public static ParameterListSyntax ParameterList(ParameterSyntax parameter) + { + return SyntaxFactory.ParameterList(SingletonSeparatedList(parameter)); + } - public static BracketedParameterListSyntax BracketedParameterList(ParameterSyntax parameter) - { - return SyntaxFactory.BracketedParameterList(SingletonSeparatedList(parameter)); - } + public static ParameterListSyntax ParameterList(params ParameterSyntax[] parameters) + { + return SyntaxFactory.ParameterList(SeparatedList(parameters)); + } - public static BracketedParameterListSyntax BracketedParameterList(params ParameterSyntax[] parameters) - { - return SyntaxFactory.BracketedParameterList(SeparatedList(parameters)); - } + public static BracketedParameterListSyntax BracketedParameterList(ParameterSyntax parameter) + { + return SyntaxFactory.BracketedParameterList(SingletonSeparatedList(parameter)); + } - public static TypeArgumentListSyntax TypeArgumentList(TypeSyntax argument) - { - return SyntaxFactory.TypeArgumentList(SingletonSeparatedList(argument)); - } + public static BracketedParameterListSyntax BracketedParameterList(params ParameterSyntax[] parameters) + { + return SyntaxFactory.BracketedParameterList(SeparatedList(parameters)); + } - public static TypeArgumentListSyntax TypeArgumentList(params TypeSyntax[] arguments) - { - return SyntaxFactory.TypeArgumentList(SeparatedList(arguments)); - } + public static TypeArgumentListSyntax TypeArgumentList(TypeSyntax argument) + { + return SyntaxFactory.TypeArgumentList(SingletonSeparatedList(argument)); + } - public static TypeParameterListSyntax TypeParameterList(TypeParameterSyntax parameter) - { - return SyntaxFactory.TypeParameterList(SingletonSeparatedList(parameter)); - } + public static TypeArgumentListSyntax TypeArgumentList(params TypeSyntax[] arguments) + { + return SyntaxFactory.TypeArgumentList(SeparatedList(arguments)); + } - public static TypeParameterListSyntax TypeParameterList(params TypeParameterSyntax[] parameters) - { - return SyntaxFactory.TypeParameterList(SeparatedList(parameters)); - } + public static TypeParameterListSyntax TypeParameterList(TypeParameterSyntax parameter) + { + return SyntaxFactory.TypeParameterList(SingletonSeparatedList(parameter)); + } - public static BaseListSyntax BaseList(BaseTypeSyntax type) - { - return SyntaxFactory.BaseList(SingletonSeparatedList(type)); - } + public static TypeParameterListSyntax TypeParameterList(params TypeParameterSyntax[] parameters) + { + return SyntaxFactory.TypeParameterList(SeparatedList(parameters)); + } - public static BaseListSyntax BaseList(params BaseTypeSyntax[] types) - { - return SyntaxFactory.BaseList(SeparatedList(types)); - } + public static BaseListSyntax BaseList(BaseTypeSyntax type) + { + return SyntaxFactory.BaseList(SingletonSeparatedList(type)); + } - public static BaseListSyntax BaseList(SyntaxToken colonToken, BaseTypeSyntax baseType) - { - return SyntaxFactory.BaseList(colonToken, SingletonSeparatedList(baseType)); - } + public static BaseListSyntax BaseList(params BaseTypeSyntax[] types) + { + return SyntaxFactory.BaseList(SeparatedList(types)); + } - public static BaseListSyntax BaseList(SyntaxToken colonToken, params BaseTypeSyntax[] types) - { - return SyntaxFactory.BaseList(colonToken, SeparatedList(types)); - } - #endregion List + public static BaseListSyntax BaseList(SyntaxToken colonToken, BaseTypeSyntax baseType) + { + return SyntaxFactory.BaseList(colonToken, SingletonSeparatedList(baseType)); + } - #region MemberDeclaration + public static BaseListSyntax BaseList(SyntaxToken colonToken, params BaseTypeSyntax[] types) + { + return SyntaxFactory.BaseList(colonToken, SeparatedList(types)); + } + #endregion List - internal static NamespaceDeclarationSyntax NamespaceDeclaration(string name, MemberDeclarationSyntax member) - { - return NamespaceDeclaration(ParseName(name), member); - } + #region MemberDeclaration - public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, MemberDeclarationSyntax member) - { - return NamespaceDeclaration(name, SingletonList(member)); - } + internal static NamespaceDeclarationSyntax NamespaceDeclaration(string name, MemberDeclarationSyntax member) + { + return NamespaceDeclaration(ParseName(name), member); + } - internal static NamespaceDeclarationSyntax NamespaceDeclaration(string name, SyntaxList members) - { - return NamespaceDeclaration(ParseName(name), members); - } + public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, MemberDeclarationSyntax member) + { + return NamespaceDeclaration(name, SingletonList(member)); + } - public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, SyntaxList members) - { - return SyntaxFactory.NamespaceDeclaration( - name, - default(SyntaxList), - default(SyntaxList), - members); - } + internal static NamespaceDeclarationSyntax NamespaceDeclaration(string name, SyntaxList members) + { + return NamespaceDeclaration(ParseName(name), members); + } - public static ClassDeclarationSyntax ClassDeclaration(SyntaxTokenList modifiers, string identifier, SyntaxList members = default) - { - return ClassDeclaration(modifiers, Identifier(identifier), members); - } + public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, SyntaxList members) + { + return SyntaxFactory.NamespaceDeclaration( + name, + default(SyntaxList), + default(SyntaxList), + members); + } - public static ClassDeclarationSyntax ClassDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, SyntaxList members = default) - { - return SyntaxFactory.ClassDeclaration( - default(SyntaxList), - modifiers, - identifier, - default(TypeParameterListSyntax), - default(BaseListSyntax), - default(SyntaxList), - members); - } + public static ClassDeclarationSyntax ClassDeclaration(SyntaxTokenList modifiers, string identifier, SyntaxList members = default) + { + return ClassDeclaration(modifiers, Identifier(identifier), members); + } - internal static ClassDeclarationSyntax ClassDeclaration(StructDeclarationSyntax structDeclaration) - { - if (structDeclaration == null) - throw new ArgumentNullException(nameof(structDeclaration)); - - SyntaxToken keyword = structDeclaration.Keyword; - - return SyntaxFactory.ClassDeclaration( - structDeclaration.AttributeLists, - structDeclaration.Modifiers, - SyntaxFactory.Token(keyword.LeadingTrivia, SyntaxKind.ClassKeyword, keyword.TrailingTrivia), - structDeclaration.Identifier, - structDeclaration.TypeParameterList, - structDeclaration.BaseList, - structDeclaration.ConstraintClauses, - structDeclaration.OpenBraceToken, - structDeclaration.Members, - structDeclaration.CloseBraceToken, - structDeclaration.SemicolonToken); - } + public static ClassDeclarationSyntax ClassDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, SyntaxList members = default) + { + return SyntaxFactory.ClassDeclaration( + default(SyntaxList), + modifiers, + identifier, + default(TypeParameterListSyntax), + default(BaseListSyntax), + default(SyntaxList), + members); + } - public static StructDeclarationSyntax StructDeclaration(SyntaxTokenList modifiers, string identifier, SyntaxList members = default) - { - return StructDeclaration(modifiers, Identifier(identifier), members); - } + internal static ClassDeclarationSyntax ClassDeclaration(StructDeclarationSyntax structDeclaration) + { + if (structDeclaration is null) + throw new ArgumentNullException(nameof(structDeclaration)); + + SyntaxToken keyword = structDeclaration.Keyword; + + return SyntaxFactory.ClassDeclaration( + structDeclaration.AttributeLists, + structDeclaration.Modifiers, + SyntaxFactory.Token(keyword.LeadingTrivia, SyntaxKind.ClassKeyword, keyword.TrailingTrivia), + structDeclaration.Identifier, + structDeclaration.TypeParameterList, + structDeclaration.BaseList, + structDeclaration.ConstraintClauses, + structDeclaration.OpenBraceToken, + structDeclaration.Members, + structDeclaration.CloseBraceToken, + structDeclaration.SemicolonToken); + } - public static StructDeclarationSyntax StructDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, SyntaxList members = default) - { - return SyntaxFactory.StructDeclaration( - default(SyntaxList), - modifiers, - identifier, - default(TypeParameterListSyntax), - default(BaseListSyntax), - default(SyntaxList), - members); - } + public static StructDeclarationSyntax StructDeclaration(SyntaxTokenList modifiers, string identifier, SyntaxList members = default) + { + return StructDeclaration(modifiers, Identifier(identifier), members); + } - internal static StructDeclarationSyntax StructDeclaration(ClassDeclarationSyntax classDeclaration) - { - if (classDeclaration == null) - throw new ArgumentNullException(nameof(classDeclaration)); - - SyntaxToken keyword = classDeclaration.Keyword; - - return SyntaxFactory.StructDeclaration( - classDeclaration.AttributeLists, - classDeclaration.Modifiers, - SyntaxFactory.Token(keyword.LeadingTrivia, SyntaxKind.StructKeyword, keyword.TrailingTrivia), - classDeclaration.Identifier, - classDeclaration.TypeParameterList, - classDeclaration.BaseList, - classDeclaration.ConstraintClauses, - classDeclaration.OpenBraceToken, - classDeclaration.Members, - classDeclaration.CloseBraceToken, - classDeclaration.SemicolonToken); - } + public static StructDeclarationSyntax StructDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, SyntaxList members = default) + { + return SyntaxFactory.StructDeclaration( + default(SyntaxList), + modifiers, + identifier, + default(TypeParameterListSyntax), + default(BaseListSyntax), + default(SyntaxList), + members); + } - public static InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxTokenList modifiers, string identifier, SyntaxList members = default) - { - return InterfaceDeclaration(modifiers, Identifier(identifier), members); - } + internal static StructDeclarationSyntax StructDeclaration(ClassDeclarationSyntax classDeclaration) + { + if (classDeclaration is null) + throw new ArgumentNullException(nameof(classDeclaration)); + + SyntaxToken keyword = classDeclaration.Keyword; + + return SyntaxFactory.StructDeclaration( + classDeclaration.AttributeLists, + classDeclaration.Modifiers, + SyntaxFactory.Token(keyword.LeadingTrivia, SyntaxKind.StructKeyword, keyword.TrailingTrivia), + classDeclaration.Identifier, + classDeclaration.TypeParameterList, + classDeclaration.BaseList, + classDeclaration.ConstraintClauses, + classDeclaration.OpenBraceToken, + classDeclaration.Members, + classDeclaration.CloseBraceToken, + classDeclaration.SemicolonToken); + } - public static InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, SyntaxList members = default) - { - return SyntaxFactory.InterfaceDeclaration( - default(SyntaxList), - modifiers, - identifier, - default(TypeParameterListSyntax), - default(BaseListSyntax), - default(SyntaxList), - members); - } + public static InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxTokenList modifiers, string identifier, SyntaxList members = default) + { + return InterfaceDeclaration(modifiers, Identifier(identifier), members); + } - public static ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax body) - { - return SyntaxFactory.ConstructorDeclaration( - default(SyntaxList), - modifiers, - identifier, - parameterList, - default(ConstructorInitializerSyntax), - body); - } + public static InterfaceDeclarationSyntax InterfaceDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, SyntaxList members = default) + { + return SyntaxFactory.InterfaceDeclaration( + default(SyntaxList), + modifiers, + identifier, + default(TypeParameterListSyntax), + default(BaseListSyntax), + default(SyntaxList), + members); + } - public static ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ArrowExpressionClauseSyntax expressionBody) - { - return SyntaxFactory.ConstructorDeclaration( - default(SyntaxList), - modifiers, - identifier, - parameterList, - default(ConstructorInitializerSyntax), - expressionBody, - SemicolonToken()); - } + public static ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax body) + { + return SyntaxFactory.ConstructorDeclaration( + default(SyntaxList), + modifiers, + identifier, + parameterList, + default(ConstructorInitializerSyntax), + body); + } - public static EnumDeclarationSyntax EnumDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, SeparatedSyntaxList members) - { - return SyntaxFactory.EnumDeclaration( - default(SyntaxList), - modifiers, - identifier, - default(BaseListSyntax), - members); - } + public static ConstructorDeclarationSyntax ConstructorDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ArrowExpressionClauseSyntax expressionBody) + { + return SyntaxFactory.ConstructorDeclaration( + default(SyntaxList), + modifiers, + identifier, + parameterList, + default(ConstructorInitializerSyntax), + expressionBody, + SemicolonToken()); + } - public static EnumMemberDeclarationSyntax EnumMemberDeclaration(string name, ExpressionSyntax value) - { - return EnumMemberDeclaration(Identifier(name), value); - } + public static EnumDeclarationSyntax EnumDeclaration(SyntaxTokenList modifiers, SyntaxToken identifier, SeparatedSyntaxList members) + { + return SyntaxFactory.EnumDeclaration( + default(SyntaxList), + modifiers, + identifier, + default(BaseListSyntax), + members); + } - public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxToken identifier, ExpressionSyntax value) - { - return EnumMemberDeclaration(identifier, EqualsValueClause(value)); - } + public static EnumMemberDeclarationSyntax EnumMemberDeclaration(string name, ExpressionSyntax value) + { + return EnumMemberDeclaration(Identifier(name), value); + } - public static EnumMemberDeclarationSyntax EnumMemberDeclaration(string name, EqualsValueClauseSyntax value) - { - return EnumMemberDeclaration(Identifier(name), value); - } + public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxToken identifier, ExpressionSyntax value) + { + return EnumMemberDeclaration(identifier, EqualsValueClause(value)); + } - public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxToken identifier, EqualsValueClauseSyntax value) - { - return SyntaxFactory.EnumMemberDeclaration( - default(SyntaxList), - identifier, - value); - } + public static EnumMemberDeclarationSyntax EnumMemberDeclaration(string name, EqualsValueClauseSyntax value) + { + return EnumMemberDeclaration(Identifier(name), value); + } - public static FieldDeclarationSyntax FieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, string identifier, ExpressionSyntax value = null) - { - return FieldDeclaration( - modifiers, - type, - Identifier(identifier), - value); - } + public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxToken identifier, EqualsValueClauseSyntax value) + { + return SyntaxFactory.EnumMemberDeclaration( + default(SyntaxList), + identifier, + value); + } - public static FieldDeclarationSyntax FieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, string identifier, EqualsValueClauseSyntax initializer) - { - return FieldDeclaration( - modifiers, - type, - Identifier(identifier), - initializer); - } + public static FieldDeclarationSyntax FieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, string identifier, ExpressionSyntax value = null) + { + return FieldDeclaration( + modifiers, + type, + Identifier(identifier), + value); + } - public static FieldDeclarationSyntax FieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, SyntaxToken identifier, ExpressionSyntax value = null) - { - return FieldDeclaration( - modifiers, - type, - identifier, - (value != null) ? EqualsValueClause(value) : default); - } + public static FieldDeclarationSyntax FieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, string identifier, EqualsValueClauseSyntax initializer) + { + return FieldDeclaration( + modifiers, + type, + Identifier(identifier), + initializer); + } - public static FieldDeclarationSyntax FieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax initializer) - { - return SyntaxFactory.FieldDeclaration( - default(SyntaxList), - modifiers, - VariableDeclaration( + public static FieldDeclarationSyntax FieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, SyntaxToken identifier, ExpressionSyntax value = null) + { + return FieldDeclaration( + modifiers, type, identifier, - initializer)); - } - - public static EventFieldDeclarationSyntax EventFieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, string identifier) - { - return EventFieldDeclaration( - modifiers, - type, - Identifier(identifier)); - } + (value is not null) ? EqualsValueClause(value) : default); + } - public static EventFieldDeclarationSyntax EventFieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, SyntaxToken identifier) - { - return SyntaxFactory.EventFieldDeclaration( - default(SyntaxList), - modifiers, - VariableDeclaration(type, identifier)); - } + public static FieldDeclarationSyntax FieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax initializer) + { + return SyntaxFactory.FieldDeclaration( + default(SyntaxList), + modifiers, + VariableDeclaration( + type, + identifier, + initializer)); + } - public static EventDeclarationSyntax EventDeclaration(SyntaxTokenList modifiers, TypeSyntax type, string identifier, AccessorListSyntax accessorList) - { - return EventDeclaration( - modifiers, - type, - Identifier(identifier), - accessorList); - } + public static EventFieldDeclarationSyntax EventFieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, string identifier) + { + return EventFieldDeclaration( + modifiers, + type, + Identifier(identifier)); + } - public static EventDeclarationSyntax EventDeclaration(SyntaxTokenList modifiers, TypeSyntax type, SyntaxToken identifier, AccessorListSyntax accessorList) - { - return SyntaxFactory.EventDeclaration( - default(SyntaxList), - modifiers, - type, - default(ExplicitInterfaceSpecifierSyntax), - identifier, - accessorList); - } + public static EventFieldDeclarationSyntax EventFieldDeclaration(SyntaxTokenList modifiers, TypeSyntax type, SyntaxToken identifier) + { + return SyntaxFactory.EventFieldDeclaration( + default(SyntaxList), + modifiers, + VariableDeclaration(type, identifier)); + } - public static DelegateDeclarationSyntax DelegateDeclaration(SyntaxTokenList modifiers, TypeSyntax returnType, string identifier, ParameterListSyntax parameterList) - { - return DelegateDeclaration( - modifiers, - returnType, - Identifier(identifier), - parameterList); - } + public static EventDeclarationSyntax EventDeclaration(SyntaxTokenList modifiers, TypeSyntax type, string identifier, AccessorListSyntax accessorList) + { + return EventDeclaration( + modifiers, + type, + Identifier(identifier), + accessorList); + } - public static DelegateDeclarationSyntax DelegateDeclaration(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, ParameterListSyntax parameterList) - { - return SyntaxFactory.DelegateDeclaration( - default(SyntaxList), - modifiers, - returnType, - identifier, - default(TypeParameterListSyntax), - parameterList, - default(SyntaxList)); - } + public static EventDeclarationSyntax EventDeclaration(SyntaxTokenList modifiers, TypeSyntax type, SyntaxToken identifier, AccessorListSyntax accessorList) + { + return SyntaxFactory.EventDeclaration( + default(SyntaxList), + modifiers, + type, + default(ExplicitInterfaceSpecifierSyntax), + identifier, + accessorList); + } - public static MethodDeclarationSyntax MethodDeclaration( - SyntaxTokenList modifiers, - TypeSyntax returnType, - SyntaxToken identifier, - ParameterListSyntax parameterList, - BlockSyntax body) - { - return SyntaxFactory.MethodDeclaration( - default(SyntaxList), - modifiers, - returnType, - default(ExplicitInterfaceSpecifierSyntax), - identifier, - default(TypeParameterListSyntax), - parameterList, - default(SyntaxList), - body, - default(ArrowExpressionClauseSyntax)); - } + public static DelegateDeclarationSyntax DelegateDeclaration(SyntaxTokenList modifiers, TypeSyntax returnType, string identifier, ParameterListSyntax parameterList) + { + return DelegateDeclaration( + modifiers, + returnType, + Identifier(identifier), + parameterList); + } - public static MethodDeclarationSyntax MethodDeclaration( - SyntaxTokenList modifiers, - TypeSyntax returnType, - SyntaxToken identifier, - ParameterListSyntax parameterList, - ArrowExpressionClauseSyntax expressionBody) - { - return SyntaxFactory.MethodDeclaration( - default(SyntaxList), - modifiers, - returnType, - default(ExplicitInterfaceSpecifierSyntax), - identifier, - default(TypeParameterListSyntax), - parameterList, - default(SyntaxList), - default(BlockSyntax), - expressionBody, - SemicolonToken()); - } + public static DelegateDeclarationSyntax DelegateDeclaration(SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, ParameterListSyntax parameterList) + { + return SyntaxFactory.DelegateDeclaration( + default(SyntaxList), + modifiers, + returnType, + identifier, + default(TypeParameterListSyntax), + parameterList, + default(SyntaxList)); + } - public static OperatorDeclarationSyntax OperatorDeclaration( - SyntaxTokenList modifiers, - TypeSyntax returnType, - SyntaxToken operatorToken, - ParameterListSyntax parameterList, - BlockSyntax body) - { - return SyntaxFactory.OperatorDeclaration( - default(SyntaxList), - modifiers, - returnType, - operatorToken, - parameterList, - body, - default(ArrowExpressionClauseSyntax)); - } + public static MethodDeclarationSyntax MethodDeclaration( + SyntaxTokenList modifiers, + TypeSyntax returnType, + SyntaxToken identifier, + ParameterListSyntax parameterList, + BlockSyntax body) + { + return SyntaxFactory.MethodDeclaration( + default(SyntaxList), + modifiers, + returnType, + default(ExplicitInterfaceSpecifierSyntax), + identifier, + default(TypeParameterListSyntax), + parameterList, + default(SyntaxList), + body, + default(ArrowExpressionClauseSyntax)); + } - public static OperatorDeclarationSyntax OperatorDeclaration( - SyntaxTokenList modifiers, - TypeSyntax returnType, - SyntaxToken operatorToken, - ParameterListSyntax parameterList, - ArrowExpressionClauseSyntax expressionBody) - { - return SyntaxFactory.OperatorDeclaration( - default(SyntaxList), - modifiers, - returnType, - Token(SyntaxKind.OperatorKeyword), - operatorToken, - parameterList, - default(BlockSyntax), - expressionBody, - SemicolonToken()); - } + public static MethodDeclarationSyntax MethodDeclaration( + SyntaxTokenList modifiers, + TypeSyntax returnType, + SyntaxToken identifier, + ParameterListSyntax parameterList, + ArrowExpressionClauseSyntax expressionBody) + { + return SyntaxFactory.MethodDeclaration( + default(SyntaxList), + modifiers, + returnType, + default(ExplicitInterfaceSpecifierSyntax), + identifier, + default(TypeParameterListSyntax), + parameterList, + default(SyntaxList), + default(BlockSyntax), + expressionBody, + SemicolonToken()); + } - public static ConversionOperatorDeclarationSyntax ImplicitConversionOperatorDeclaration( - SyntaxTokenList modifiers, - TypeSyntax type, - ParameterListSyntax parameterList, - BlockSyntax body) - { - return SyntaxFactory.ConversionOperatorDeclaration( - default(SyntaxList), - modifiers, - Token(SyntaxKind.ImplicitKeyword), - type, - parameterList, - body, - default(ArrowExpressionClauseSyntax)); - } + public static OperatorDeclarationSyntax OperatorDeclaration( + SyntaxTokenList modifiers, + TypeSyntax returnType, + SyntaxToken operatorToken, + ParameterListSyntax parameterList, + BlockSyntax body) + { + return SyntaxFactory.OperatorDeclaration( + default(SyntaxList), + modifiers, + returnType, + operatorToken, + parameterList, + body, + default(ArrowExpressionClauseSyntax)); + } - public static ConversionOperatorDeclarationSyntax ImplicitConversionOperatorDeclaration( - SyntaxTokenList modifiers, - TypeSyntax type, - ParameterListSyntax parameterList, - ArrowExpressionClauseSyntax expressionBody) - { - return SyntaxFactory.ConversionOperatorDeclaration( - default(SyntaxList), - modifiers, - Token(SyntaxKind.ImplicitKeyword), - Token(SyntaxKind.OperatorKeyword), - type, - parameterList, - default(BlockSyntax), - expressionBody, - SemicolonToken()); - } + public static OperatorDeclarationSyntax OperatorDeclaration( + SyntaxTokenList modifiers, + TypeSyntax returnType, + SyntaxToken operatorToken, + ParameterListSyntax parameterList, + ArrowExpressionClauseSyntax expressionBody) + { + return SyntaxFactory.OperatorDeclaration( + default(SyntaxList), + modifiers, + returnType, + Token(SyntaxKind.OperatorKeyword), + operatorToken, + parameterList, + default(BlockSyntax), + expressionBody, + SemicolonToken()); + } - public static ConversionOperatorDeclarationSyntax ExplicitConversionOperatorDeclaration( - SyntaxTokenList modifiers, - TypeSyntax type, - ParameterListSyntax parameterList, - BlockSyntax body) - { - return SyntaxFactory.ConversionOperatorDeclaration( - default(SyntaxList), - modifiers, - Token(SyntaxKind.ExplicitKeyword), - type, - parameterList, - body, - default(ArrowExpressionClauseSyntax)); - } + public static ConversionOperatorDeclarationSyntax ImplicitConversionOperatorDeclaration( + SyntaxTokenList modifiers, + TypeSyntax type, + ParameterListSyntax parameterList, + BlockSyntax body) + { + return SyntaxFactory.ConversionOperatorDeclaration( + default(SyntaxList), + modifiers, + Token(SyntaxKind.ImplicitKeyword), + type, + parameterList, + body, + default(ArrowExpressionClauseSyntax)); + } - public static ConversionOperatorDeclarationSyntax ExplicitConversionOperatorDeclaration( - SyntaxTokenList modifiers, - TypeSyntax type, - ParameterListSyntax parameterList, - ArrowExpressionClauseSyntax expressionBody) - { - return SyntaxFactory.ConversionOperatorDeclaration( - default(SyntaxList), - modifiers, - Token(SyntaxKind.ExplicitKeyword), - Token(SyntaxKind.OperatorKeyword), - type, - parameterList, - default(BlockSyntax), - expressionBody, - SemicolonToken()); - } + public static ConversionOperatorDeclarationSyntax ImplicitConversionOperatorDeclaration( + SyntaxTokenList modifiers, + TypeSyntax type, + ParameterListSyntax parameterList, + ArrowExpressionClauseSyntax expressionBody) + { + return SyntaxFactory.ConversionOperatorDeclaration( + default(SyntaxList), + modifiers, + Token(SyntaxKind.ImplicitKeyword), + Token(SyntaxKind.OperatorKeyword), + type, + parameterList, + default(BlockSyntax), + expressionBody, + SemicolonToken()); + } - public static PropertyDeclarationSyntax PropertyDeclaration( - SyntaxTokenList modifiers, - TypeSyntax type, - SyntaxToken identifier, - AccessorListSyntax accessorList, - ExpressionSyntax value = null) - { - return SyntaxFactory.PropertyDeclaration( - default(SyntaxList), - modifiers, - type, - default(ExplicitInterfaceSpecifierSyntax), - identifier, - accessorList, - default(ArrowExpressionClauseSyntax), - (value != null) ? EqualsValueClause(value) : default, - (value != null) ? SemicolonToken() : default); - } + public static ConversionOperatorDeclarationSyntax ExplicitConversionOperatorDeclaration( + SyntaxTokenList modifiers, + TypeSyntax type, + ParameterListSyntax parameterList, + BlockSyntax body) + { + return SyntaxFactory.ConversionOperatorDeclaration( + default(SyntaxList), + modifiers, + Token(SyntaxKind.ExplicitKeyword), + type, + parameterList, + body, + default(ArrowExpressionClauseSyntax)); + } - public static PropertyDeclarationSyntax PropertyDeclaration( - SyntaxTokenList modifiers, - TypeSyntax type, - SyntaxToken identifier, - ArrowExpressionClauseSyntax expressionBody) - { - return SyntaxFactory.PropertyDeclaration( - default(SyntaxList), - modifiers, - type, - default(ExplicitInterfaceSpecifierSyntax), - identifier, - default(AccessorListSyntax), - expressionBody, - default(EqualsValueClauseSyntax), - SemicolonToken()); - } + public static ConversionOperatorDeclarationSyntax ExplicitConversionOperatorDeclaration( + SyntaxTokenList modifiers, + TypeSyntax type, + ParameterListSyntax parameterList, + ArrowExpressionClauseSyntax expressionBody) + { + return SyntaxFactory.ConversionOperatorDeclaration( + default(SyntaxList), + modifiers, + Token(SyntaxKind.ExplicitKeyword), + Token(SyntaxKind.OperatorKeyword), + type, + parameterList, + default(BlockSyntax), + expressionBody, + SemicolonToken()); + } - public static IndexerDeclarationSyntax IndexerDeclaration( - SyntaxTokenList modifiers, - TypeSyntax type, - BracketedParameterListSyntax parameterList, - AccessorListSyntax accessorList) - { - return SyntaxFactory.IndexerDeclaration( - default(SyntaxList), - modifiers, - type, - default(ExplicitInterfaceSpecifierSyntax), - parameterList, - accessorList); - } + public static PropertyDeclarationSyntax PropertyDeclaration( + SyntaxTokenList modifiers, + TypeSyntax type, + SyntaxToken identifier, + AccessorListSyntax accessorList, + ExpressionSyntax value = null) + { + return SyntaxFactory.PropertyDeclaration( + default(SyntaxList), + modifiers, + type, + default(ExplicitInterfaceSpecifierSyntax), + identifier, + accessorList, + default(ArrowExpressionClauseSyntax), + (value is not null) ? EqualsValueClause(value) : default, + (value is not null) ? SemicolonToken() : default); + } - public static IndexerDeclarationSyntax IndexerDeclaration( - SyntaxTokenList modifiers, - TypeSyntax type, - BracketedParameterListSyntax parameterList, - ArrowExpressionClauseSyntax expressionBody) - { - return SyntaxFactory.IndexerDeclaration( - default(SyntaxList), - modifiers, - type, - default(ExplicitInterfaceSpecifierSyntax), - Token(SyntaxKind.ThisKeyword), - parameterList, - default(AccessorListSyntax), - expressionBody, - SemicolonToken()); - } - #endregion MemberDeclaration + public static PropertyDeclarationSyntax PropertyDeclaration( + SyntaxTokenList modifiers, + TypeSyntax type, + SyntaxToken identifier, + ArrowExpressionClauseSyntax expressionBody) + { + return SyntaxFactory.PropertyDeclaration( + default(SyntaxList), + modifiers, + type, + default(ExplicitInterfaceSpecifierSyntax), + identifier, + default(AccessorListSyntax), + expressionBody, + default(EqualsValueClauseSyntax), + SemicolonToken()); + } - #region AccessorDeclaration - public static AccessorDeclarationSyntax GetAccessorDeclaration(BlockSyntax body) - { - return GetAccessorDeclaration(default(SyntaxTokenList), body); - } + public static IndexerDeclarationSyntax IndexerDeclaration( + SyntaxTokenList modifiers, + TypeSyntax type, + BracketedParameterListSyntax parameterList, + AccessorListSyntax accessorList) + { + return SyntaxFactory.IndexerDeclaration( + default(SyntaxList), + modifiers, + type, + default(ExplicitInterfaceSpecifierSyntax), + parameterList, + accessorList); + } - public static AccessorDeclarationSyntax GetAccessorDeclaration(SyntaxTokenList modifiers, BlockSyntax body) - { - return AccessorDeclaration( - SyntaxKind.GetAccessorDeclaration, - default(SyntaxList), - modifiers, - body); - } + public static IndexerDeclarationSyntax IndexerDeclaration( + SyntaxTokenList modifiers, + TypeSyntax type, + BracketedParameterListSyntax parameterList, + ArrowExpressionClauseSyntax expressionBody) + { + return SyntaxFactory.IndexerDeclaration( + default(SyntaxList), + modifiers, + type, + default(ExplicitInterfaceSpecifierSyntax), + Token(SyntaxKind.ThisKeyword), + parameterList, + default(AccessorListSyntax), + expressionBody, + SemicolonToken()); + } + #endregion MemberDeclaration - public static AccessorDeclarationSyntax GetAccessorDeclaration(ArrowExpressionClauseSyntax expressionBody) - { - return GetAccessorDeclaration(default(SyntaxTokenList), expressionBody); - } + #region AccessorDeclaration + public static AccessorDeclarationSyntax GetAccessorDeclaration(BlockSyntax body) + { + return GetAccessorDeclaration(default(SyntaxTokenList), body); + } - public static AccessorDeclarationSyntax GetAccessorDeclaration(SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) - { - return AccessorDeclaration( - SyntaxKind.GetAccessorDeclaration, - default(SyntaxList), - modifiers, - Token(SyntaxKind.GetKeyword), - expressionBody, - SemicolonToken()); - } + public static AccessorDeclarationSyntax GetAccessorDeclaration(SyntaxTokenList modifiers, BlockSyntax body) + { + return AccessorDeclaration( + SyntaxKind.GetAccessorDeclaration, + default(SyntaxList), + modifiers, + body); + } - public static AccessorDeclarationSyntax SetAccessorDeclaration(BlockSyntax body) - { - return SetAccessorDeclaration(default(SyntaxTokenList), body); - } + public static AccessorDeclarationSyntax GetAccessorDeclaration(ArrowExpressionClauseSyntax expressionBody) + { + return GetAccessorDeclaration(default(SyntaxTokenList), expressionBody); + } - public static AccessorDeclarationSyntax SetAccessorDeclaration(SyntaxTokenList modifiers, BlockSyntax body) - { - return AccessorDeclaration( - SyntaxKind.SetAccessorDeclaration, - default(SyntaxList), - modifiers, - body); - } + public static AccessorDeclarationSyntax GetAccessorDeclaration(SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) + { + return AccessorDeclaration( + SyntaxKind.GetAccessorDeclaration, + default(SyntaxList), + modifiers, + Token(SyntaxKind.GetKeyword), + expressionBody, + SemicolonToken()); + } - public static AccessorDeclarationSyntax SetAccessorDeclaration(ArrowExpressionClauseSyntax expressionBody) - { - return SetAccessorDeclaration(default(SyntaxTokenList), expressionBody); - } + public static AccessorDeclarationSyntax SetAccessorDeclaration(BlockSyntax body) + { + return SetAccessorDeclaration(default(SyntaxTokenList), body); + } - public static AccessorDeclarationSyntax SetAccessorDeclaration(SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) - { - return AccessorDeclaration( - SyntaxKind.SetAccessorDeclaration, - default(SyntaxList), - modifiers, - Token(SyntaxKind.SetKeyword), - expressionBody, - SemicolonToken()); - } + public static AccessorDeclarationSyntax SetAccessorDeclaration(SyntaxTokenList modifiers, BlockSyntax body) + { + return AccessorDeclaration( + SyntaxKind.SetAccessorDeclaration, + default(SyntaxList), + modifiers, + body); + } - public static AccessorDeclarationSyntax AddAccessorDeclaration(BlockSyntax body) - { - return AddAccessorDeclaration(default(SyntaxTokenList), body); - } + public static AccessorDeclarationSyntax SetAccessorDeclaration(ArrowExpressionClauseSyntax expressionBody) + { + return SetAccessorDeclaration(default(SyntaxTokenList), expressionBody); + } - public static AccessorDeclarationSyntax AddAccessorDeclaration(SyntaxTokenList modifiers, BlockSyntax body) - { - return AccessorDeclaration( - SyntaxKind.AddAccessorDeclaration, - default(SyntaxList), - modifiers, - body); - } + public static AccessorDeclarationSyntax SetAccessorDeclaration(SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) + { + return AccessorDeclaration( + SyntaxKind.SetAccessorDeclaration, + default(SyntaxList), + modifiers, + Token(SyntaxKind.SetKeyword), + expressionBody, + SemicolonToken()); + } - public static AccessorDeclarationSyntax AddAccessorDeclaration(ArrowExpressionClauseSyntax expressionBody) - { - return AddAccessorDeclaration(default(SyntaxTokenList), expressionBody); - } + public static AccessorDeclarationSyntax AddAccessorDeclaration(BlockSyntax body) + { + return AddAccessorDeclaration(default(SyntaxTokenList), body); + } - public static AccessorDeclarationSyntax AddAccessorDeclaration(SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) - { - return AccessorDeclaration( - SyntaxKind.AddAccessorDeclaration, - default(SyntaxList), - modifiers, - Token(SyntaxKind.AddKeyword), - expressionBody, - SemicolonToken()); - } + public static AccessorDeclarationSyntax AddAccessorDeclaration(SyntaxTokenList modifiers, BlockSyntax body) + { + return AccessorDeclaration( + SyntaxKind.AddAccessorDeclaration, + default(SyntaxList), + modifiers, + body); + } - public static AccessorDeclarationSyntax RemoveAccessorDeclaration(BlockSyntax body) - { - return RemoveAccessorDeclaration(default(SyntaxTokenList), body); - } + public static AccessorDeclarationSyntax AddAccessorDeclaration(ArrowExpressionClauseSyntax expressionBody) + { + return AddAccessorDeclaration(default(SyntaxTokenList), expressionBody); + } - public static AccessorDeclarationSyntax RemoveAccessorDeclaration(SyntaxTokenList modifiers, BlockSyntax body) - { - return AccessorDeclaration( - SyntaxKind.RemoveAccessorDeclaration, - default(SyntaxList), - modifiers, - body); - } + public static AccessorDeclarationSyntax AddAccessorDeclaration(SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) + { + return AccessorDeclaration( + SyntaxKind.AddAccessorDeclaration, + default(SyntaxList), + modifiers, + Token(SyntaxKind.AddKeyword), + expressionBody, + SemicolonToken()); + } - public static AccessorDeclarationSyntax RemoveAccessorDeclaration(ArrowExpressionClauseSyntax expressionBody) - { - return RemoveAccessorDeclaration(default(SyntaxTokenList), expressionBody); - } + public static AccessorDeclarationSyntax RemoveAccessorDeclaration(BlockSyntax body) + { + return RemoveAccessorDeclaration(default(SyntaxTokenList), body); + } - public static AccessorDeclarationSyntax RemoveAccessorDeclaration(SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) - { - return AccessorDeclaration( - SyntaxKind.RemoveAccessorDeclaration, - default(SyntaxList), - modifiers, - Token(SyntaxKind.RemoveKeyword), - expressionBody, - SemicolonToken()); - } + public static AccessorDeclarationSyntax RemoveAccessorDeclaration(SyntaxTokenList modifiers, BlockSyntax body) + { + return AccessorDeclaration( + SyntaxKind.RemoveAccessorDeclaration, + default(SyntaxList), + modifiers, + body); + } - public static AccessorDeclarationSyntax AutoGetAccessorDeclaration(SyntaxTokenList modifiers = default) - { - return AutoAccessorDeclaration(SyntaxKind.GetAccessorDeclaration, modifiers); - } + public static AccessorDeclarationSyntax RemoveAccessorDeclaration(ArrowExpressionClauseSyntax expressionBody) + { + return RemoveAccessorDeclaration(default(SyntaxTokenList), expressionBody); + } - public static AccessorDeclarationSyntax AutoSetAccessorDeclaration(SyntaxTokenList modifiers = default) - { - return AutoAccessorDeclaration(SyntaxKind.SetAccessorDeclaration, modifiers); - } + public static AccessorDeclarationSyntax RemoveAccessorDeclaration(SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody) + { + return AccessorDeclaration( + SyntaxKind.RemoveAccessorDeclaration, + default(SyntaxList), + modifiers, + Token(SyntaxKind.RemoveKeyword), + expressionBody, + SemicolonToken()); + } - public static AccessorDeclarationSyntax AutoInitAccessorDeclaration(SyntaxTokenList modifiers = default) - { - return AutoAccessorDeclaration(SyntaxKind.InitAccessorDeclaration, modifiers); - } + public static AccessorDeclarationSyntax AutoGetAccessorDeclaration(SyntaxTokenList modifiers = default) + { + return AutoAccessorDeclaration(SyntaxKind.GetAccessorDeclaration, modifiers); + } - internal static AccessorDeclarationSyntax AutoAccessorDeclaration(SyntaxKind kind, SyntaxTokenList modifiers = default) - { - return AccessorDeclaration( - kind, - default(SyntaxList), - modifiers, - Token(AccessorDeclarationKeywordKind(kind)), - default(BlockSyntax), - SemicolonToken()); - } + public static AccessorDeclarationSyntax AutoSetAccessorDeclaration(SyntaxTokenList modifiers = default) + { + return AutoAccessorDeclaration(SyntaxKind.SetAccessorDeclaration, modifiers); + } - private static SyntaxKind AccessorDeclarationKeywordKind(SyntaxKind kind) - { - switch (kind) - { - case SyntaxKind.GetAccessorDeclaration: - return SyntaxKind.GetKeyword; - case SyntaxKind.SetAccessorDeclaration: - return SyntaxKind.SetKeyword; - case SyntaxKind.InitAccessorDeclaration: - return SyntaxKind.InitKeyword; - case SyntaxKind.AddAccessorDeclaration: - return SyntaxKind.AddKeyword; - case SyntaxKind.RemoveAccessorDeclaration: - return SyntaxKind.RemoveKeyword; - case SyntaxKind.UnknownAccessorDeclaration: - return SyntaxKind.IdentifierToken; - default: - throw new ArgumentOutOfRangeException(nameof(kind)); + public static AccessorDeclarationSyntax AutoInitAccessorDeclaration(SyntaxTokenList modifiers = default) + { + return AutoAccessorDeclaration(SyntaxKind.InitAccessorDeclaration, modifiers); } - } - #endregion AccessorDeclaration - #region Statement - public static LocalDeclarationStatementSyntax LocalDeclarationStatement(TypeSyntax type, string identifier, ExpressionSyntax value = null) - { - return LocalDeclarationStatement(type, Identifier(identifier), value); - } + internal static AccessorDeclarationSyntax AutoAccessorDeclaration(SyntaxKind kind, SyntaxTokenList modifiers = default) + { + return AccessorDeclaration( + kind, + default(SyntaxList), + modifiers, + Token(AccessorDeclarationKeywordKind(kind)), + default(BlockSyntax), + SemicolonToken()); + } - public static LocalDeclarationStatementSyntax LocalDeclarationStatement(TypeSyntax type, SyntaxToken identifier, ExpressionSyntax value = null) - { - VariableDeclaratorSyntax variableDeclarator = (value != null) - ? VariableDeclarator(identifier, EqualsValueClause(value)) - : SyntaxFactory.VariableDeclarator(identifier); + private static SyntaxKind AccessorDeclarationKeywordKind(SyntaxKind kind) + { + switch (kind) + { + case SyntaxKind.GetAccessorDeclaration: + return SyntaxKind.GetKeyword; + case SyntaxKind.SetAccessorDeclaration: + return SyntaxKind.SetKeyword; + case SyntaxKind.InitAccessorDeclaration: + return SyntaxKind.InitKeyword; + case SyntaxKind.AddAccessorDeclaration: + return SyntaxKind.AddKeyword; + case SyntaxKind.RemoveAccessorDeclaration: + return SyntaxKind.RemoveKeyword; + case SyntaxKind.UnknownAccessorDeclaration: + return SyntaxKind.IdentifierToken; + default: + throw new ArgumentOutOfRangeException(nameof(kind)); + } + } + #endregion AccessorDeclaration - return SyntaxFactory.LocalDeclarationStatement( - SyntaxFactory.VariableDeclaration( - type, - SingletonSeparatedList(variableDeclarator))); - } + #region Statement + public static LocalDeclarationStatementSyntax LocalDeclarationStatement(TypeSyntax type, string identifier, ExpressionSyntax value = null) + { + return LocalDeclarationStatement(type, Identifier(identifier), value); + } - public static LocalDeclarationStatementSyntax LocalDeclarationStatement(TypeSyntax type, string identifier, EqualsValueClauseSyntax initializer) - { - return LocalDeclarationStatement(type, Identifier(identifier), initializer); - } + public static LocalDeclarationStatementSyntax LocalDeclarationStatement(TypeSyntax type, SyntaxToken identifier, ExpressionSyntax value = null) + { + VariableDeclaratorSyntax variableDeclarator = (value is not null) + ? VariableDeclarator(identifier, EqualsValueClause(value)) + : SyntaxFactory.VariableDeclarator(identifier); + + return SyntaxFactory.LocalDeclarationStatement( + SyntaxFactory.VariableDeclaration( + type, + SingletonSeparatedList(variableDeclarator))); + } - public static LocalDeclarationStatementSyntax LocalDeclarationStatement(TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax initializer) - { - return SyntaxFactory.LocalDeclarationStatement( - SyntaxFactory.VariableDeclaration( - type, - SingletonSeparatedList(VariableDeclarator(identifier, initializer)))); - } + public static LocalDeclarationStatementSyntax LocalDeclarationStatement(TypeSyntax type, string identifier, EqualsValueClauseSyntax initializer) + { + return LocalDeclarationStatement(type, Identifier(identifier), initializer); + } - public static YieldStatementSyntax YieldReturnStatement(ExpressionSyntax expression) - { - return YieldStatement(SyntaxKind.YieldReturnStatement, expression); - } + public static LocalDeclarationStatementSyntax LocalDeclarationStatement(TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax initializer) + { + return SyntaxFactory.LocalDeclarationStatement( + SyntaxFactory.VariableDeclaration( + type, + SingletonSeparatedList(VariableDeclarator(identifier, initializer)))); + } - public static YieldStatementSyntax YieldBreakStatement() - { - return YieldStatement(SyntaxKind.YieldBreakStatement); - } + public static YieldStatementSyntax YieldReturnStatement(ExpressionSyntax expression) + { + return YieldStatement(SyntaxKind.YieldReturnStatement, expression); + } - public static TryStatementSyntax TryStatement(BlockSyntax block, CatchClauseSyntax @catch, FinallyClauseSyntax @finally = null) - { - return SyntaxFactory.TryStatement(block, SingletonList(@catch), @finally); - } + public static YieldStatementSyntax YieldBreakStatement() + { + return YieldStatement(SyntaxKind.YieldBreakStatement); + } - public static ExpressionStatementSyntax SimpleAssignmentStatement(ExpressionSyntax left, ExpressionSyntax right) - { - return ExpressionStatement(SimpleAssignmentExpression(left, right)); - } + public static TryStatementSyntax TryStatement(BlockSyntax block, CatchClauseSyntax @catch, FinallyClauseSyntax @finally = null) + { + return SyntaxFactory.TryStatement(block, SingletonList(@catch), @finally); + } - public static ExpressionStatementSyntax SimpleAssignmentStatement(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return ExpressionStatement(SimpleAssignmentExpression(left, operatorToken, right)); - } + public static ExpressionStatementSyntax SimpleAssignmentStatement(ExpressionSyntax left, ExpressionSyntax right) + { + return ExpressionStatement(SimpleAssignmentExpression(left, right)); + } - public static BlockSyntax Block(StatementSyntax statement) - { - return SyntaxFactory.Block(SingletonList(statement)); - } + public static ExpressionStatementSyntax SimpleAssignmentStatement(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return ExpressionStatement(SimpleAssignmentExpression(left, operatorToken, right)); + } - public static BlockSyntax Block(SyntaxToken openBrace, StatementSyntax statement, SyntaxToken closeBrace) - { - return SyntaxFactory.Block(openBrace, SingletonList(statement), closeBrace); - } + public static BlockSyntax Block(StatementSyntax statement) + { + return SyntaxFactory.Block(SingletonList(statement)); + } - public static LocalFunctionStatementSyntax LocalFunctionStatement( - SyntaxTokenList modifiers, - TypeSyntax returnType, - SyntaxToken identifier, - ParameterListSyntax parameterList, - BlockSyntax body) - { - return SyntaxFactory.LocalFunctionStatement( - modifiers, - returnType, - identifier, - default(TypeParameterListSyntax), - parameterList, - default(SyntaxList), - body, - default(ArrowExpressionClauseSyntax)); - } + public static BlockSyntax Block(SyntaxToken openBrace, StatementSyntax statement, SyntaxToken closeBrace) + { + return SyntaxFactory.Block(openBrace, SingletonList(statement), closeBrace); + } - public static LocalFunctionStatementSyntax LocalFunctionStatement( - SyntaxTokenList modifiers, - TypeSyntax returnType, - SyntaxToken identifier, - ParameterListSyntax parameterList, - ArrowExpressionClauseSyntax expressionBody) - { - return SyntaxFactory.LocalFunctionStatement( - modifiers, - returnType, - identifier, - default(TypeParameterListSyntax), - parameterList, - default(SyntaxList), - default(BlockSyntax), - expressionBody, - SemicolonToken()); - } + public static LocalFunctionStatementSyntax LocalFunctionStatement( + SyntaxTokenList modifiers, + TypeSyntax returnType, + SyntaxToken identifier, + ParameterListSyntax parameterList, + BlockSyntax body) + { + return SyntaxFactory.LocalFunctionStatement( + modifiers, + returnType, + identifier, + default(TypeParameterListSyntax), + parameterList, + default(SyntaxList), + body, + default(ArrowExpressionClauseSyntax)); + } - internal static ThrowStatementSyntax ThrowNewStatement(TypeSyntax exceptionType) - { - return ThrowStatement(ObjectCreationExpression(exceptionType, ArgumentList())); - } + public static LocalFunctionStatementSyntax LocalFunctionStatement( + SyntaxTokenList modifiers, + TypeSyntax returnType, + SyntaxToken identifier, + ParameterListSyntax parameterList, + ArrowExpressionClauseSyntax expressionBody) + { + return SyntaxFactory.LocalFunctionStatement( + modifiers, + returnType, + identifier, + default(TypeParameterListSyntax), + parameterList, + default(SyntaxList), + default(BlockSyntax), + expressionBody, + SemicolonToken()); + } - public static ForStatementSyntax ForStatement( - VariableDeclarationSyntax declaration, - ExpressionSyntax condition, - ExpressionSyntax incrementor, - StatementSyntax statement) - { - return SyntaxFactory.ForStatement( - declaration: declaration, - initializers: default(SeparatedSyntaxList), - condition: condition, - incrementors: SingletonSeparatedList(incrementor), - statement: statement); - } - #endregion Statement + internal static ThrowStatementSyntax ThrowNewStatement(TypeSyntax exceptionType) + { + return ThrowStatement(ObjectCreationExpression(exceptionType, ArgumentList())); + } - #region BinaryExpression - public static BinaryExpressionSyntax AddExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.AddExpression, left, right); - } + public static ForStatementSyntax ForStatement( + VariableDeclarationSyntax declaration, + ExpressionSyntax condition, + ExpressionSyntax incrementor, + StatementSyntax statement) + { + return SyntaxFactory.ForStatement( + declaration: declaration, + initializers: default(SeparatedSyntaxList), + condition: condition, + incrementors: SingletonSeparatedList(incrementor), + statement: statement); + } + #endregion Statement - public static BinaryExpressionSyntax AddExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.AddExpression, left, operatorToken, right); - } + #region BinaryExpression + public static BinaryExpressionSyntax AddExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.AddExpression, left, right); + } - public static BinaryExpressionSyntax SubtractExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.SubtractExpression, left, right); - } + public static BinaryExpressionSyntax AddExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.AddExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax SubtractExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.SubtractExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax SubtractExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.SubtractExpression, left, right); + } - public static BinaryExpressionSyntax MultiplyExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.MultiplyExpression, left, right); - } + public static BinaryExpressionSyntax SubtractExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.SubtractExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax MultiplyExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.MultiplyExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax MultiplyExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.MultiplyExpression, left, right); + } - public static BinaryExpressionSyntax DivideExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.DivideExpression, left, right); - } + public static BinaryExpressionSyntax MultiplyExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.MultiplyExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax DivideExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.DivideExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax DivideExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.DivideExpression, left, right); + } - public static BinaryExpressionSyntax ModuloExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.ModuloExpression, left, right); - } + public static BinaryExpressionSyntax DivideExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.DivideExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax ModuloExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.ModuloExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax ModuloExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.ModuloExpression, left, right); + } - public static BinaryExpressionSyntax LeftShiftExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LeftShiftExpression, left, right); - } + public static BinaryExpressionSyntax ModuloExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.ModuloExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax LeftShiftExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LeftShiftExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax LeftShiftExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LeftShiftExpression, left, right); + } - public static BinaryExpressionSyntax RightShiftExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.RightShiftExpression, left, right); - } + public static BinaryExpressionSyntax LeftShiftExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LeftShiftExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax RightShiftExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.RightShiftExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax RightShiftExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.RightShiftExpression, left, right); + } - public static BinaryExpressionSyntax LogicalOrExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LogicalOrExpression, left, right); - } + public static BinaryExpressionSyntax RightShiftExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.RightShiftExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax LogicalOrExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LogicalOrExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax LogicalOrExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LogicalOrExpression, left, right); + } - public static BinaryExpressionSyntax LogicalAndExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LogicalAndExpression, left, right); - } + public static BinaryExpressionSyntax LogicalOrExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LogicalOrExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax LogicalAndExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LogicalAndExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax LogicalAndExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LogicalAndExpression, left, right); + } - public static BinaryExpressionSyntax BitwiseOrExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.BitwiseOrExpression, left, right); - } + public static BinaryExpressionSyntax LogicalAndExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LogicalAndExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax BitwiseOrExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.BitwiseOrExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax BitwiseOrExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.BitwiseOrExpression, left, right); + } - public static BinaryExpressionSyntax BitwiseAndExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.BitwiseAndExpression, left, right); - } + public static BinaryExpressionSyntax BitwiseOrExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.BitwiseOrExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax BitwiseAndExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.BitwiseAndExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax BitwiseAndExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.BitwiseAndExpression, left, right); + } - public static BinaryExpressionSyntax ExclusiveOrExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.ExclusiveOrExpression, left, right); - } + public static BinaryExpressionSyntax BitwiseAndExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.BitwiseAndExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax ExclusiveOrExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.ExclusiveOrExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax ExclusiveOrExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.ExclusiveOrExpression, left, right); + } - public static BinaryExpressionSyntax EqualsExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.EqualsExpression, left, right); - } + public static BinaryExpressionSyntax ExclusiveOrExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.ExclusiveOrExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax EqualsExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.EqualsExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax EqualsExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.EqualsExpression, left, right); + } - public static BinaryExpressionSyntax NotEqualsExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.NotEqualsExpression, left, right); - } + public static BinaryExpressionSyntax EqualsExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.EqualsExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax NotEqualsExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.NotEqualsExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax NotEqualsExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.NotEqualsExpression, left, right); + } - public static BinaryExpressionSyntax LessThanExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LessThanExpression, left, right); - } + public static BinaryExpressionSyntax NotEqualsExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.NotEqualsExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax LessThanExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LessThanExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax LessThanExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LessThanExpression, left, right); + } - public static BinaryExpressionSyntax LessThanOrEqualExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, right); - } + public static BinaryExpressionSyntax LessThanExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LessThanExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax LessThanOrEqualExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax LessThanOrEqualExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, right); + } - public static BinaryExpressionSyntax GreaterThanExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.GreaterThanExpression, left, right); - } + public static BinaryExpressionSyntax LessThanOrEqualExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax GreaterThanExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.GreaterThanExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax GreaterThanExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.GreaterThanExpression, left, right); + } - public static BinaryExpressionSyntax GreaterThanOrEqualExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, right); - } + public static BinaryExpressionSyntax GreaterThanExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.GreaterThanExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax GreaterThanOrEqualExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax GreaterThanOrEqualExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, right); + } - public static BinaryExpressionSyntax IsExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.IsExpression, left, right); - } + public static BinaryExpressionSyntax GreaterThanOrEqualExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax IsExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.IsExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax IsExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.IsExpression, left, right); + } - public static BinaryExpressionSyntax AsExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.AsExpression, left, right); - } + public static BinaryExpressionSyntax IsExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.IsExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax AsExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.AsExpression, left, operatorToken, right); - } + public static BinaryExpressionSyntax AsExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.AsExpression, left, right); + } - public static BinaryExpressionSyntax CoalesceExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.CoalesceExpression, left, right); - } + public static BinaryExpressionSyntax AsExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.AsExpression, left, operatorToken, right); + } - public static BinaryExpressionSyntax CoalesceExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return BinaryExpression(SyntaxKind.CoalesceExpression, left, operatorToken, right); - } - #endregion BinaryExpression + public static BinaryExpressionSyntax CoalesceExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.CoalesceExpression, left, right); + } - #region PrefixUnaryExpression - public static PrefixUnaryExpressionSyntax UnaryPlusExpression(ExpressionSyntax operand) - { - return PrefixUnaryExpression(SyntaxKind.UnaryPlusExpression, operand); - } + public static BinaryExpressionSyntax CoalesceExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return BinaryExpression(SyntaxKind.CoalesceExpression, left, operatorToken, right); + } + #endregion BinaryExpression - public static PrefixUnaryExpressionSyntax UnaryPlusExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PrefixUnaryExpression(SyntaxKind.UnaryPlusExpression, operatorToken, operand); - } + #region PrefixUnaryExpression + public static PrefixUnaryExpressionSyntax UnaryPlusExpression(ExpressionSyntax operand) + { + return PrefixUnaryExpression(SyntaxKind.UnaryPlusExpression, operand); + } - public static PrefixUnaryExpressionSyntax UnaryMinusExpression(ExpressionSyntax operand) - { - return PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, operand); - } + public static PrefixUnaryExpressionSyntax UnaryPlusExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PrefixUnaryExpression(SyntaxKind.UnaryPlusExpression, operatorToken, operand); + } - public static PrefixUnaryExpressionSyntax UnaryMinusExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, operatorToken, operand); - } + public static PrefixUnaryExpressionSyntax UnaryMinusExpression(ExpressionSyntax operand) + { + return PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, operand); + } - public static PrefixUnaryExpressionSyntax BitwiseNotExpression(ExpressionSyntax operand) - { - return PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, operand); - } + public static PrefixUnaryExpressionSyntax UnaryMinusExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, operatorToken, operand); + } - public static PrefixUnaryExpressionSyntax BitwiseNotExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, operatorToken, operand); - } + public static PrefixUnaryExpressionSyntax BitwiseNotExpression(ExpressionSyntax operand) + { + return PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, operand); + } - public static PrefixUnaryExpressionSyntax LogicalNotExpression(ExpressionSyntax operand) - { - return PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, operand); - } + public static PrefixUnaryExpressionSyntax BitwiseNotExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, operatorToken, operand); + } - public static PrefixUnaryExpressionSyntax LogicalNotExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, operatorToken, operand); - } + public static PrefixUnaryExpressionSyntax LogicalNotExpression(ExpressionSyntax operand) + { + return PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, operand); + } - public static PrefixUnaryExpressionSyntax PreIncrementExpression(ExpressionSyntax operand) - { - return PrefixUnaryExpression(SyntaxKind.PreIncrementExpression, operand); - } + public static PrefixUnaryExpressionSyntax LogicalNotExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, operatorToken, operand); + } - public static PrefixUnaryExpressionSyntax PreIncrementExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PrefixUnaryExpression(SyntaxKind.PreIncrementExpression, operatorToken, operand); - } + public static PrefixUnaryExpressionSyntax PreIncrementExpression(ExpressionSyntax operand) + { + return PrefixUnaryExpression(SyntaxKind.PreIncrementExpression, operand); + } - public static PrefixUnaryExpressionSyntax PreDecrementExpression(ExpressionSyntax operand) - { - return PrefixUnaryExpression(SyntaxKind.PreDecrementExpression, operand); - } + public static PrefixUnaryExpressionSyntax PreIncrementExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PrefixUnaryExpression(SyntaxKind.PreIncrementExpression, operatorToken, operand); + } - public static PrefixUnaryExpressionSyntax PreDecrementExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PrefixUnaryExpression(SyntaxKind.PreDecrementExpression, operatorToken, operand); - } + public static PrefixUnaryExpressionSyntax PreDecrementExpression(ExpressionSyntax operand) + { + return PrefixUnaryExpression(SyntaxKind.PreDecrementExpression, operand); + } - public static PrefixUnaryExpressionSyntax AddressOfExpression(ExpressionSyntax operand) - { - return PrefixUnaryExpression(SyntaxKind.AddressOfExpression, operand); - } + public static PrefixUnaryExpressionSyntax PreDecrementExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PrefixUnaryExpression(SyntaxKind.PreDecrementExpression, operatorToken, operand); + } - public static PrefixUnaryExpressionSyntax AddressOfExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PrefixUnaryExpression(SyntaxKind.AddressOfExpression, operatorToken, operand); - } + public static PrefixUnaryExpressionSyntax AddressOfExpression(ExpressionSyntax operand) + { + return PrefixUnaryExpression(SyntaxKind.AddressOfExpression, operand); + } - public static PrefixUnaryExpressionSyntax PointerIndirectionExpression(ExpressionSyntax operand) - { - return PrefixUnaryExpression(SyntaxKind.PointerIndirectionExpression, operand); - } + public static PrefixUnaryExpressionSyntax AddressOfExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PrefixUnaryExpression(SyntaxKind.AddressOfExpression, operatorToken, operand); + } - public static PrefixUnaryExpressionSyntax PointerIndirectionExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PrefixUnaryExpression(SyntaxKind.PointerIndirectionExpression, operatorToken, operand); - } - #endregion PrefixUnaryExpression + public static PrefixUnaryExpressionSyntax PointerIndirectionExpression(ExpressionSyntax operand) + { + return PrefixUnaryExpression(SyntaxKind.PointerIndirectionExpression, operand); + } - #region PostfixUnaryExpression - public static PostfixUnaryExpressionSyntax PostIncrementExpression(ExpressionSyntax operand) - { - return PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, operand); - } + public static PrefixUnaryExpressionSyntax PointerIndirectionExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PrefixUnaryExpression(SyntaxKind.PointerIndirectionExpression, operatorToken, operand); + } + #endregion PrefixUnaryExpression - public static PostfixUnaryExpressionSyntax PostIncrementExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, operand, operatorToken); - } + #region PostfixUnaryExpression + public static PostfixUnaryExpressionSyntax PostIncrementExpression(ExpressionSyntax operand) + { + return PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, operand); + } - public static PostfixUnaryExpressionSyntax PostDecrementExpression(ExpressionSyntax operand) - { - return PostfixUnaryExpression(SyntaxKind.PostDecrementExpression, operand); - } + public static PostfixUnaryExpressionSyntax PostIncrementExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, operand, operatorToken); + } - public static PostfixUnaryExpressionSyntax PostDecrementExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PostfixUnaryExpression(SyntaxKind.PostDecrementExpression, operand, operatorToken); - } + public static PostfixUnaryExpressionSyntax PostDecrementExpression(ExpressionSyntax operand) + { + return PostfixUnaryExpression(SyntaxKind.PostDecrementExpression, operand); + } - public static PostfixUnaryExpressionSyntax SuppressNullableWarningExpression(ExpressionSyntax operand) - { - return PostfixUnaryExpression(SyntaxKind.SuppressNullableWarningExpression, operand); - } + public static PostfixUnaryExpressionSyntax PostDecrementExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PostfixUnaryExpression(SyntaxKind.PostDecrementExpression, operand, operatorToken); + } - public static PostfixUnaryExpressionSyntax SuppressNullableWarningExpression(ExpressionSyntax operand, SyntaxToken operatorToken) - { - return PostfixUnaryExpression(SyntaxKind.SuppressNullableWarningExpression, operand, operatorToken); - } + public static PostfixUnaryExpressionSyntax SuppressNullableWarningExpression(ExpressionSyntax operand) + { + return PostfixUnaryExpression(SyntaxKind.SuppressNullableWarningExpression, operand); + } - #endregion PostfixUnaryExpression + public static PostfixUnaryExpressionSyntax SuppressNullableWarningExpression(ExpressionSyntax operand, SyntaxToken operatorToken) + { + return PostfixUnaryExpression(SyntaxKind.SuppressNullableWarningExpression, operand, operatorToken); + } - #region AssignmentExpression - public static AssignmentExpressionSyntax SimpleAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, right); - } + #endregion PostfixUnaryExpression - public static AssignmentExpressionSyntax SimpleAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, operatorToken, right); - } + #region AssignmentExpression + public static AssignmentExpressionSyntax SimpleAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax AddAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.AddAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax SimpleAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax AddAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.AddAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax AddAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.AddAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax SubtractAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax AddAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.AddAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax SubtractAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax SubtractAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax MultiplyAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.MultiplyAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax SubtractAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax MultiplyAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.MultiplyAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax MultiplyAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.MultiplyAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax DivideAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.DivideAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax MultiplyAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.MultiplyAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax DivideAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.DivideAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax DivideAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.DivideAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax ModuloAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.ModuloAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax DivideAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.DivideAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax ModuloAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.ModuloAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax ModuloAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.ModuloAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax AndAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.AndAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax ModuloAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.ModuloAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax AndAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.AndAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax AndAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.AndAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax ExclusiveOrAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.ExclusiveOrAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax AndAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.AndAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax ExclusiveOrAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.ExclusiveOrAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax ExclusiveOrAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.ExclusiveOrAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax OrAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.OrAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax ExclusiveOrAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.ExclusiveOrAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax OrAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.OrAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax OrAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.OrAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax LeftShiftAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.LeftShiftAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax OrAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.OrAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax LeftShiftAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.LeftShiftAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax LeftShiftAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.LeftShiftAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax RightShiftAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.RightShiftAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax LeftShiftAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.LeftShiftAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax RightShiftAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.RightShiftAssignmentExpression, left, operatorToken, right); - } + public static AssignmentExpressionSyntax RightShiftAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.RightShiftAssignmentExpression, left, right); + } - public static AssignmentExpressionSyntax CoalesceAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.CoalesceAssignmentExpression, left, right); - } + public static AssignmentExpressionSyntax RightShiftAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.RightShiftAssignmentExpression, left, operatorToken, right); + } - public static AssignmentExpressionSyntax CoalesceAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) - { - return AssignmentExpression(SyntaxKind.CoalesceAssignmentExpression, left, operatorToken, right); - } - #endregion AssignmentExpression + public static AssignmentExpressionSyntax CoalesceAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.CoalesceAssignmentExpression, left, right); + } - #region LiteralExpression - public static LiteralExpressionSyntax StringLiteralExpression(string value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal(value)); - } + public static AssignmentExpressionSyntax CoalesceAssignmentExpression(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) + { + return AssignmentExpression(SyntaxKind.CoalesceAssignmentExpression, left, operatorToken, right); + } + #endregion AssignmentExpression - public static LiteralExpressionSyntax CharacterLiteralExpression(char value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.CharacterLiteralExpression, - Literal(value)); - } + #region LiteralExpression + public static LiteralExpressionSyntax StringLiteralExpression(string value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax NumericLiteralExpression(int value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(value)); - } + public static LiteralExpressionSyntax CharacterLiteralExpression(char value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.CharacterLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax NumericLiteralExpression(uint value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(value)); - } + public static LiteralExpressionSyntax NumericLiteralExpression(int value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax NumericLiteralExpression(sbyte value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(value)); - } + public static LiteralExpressionSyntax NumericLiteralExpression(uint value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax NumericLiteralExpression(decimal value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(value)); - } + public static LiteralExpressionSyntax NumericLiteralExpression(sbyte value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax NumericLiteralExpression(double value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(value)); - } + public static LiteralExpressionSyntax NumericLiteralExpression(decimal value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax NumericLiteralExpression(float value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(value)); - } + public static LiteralExpressionSyntax NumericLiteralExpression(double value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax NumericLiteralExpression(long value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(value)); - } + public static LiteralExpressionSyntax NumericLiteralExpression(float value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax NumericLiteralExpression(ulong value) - { - return SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(value)); - } + public static LiteralExpressionSyntax NumericLiteralExpression(long value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(value)); + } - internal static LiteralExpressionSyntax NumericLiteralExpression(ulong value, SpecialType numericType) - { - return LiteralExpression(ConvertHelpers.ConvertFromUInt64(value, numericType)); - } + public static LiteralExpressionSyntax NumericLiteralExpression(ulong value) + { + return SyntaxFactory.LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(value)); + } - public static LiteralExpressionSyntax TrueLiteralExpression() - { - return SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression); - } + internal static LiteralExpressionSyntax NumericLiteralExpression(ulong value, SpecialType numericType) + { + return LiteralExpression(ConvertHelpers.ConvertFromUInt64(value, numericType)); + } - public static LiteralExpressionSyntax FalseLiteralExpression() - { - return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); - } + public static LiteralExpressionSyntax TrueLiteralExpression() + { + return SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression); + } - public static LiteralExpressionSyntax BooleanLiteralExpression(bool value) - { - return (value) ? TrueLiteralExpression() : FalseLiteralExpression(); - } + public static LiteralExpressionSyntax FalseLiteralExpression() + { + return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); + } - public static LiteralExpressionSyntax NullLiteralExpression() - { - return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); - } + public static LiteralExpressionSyntax BooleanLiteralExpression(bool value) + { + return (value) ? TrueLiteralExpression() : FalseLiteralExpression(); + } - public static LiteralExpressionSyntax DefaultLiteralExpression() - { - return SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression); - } + public static LiteralExpressionSyntax NullLiteralExpression() + { + return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); + } - public static LiteralExpressionSyntax LiteralExpression(object value) - { - if (value == null) - return NullLiteralExpression(); + public static LiteralExpressionSyntax DefaultLiteralExpression() + { + return SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression); + } - if (value is string stringValue) - return StringLiteralExpression(stringValue); + public static LiteralExpressionSyntax LiteralExpression(object value) + { + if (value is null) + return NullLiteralExpression(); - if (value is bool boolValue) - return (boolValue) ? TrueLiteralExpression() : FalseLiteralExpression(); + if (value is string stringValue) + return StringLiteralExpression(stringValue); - if (value is char charValue) - return CharacterLiteralExpression(charValue); + if (value is bool boolValue) + return (boolValue) ? TrueLiteralExpression() : FalseLiteralExpression(); - if (value is sbyte sbyteValue) - return NumericLiteralExpression(sbyteValue); + if (value is char charValue) + return CharacterLiteralExpression(charValue); - if (value is byte byteValue) - return NumericLiteralExpression(byteValue); + if (value is sbyte sbyteValue) + return NumericLiteralExpression(sbyteValue); - if (value is short shortValue) - return NumericLiteralExpression(shortValue); + if (value is byte byteValue) + return NumericLiteralExpression(byteValue); - if (value is ushort ushortValue) - return NumericLiteralExpression(ushortValue); + if (value is short shortValue) + return NumericLiteralExpression(shortValue); - if (value is int intValue) - return NumericLiteralExpression(intValue); + if (value is ushort ushortValue) + return NumericLiteralExpression(ushortValue); - if (value is uint uintValue) - return NumericLiteralExpression(uintValue); + if (value is int intValue) + return NumericLiteralExpression(intValue); - if (value is long longValue) - return NumericLiteralExpression(longValue); + if (value is uint uintValue) + return NumericLiteralExpression(uintValue); - if (value is ulong ulongValue) - return NumericLiteralExpression(ulongValue); + if (value is long longValue) + return NumericLiteralExpression(longValue); - if (value is decimal decimalValue) - return NumericLiteralExpression(decimalValue); + if (value is ulong ulongValue) + return NumericLiteralExpression(ulongValue); - if (value is float floatValue) - return NumericLiteralExpression(floatValue); + if (value is decimal decimalValue) + return NumericLiteralExpression(decimalValue); - if (value is double doubleValue) - return NumericLiteralExpression(doubleValue); + if (value is float floatValue) + return NumericLiteralExpression(floatValue); - return StringLiteralExpression(value.ToString()); - } - #endregion LiteralExpression + if (value is double doubleValue) + return NumericLiteralExpression(doubleValue); - #region Expression - public static ObjectCreationExpressionSyntax ObjectCreationExpression(TypeSyntax type, ArgumentListSyntax argumentList) - { - return SyntaxFactory.ObjectCreationExpression(type, argumentList, default(InitializerExpressionSyntax)); - } + return StringLiteralExpression(value.ToString()); + } + #endregion LiteralExpression - public static MemberAccessExpressionSyntax SimpleMemberAccessExpression(ExpressionSyntax expression, SimpleNameSyntax name) - { - return MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expression, name); - } + #region Expression + public static ObjectCreationExpressionSyntax ObjectCreationExpression(TypeSyntax type, ArgumentListSyntax argumentList) + { + return SyntaxFactory.ObjectCreationExpression(type, argumentList, default(InitializerExpressionSyntax)); + } - public static MemberAccessExpressionSyntax SimpleMemberAccessExpression(ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) - { - return MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expression, operatorToken, name); - } + public static MemberAccessExpressionSyntax SimpleMemberAccessExpression(ExpressionSyntax expression, SimpleNameSyntax name) + { + return MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expression, name); + } - public static InvocationExpressionSyntax SimpleMemberInvocationExpression(ExpressionSyntax expression, SimpleNameSyntax name) - { - return InvocationExpression(SimpleMemberAccessExpression(expression, name)); - } + public static MemberAccessExpressionSyntax SimpleMemberAccessExpression(ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) + { + return MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expression, operatorToken, name); + } - public static InvocationExpressionSyntax SimpleMemberInvocationExpression(ExpressionSyntax expression, SimpleNameSyntax name, ArgumentSyntax argument) - { - return SimpleMemberInvocationExpression(expression, name, ArgumentList(argument)); - } + public static InvocationExpressionSyntax SimpleMemberInvocationExpression(ExpressionSyntax expression, SimpleNameSyntax name) + { + return InvocationExpression(SimpleMemberAccessExpression(expression, name)); + } - public static InvocationExpressionSyntax SimpleMemberInvocationExpression(ExpressionSyntax expression, SimpleNameSyntax name, ArgumentListSyntax argumentList) - { - return InvocationExpression(SimpleMemberAccessExpression(expression, name), argumentList); - } + public static InvocationExpressionSyntax SimpleMemberInvocationExpression(ExpressionSyntax expression, SimpleNameSyntax name, ArgumentSyntax argument) + { + return SimpleMemberInvocationExpression(expression, name, ArgumentList(argument)); + } - public static InvocationExpressionSyntax NameOfExpression(string identifier) - { - return NameOfExpression(IdentifierName(identifier)); - } + public static InvocationExpressionSyntax SimpleMemberInvocationExpression(ExpressionSyntax expression, SimpleNameSyntax name, ArgumentListSyntax argumentList) + { + return InvocationExpression(SimpleMemberAccessExpression(expression, name), argumentList); + } - public static InvocationExpressionSyntax NameOfExpression(ExpressionSyntax expression) - { - string text = SyntaxFacts.GetText(SyntaxKind.NameOfKeyword); - - SyntaxToken identifier = Identifier( - leading: default(SyntaxTriviaList), - contextualKind: SyntaxKind.NameOfKeyword, - text: text, - valueText: text, - trailing: default(SyntaxTriviaList)); - - return InvocationExpression( - IdentifierName(identifier), - ArgumentList(SyntaxFactory.Argument(expression))); - } + public static InvocationExpressionSyntax NameOfExpression(string identifier) + { + return NameOfExpression(IdentifierName(identifier)); + } - public static InitializerExpressionSyntax ArrayInitializerExpression(SeparatedSyntaxList expressions = default) - { - return InitializerExpression(SyntaxKind.ArrayInitializerExpression, expressions); - } + public static InvocationExpressionSyntax NameOfExpression(ExpressionSyntax expression) + { + string text = SyntaxFacts.GetText(SyntaxKind.NameOfKeyword); + + SyntaxToken identifier = Identifier( + leading: default(SyntaxTriviaList), + contextualKind: SyntaxKind.NameOfKeyword, + text: text, + valueText: text, + trailing: default(SyntaxTriviaList)); + + return InvocationExpression( + IdentifierName(identifier), + ArgumentList(SyntaxFactory.Argument(expression))); + } - public static InitializerExpressionSyntax ArrayInitializerExpression(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) - { - return InitializerExpression(SyntaxKind.ArrayInitializerExpression, openBraceToken, expressions, closeBraceToken); - } + public static InitializerExpressionSyntax ArrayInitializerExpression(SeparatedSyntaxList expressions = default) + { + return InitializerExpression(SyntaxKind.ArrayInitializerExpression, expressions); + } - public static InitializerExpressionSyntax CollectionInitializerExpression(SeparatedSyntaxList expressions = default) - { - return InitializerExpression(SyntaxKind.CollectionInitializerExpression, expressions); - } + public static InitializerExpressionSyntax ArrayInitializerExpression(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + return InitializerExpression(SyntaxKind.ArrayInitializerExpression, openBraceToken, expressions, closeBraceToken); + } - public static InitializerExpressionSyntax CollectionInitializerExpression(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) - { - return InitializerExpression(SyntaxKind.CollectionInitializerExpression, openBraceToken, expressions, closeBraceToken); - } + public static InitializerExpressionSyntax CollectionInitializerExpression(SeparatedSyntaxList expressions = default) + { + return InitializerExpression(SyntaxKind.CollectionInitializerExpression, expressions); + } - public static InitializerExpressionSyntax ComplexElementInitializerExpression(SeparatedSyntaxList expressions = default) - { - return InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, expressions); - } + public static InitializerExpressionSyntax CollectionInitializerExpression(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + return InitializerExpression(SyntaxKind.CollectionInitializerExpression, openBraceToken, expressions, closeBraceToken); + } - public static InitializerExpressionSyntax ComplexElementInitializerExpression(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) - { - return InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, openBraceToken, expressions, closeBraceToken); - } + public static InitializerExpressionSyntax ComplexElementInitializerExpression(SeparatedSyntaxList expressions = default) + { + return InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, expressions); + } - public static InitializerExpressionSyntax ObjectInitializerExpression(SeparatedSyntaxList expressions = default) - { - return InitializerExpression(SyntaxKind.ObjectInitializerExpression, expressions); - } + public static InitializerExpressionSyntax ComplexElementInitializerExpression(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + return InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, openBraceToken, expressions, closeBraceToken); + } - public static InitializerExpressionSyntax ObjectInitializerExpression(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) - { - return InitializerExpression(SyntaxKind.ObjectInitializerExpression, openBraceToken, expressions, closeBraceToken); - } + public static InitializerExpressionSyntax ObjectInitializerExpression(SeparatedSyntaxList expressions = default) + { + return InitializerExpression(SyntaxKind.ObjectInitializerExpression, expressions); + } - public static CheckedExpressionSyntax CheckedExpression(ExpressionSyntax expression) - { - return SyntaxFactory.CheckedExpression(SyntaxKind.CheckedExpression, expression); - } + public static InitializerExpressionSyntax ObjectInitializerExpression(SyntaxToken openBraceToken, SeparatedSyntaxList expressions, SyntaxToken closeBraceToken) + { + return InitializerExpression(SyntaxKind.ObjectInitializerExpression, openBraceToken, expressions, closeBraceToken); + } - public static CheckedExpressionSyntax CheckedExpression(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) - { - return SyntaxFactory.CheckedExpression(SyntaxKind.CheckedExpression, Token(SyntaxKind.CheckedKeyword), openParenToken, expression, closeParenToken); - } + public static CheckedExpressionSyntax CheckedExpression(ExpressionSyntax expression) + { + return SyntaxFactory.CheckedExpression(SyntaxKind.CheckedExpression, expression); + } - public static CheckedExpressionSyntax UncheckedExpression(ExpressionSyntax expression) - { - return SyntaxFactory.CheckedExpression(SyntaxKind.UncheckedExpression, expression); - } + public static CheckedExpressionSyntax CheckedExpression(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + return SyntaxFactory.CheckedExpression(SyntaxKind.CheckedExpression, Token(SyntaxKind.CheckedKeyword), openParenToken, expression, closeParenToken); + } - public static CheckedExpressionSyntax UncheckedExpression(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) - { - return SyntaxFactory.CheckedExpression(SyntaxKind.UncheckedExpression, Token(SyntaxKind.UncheckedKeyword), openParenToken, expression, closeParenToken); - } + public static CheckedExpressionSyntax UncheckedExpression(ExpressionSyntax expression) + { + return SyntaxFactory.CheckedExpression(SyntaxKind.UncheckedExpression, expression); + } - internal static ThrowExpressionSyntax ThrowNewExpression(TypeSyntax exceptionType) - { - return ThrowExpression(ObjectCreationExpression(exceptionType, ArgumentList())); - } - #endregion Expression + public static CheckedExpressionSyntax UncheckedExpression(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) + { + return SyntaxFactory.CheckedExpression(SyntaxKind.UncheckedExpression, Token(SyntaxKind.UncheckedKeyword), openParenToken, expression, closeParenToken); + } - public static IdentifierNameSyntax VarType() - { - return IdentifierName("var"); - } + internal static ThrowExpressionSyntax ThrowNewExpression(TypeSyntax exceptionType) + { + return ThrowExpression(ObjectCreationExpression(exceptionType, ArgumentList())); + } + #endregion Expression - public static GenericNameSyntax GenericName(string identifier, TypeSyntax typeArgument) - { - return GenericName(Identifier(identifier), typeArgument); - } + public static IdentifierNameSyntax VarType() + { + return IdentifierName("var"); + } - public static GenericNameSyntax GenericName(SyntaxToken identifier, TypeSyntax typeArgument) - { - return SyntaxFactory.GenericName(identifier, TypeArgumentList(typeArgument)); - } + public static GenericNameSyntax GenericName(string identifier, TypeSyntax typeArgument) + { + return GenericName(Identifier(identifier), typeArgument); + } - public static VariableDeclaratorSyntax VariableDeclarator(string identifier, EqualsValueClauseSyntax initializer) - { - return VariableDeclarator(Identifier(identifier), initializer); - } + public static GenericNameSyntax GenericName(SyntaxToken identifier, TypeSyntax typeArgument) + { + return SyntaxFactory.GenericName(identifier, TypeArgumentList(typeArgument)); + } - public static VariableDeclaratorSyntax VariableDeclarator(SyntaxToken identifier, EqualsValueClauseSyntax initializer) - { - return SyntaxFactory.VariableDeclarator(identifier, default(BracketedArgumentListSyntax), initializer); - } + public static VariableDeclaratorSyntax VariableDeclarator(string identifier, EqualsValueClauseSyntax initializer) + { + return VariableDeclarator(Identifier(identifier), initializer); + } - public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, string identifier, ExpressionSyntax value = null) - { - return VariableDeclaration(type, Identifier(identifier), value); - } + public static VariableDeclaratorSyntax VariableDeclarator(SyntaxToken identifier, EqualsValueClauseSyntax initializer) + { + return SyntaxFactory.VariableDeclarator(identifier, default(BracketedArgumentListSyntax), initializer); + } - public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, SyntaxToken identifier, ExpressionSyntax value = null) - { - if (value != null) + public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, string identifier, ExpressionSyntax value = null) { - return VariableDeclaration(type, identifier, EqualsValueClause(value)); + return VariableDeclaration(type, Identifier(identifier), value); } - else + + public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, SyntaxToken identifier, ExpressionSyntax value = null) { - return VariableDeclaration(type, SyntaxFactory.VariableDeclarator(identifier)); + if (value is not null) + { + return VariableDeclaration(type, identifier, EqualsValueClause(value)); + } + else + { + return VariableDeclaration(type, SyntaxFactory.VariableDeclarator(identifier)); + } } - } - public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax initializer) - { - return VariableDeclaration( - type, - VariableDeclarator(identifier, initializer)); - } + public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax initializer) + { + return VariableDeclaration( + type, + VariableDeclarator(identifier, initializer)); + } - public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, VariableDeclaratorSyntax variable) - { - return SyntaxFactory.VariableDeclaration(type, SingletonSeparatedList(variable)); - } + public static VariableDeclarationSyntax VariableDeclaration(TypeSyntax type, VariableDeclaratorSyntax variable) + { + return SyntaxFactory.VariableDeclaration(type, SingletonSeparatedList(variable)); + } - public static UsingDirectiveSyntax UsingStaticDirective(NameSyntax name) - { - return UsingDirective( - Token(SyntaxKind.StaticKeyword), - default(NameEqualsSyntax), - name); - } + public static UsingDirectiveSyntax UsingStaticDirective(NameSyntax name) + { + return UsingDirective( + Token(SyntaxKind.StaticKeyword), + default(NameEqualsSyntax), + name); + } - public static UsingDirectiveSyntax UsingStaticDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameSyntax name, SyntaxToken semicolonToken) - { - return UsingDirective( - usingKeyword, - staticKeyword, - default(NameEqualsSyntax), - name, - semicolonToken); - } + public static UsingDirectiveSyntax UsingStaticDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameSyntax name, SyntaxToken semicolonToken) + { + return UsingDirective( + usingKeyword, + staticKeyword, + default(NameEqualsSyntax), + name, + semicolonToken); + } - public static AttributeSyntax Attribute(NameSyntax name, AttributeArgumentSyntax argument) - { - return SyntaxFactory.Attribute( - name, - AttributeArgumentList(argument)); - } + public static AttributeSyntax Attribute(NameSyntax name, AttributeArgumentSyntax argument) + { + return SyntaxFactory.Attribute( + name, + AttributeArgumentList(argument)); + } - public static AttributeArgumentSyntax AttributeArgument(NameEqualsSyntax nameEquals, ExpressionSyntax expression) - { - return SyntaxFactory.AttributeArgument( - nameEquals: nameEquals, - nameColon: default(NameColonSyntax), - expression: expression); - } + public static AttributeArgumentSyntax AttributeArgument(NameEqualsSyntax nameEquals, ExpressionSyntax expression) + { + return SyntaxFactory.AttributeArgument( + nameEquals: nameEquals, + nameColon: default(NameColonSyntax), + expression: expression); + } - public static AttributeArgumentSyntax AttributeArgument(NameColonSyntax nameColon, ExpressionSyntax expression) - { - return SyntaxFactory.AttributeArgument( - nameEquals: default(NameEqualsSyntax), - nameColon: nameColon, - expression: expression); - } + public static AttributeArgumentSyntax AttributeArgument(NameColonSyntax nameColon, ExpressionSyntax expression) + { + return SyntaxFactory.AttributeArgument( + nameEquals: default(NameEqualsSyntax), + nameColon: nameColon, + expression: expression); + } - public static ArgumentSyntax Argument(NameColonSyntax nameColon, ExpressionSyntax expression) - { - return SyntaxFactory.Argument(nameColon, default(SyntaxToken), expression); - } + public static ArgumentSyntax Argument(NameColonSyntax nameColon, ExpressionSyntax expression) + { + return SyntaxFactory.Argument(nameColon, default(SyntaxToken), expression); + } - public static ParameterSyntax Parameter(TypeSyntax type, string identifier, ExpressionSyntax @default = null) - { - return Parameter(type, Identifier(identifier), @default); - } + public static ParameterSyntax Parameter(TypeSyntax type, string identifier, ExpressionSyntax @default = null) + { + return Parameter(type, Identifier(identifier), @default); + } - public static ParameterSyntax Parameter(TypeSyntax type, SyntaxToken identifier, ExpressionSyntax @default = null) - { - if (@default != null) + public static ParameterSyntax Parameter(TypeSyntax type, SyntaxToken identifier, ExpressionSyntax @default = null) { - return Parameter(type, identifier, EqualsValueClause(@default)); + if (@default is not null) + { + return Parameter(type, identifier, EqualsValueClause(@default)); + } + else + { + return SyntaxFactory.Parameter( + default(SyntaxList), + default(SyntaxTokenList), + type, + identifier, + default(EqualsValueClauseSyntax)); + } } - else + + public static ParameterSyntax Parameter(TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax @default) { return SyntaxFactory.Parameter( default(SyntaxList), default(SyntaxTokenList), type, identifier, - default(EqualsValueClauseSyntax)); + @default); } - } - - public static ParameterSyntax Parameter(TypeSyntax type, SyntaxToken identifier, EqualsValueClauseSyntax @default) - { - return SyntaxFactory.Parameter( - default(SyntaxList), - default(SyntaxTokenList), - type, - identifier, - @default); - } - public static TypeParameterConstraintClauseSyntax TypeParameterConstraintClause( - string name, - TypeParameterConstraintSyntax typeParameterConstraint) - { - return TypeParameterConstraintClause(IdentifierName(name), typeParameterConstraint); - } + public static TypeParameterConstraintClauseSyntax TypeParameterConstraintClause( + string name, + TypeParameterConstraintSyntax typeParameterConstraint) + { + return TypeParameterConstraintClause(IdentifierName(name), typeParameterConstraint); + } - public static TypeParameterConstraintClauseSyntax TypeParameterConstraintClause( - IdentifierNameSyntax identifierName, - TypeParameterConstraintSyntax typeParameterConstraint) - { - return SyntaxFactory.TypeParameterConstraintClause(identifierName, SingletonSeparatedList(typeParameterConstraint)); - } + public static TypeParameterConstraintClauseSyntax TypeParameterConstraintClause( + IdentifierNameSyntax identifierName, + TypeParameterConstraintSyntax typeParameterConstraint) + { + return SyntaxFactory.TypeParameterConstraintClause(identifierName, SingletonSeparatedList(typeParameterConstraint)); + } - public static ClassOrStructConstraintSyntax ClassConstraint() - { - return ClassOrStructConstraint(SyntaxKind.ClassConstraint, Token(SyntaxKind.ClassKeyword)); - } + public static ClassOrStructConstraintSyntax ClassConstraint() + { + return ClassOrStructConstraint(SyntaxKind.ClassConstraint, Token(SyntaxKind.ClassKeyword)); + } - public static ClassOrStructConstraintSyntax StructConstraint() - { - return ClassOrStructConstraint(SyntaxKind.StructConstraint, Token(SyntaxKind.StructKeyword)); - } + public static ClassOrStructConstraintSyntax StructConstraint() + { + return ClassOrStructConstraint(SyntaxKind.StructConstraint, Token(SyntaxKind.StructKeyword)); + } - public static ConstructorInitializerSyntax BaseConstructorInitializer(ArgumentListSyntax argumentList = null) - { - return ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, argumentList); - } + public static ConstructorInitializerSyntax BaseConstructorInitializer(ArgumentListSyntax argumentList = null) + { + return ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, argumentList); + } - public static ConstructorInitializerSyntax BaseConstructorInitializer(SyntaxToken semicolonToken, ArgumentListSyntax argumentList) - { - return ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, semicolonToken, Token(SyntaxKind.BaseKeyword), argumentList); - } + public static ConstructorInitializerSyntax BaseConstructorInitializer(SyntaxToken semicolonToken, ArgumentListSyntax argumentList) + { + return ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, semicolonToken, Token(SyntaxKind.BaseKeyword), argumentList); + } - public static ConstructorInitializerSyntax ThisConstructorInitializer(ArgumentListSyntax argumentList = null) - { - return ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, argumentList); - } + public static ConstructorInitializerSyntax ThisConstructorInitializer(ArgumentListSyntax argumentList = null) + { + return ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, argumentList); + } - public static ConstructorInitializerSyntax ThisConstructorInitializer(SyntaxToken semicolonToken, ArgumentListSyntax argumentList) - { - return ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, semicolonToken, Token(SyntaxKind.ThisKeyword), argumentList); - } + public static ConstructorInitializerSyntax ThisConstructorInitializer(SyntaxToken semicolonToken, ArgumentListSyntax argumentList) + { + return ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, semicolonToken, Token(SyntaxKind.ThisKeyword), argumentList); + } - public static SwitchSectionSyntax SwitchSection(SwitchLabelSyntax switchLabel, StatementSyntax statement) - { - return SwitchSection(switchLabel, SingletonList(statement)); - } + public static SwitchSectionSyntax SwitchSection(SwitchLabelSyntax switchLabel, StatementSyntax statement) + { + return SwitchSection(switchLabel, SingletonList(statement)); + } - public static SwitchSectionSyntax SwitchSection(SwitchLabelSyntax switchLabel, SyntaxList statements) - { - return SyntaxFactory.SwitchSection(SingletonList(switchLabel), statements); - } + public static SwitchSectionSyntax SwitchSection(SwitchLabelSyntax switchLabel, SyntaxList statements) + { + return SyntaxFactory.SwitchSection(SingletonList(switchLabel), statements); + } - public static SwitchSectionSyntax SwitchSection(SyntaxList switchLabels, StatementSyntax statement) - { - return SyntaxFactory.SwitchSection(switchLabels, SingletonList(statement)); - } + public static SwitchSectionSyntax SwitchSection(SyntaxList switchLabels, StatementSyntax statement) + { + return SyntaxFactory.SwitchSection(switchLabels, SingletonList(statement)); + } - public static SwitchSectionSyntax DefaultSwitchSection(StatementSyntax statement) - { - return DefaultSwitchSection(SingletonList(statement)); - } + public static SwitchSectionSyntax DefaultSwitchSection(StatementSyntax statement) + { + return DefaultSwitchSection(SingletonList(statement)); + } - public static SwitchSectionSyntax DefaultSwitchSection(SyntaxList statements) - { - return SwitchSection(DefaultSwitchLabel(), statements); - } + public static SwitchSectionSyntax DefaultSwitchSection(SyntaxList statements) + { + return SwitchSection(DefaultSwitchLabel(), statements); + } - public static CompilationUnitSyntax CompilationUnit(MemberDeclarationSyntax member) - { - return CompilationUnit( - default(SyntaxList), - member); - } + public static CompilationUnitSyntax CompilationUnit(MemberDeclarationSyntax member) + { + return CompilationUnit( + default(SyntaxList), + member); + } - public static CompilationUnitSyntax CompilationUnit(SyntaxList usings, MemberDeclarationSyntax member) - { - return CompilationUnit( - usings, - SingletonList(member)); - } + public static CompilationUnitSyntax CompilationUnit(SyntaxList usings, MemberDeclarationSyntax member) + { + return CompilationUnit( + usings, + SingletonList(member)); + } - public static CompilationUnitSyntax CompilationUnit(SyntaxList usings, SyntaxList members) - { - return SyntaxFactory.CompilationUnit( - default(SyntaxList), - usings, - default(SyntaxList), - members); - } + public static CompilationUnitSyntax CompilationUnit(SyntaxList usings, SyntaxList members) + { + return SyntaxFactory.CompilationUnit( + default(SyntaxList), + usings, + default(SyntaxList), + members); + } - internal static SyntaxList UsingDirectives(string name) - { - return SingletonList(UsingDirective(ParseName(name))); - } + internal static SyntaxList UsingDirectives(string name) + { + return SingletonList(UsingDirective(ParseName(name))); + } - internal static SyntaxList UsingDirectives(params string[] names) - { - return List(names.Select(f => UsingDirective(ParseName(f)))); - } + internal static SyntaxList UsingDirectives(params string[] names) + { + return List(names.Select(f => UsingDirective(ParseName(f)))); + } - public static UnaryPatternSyntax NotPattern(PatternSyntax pattern) - { - return UnaryPattern(Token(SyntaxKind.NotKeyword), pattern); - } + public static UnaryPatternSyntax NotPattern(PatternSyntax pattern) + { + return UnaryPattern(Token(SyntaxKind.NotKeyword), pattern); + } - internal static bool AreEquivalent( - SyntaxNode node1, - SyntaxNode node2, - bool topLevel = false) - { - return SyntaxFactory.AreEquivalent(node1, node2, topLevel: topLevel); - } + internal static bool AreEquivalent( + SyntaxNode node1, + SyntaxNode node2, + bool topLevel = false) + { + return SyntaxFactory.AreEquivalent(node1, node2, topLevel: topLevel); + } - internal static bool AreEquivalent( - SyntaxNode node1, - SyntaxNode node2, - SyntaxNode node3, - bool topLevel = false) - { - return AreEquivalent(node1, node2, topLevel: topLevel) - && AreEquivalent(node1, node3, topLevel: topLevel); + internal static bool AreEquivalent( + SyntaxNode node1, + SyntaxNode node2, + SyntaxNode node3, + bool topLevel = false) + { + return AreEquivalent(node1, node2, topLevel: topLevel) + && AreEquivalent(node1, node3, topLevel: topLevel); + } } } diff --git a/src/CSharp/CSharp/CSharpOverriddenSymbolInfo.cs b/src/CSharp/CSharp/CSharpOverriddenSymbolInfo.cs index 216127c03c..5220a621e9 100644 --- a/src/CSharp/CSharp/CSharpOverriddenSymbolInfo.cs +++ b/src/CSharp/CSharp/CSharpOverriddenSymbolInfo.cs @@ -6,158 +6,159 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal static class CSharpOverriddenSymbolInfo +namespace Roslynator.CSharp { - private static OverriddenSymbolInfo Default { get; } = new(); - - public static bool CanCreate(SyntaxNode node) + internal static class CSharpOverriddenSymbolInfo { - switch (node?.Kind()) + private static OverriddenSymbolInfo Default { get; } = new(); + + public static bool CanCreate(SyntaxNode node) { - case SyntaxKind.MethodDeclaration: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.IndexerDeclaration: - case SyntaxKind.EventDeclaration: - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - { - return true; - } - case SyntaxKind.VariableDeclarator: - { - return node.IsParentKind(SyntaxKind.VariableDeclaration) - && node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); - } + switch (node?.Kind()) + { + case SyntaxKind.MethodDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.IndexerDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + { + return true; + } + case SyntaxKind.VariableDeclarator: + { + return node.IsParentKind(SyntaxKind.VariableDeclaration) + && node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); + } + } + + return false; } - return false; - } - - internal static OverriddenSymbolInfo Create( - SyntaxNode node, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (node == null) - return Default; - - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); - - switch (node) + internal static OverriddenSymbolInfo Create( + SyntaxNode node, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) { - case MethodDeclarationSyntax methodDeclaration: - return CreateImpl(methodDeclaration, semanticModel, cancellationToken); - case PropertyDeclarationSyntax propertyDeclaration: - return CreateImpl(propertyDeclaration, semanticModel, cancellationToken); - case IndexerDeclarationSyntax indexerDeclaration: - return CreateImpl(indexerDeclaration, semanticModel, cancellationToken); - case EventDeclarationSyntax eventDeclaration: - return CreateImpl(eventDeclaration, semanticModel, cancellationToken); - case VariableDeclaratorSyntax variableDeclarator: - return CreateImpl(variableDeclarator, semanticModel, cancellationToken); - case AccessorDeclarationSyntax accessorDeclaration: - return CreateImpl(accessorDeclaration, semanticModel, cancellationToken); - default: + if (node is null) return Default; + + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); + + switch (node) + { + case MethodDeclarationSyntax methodDeclaration: + return CreateImpl(methodDeclaration, semanticModel, cancellationToken); + case PropertyDeclarationSyntax propertyDeclaration: + return CreateImpl(propertyDeclaration, semanticModel, cancellationToken); + case IndexerDeclarationSyntax indexerDeclaration: + return CreateImpl(indexerDeclaration, semanticModel, cancellationToken); + case EventDeclarationSyntax eventDeclaration: + return CreateImpl(eventDeclaration, semanticModel, cancellationToken); + case VariableDeclaratorSyntax variableDeclarator: + return CreateImpl(variableDeclarator, semanticModel, cancellationToken); + case AccessorDeclarationSyntax accessorDeclaration: + return CreateImpl(accessorDeclaration, semanticModel, cancellationToken); + default: + return Default; + } } - } - private static OverriddenSymbolInfo CreateImpl( - MethodDeclarationSyntax methodDeclaration, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); + private static OverriddenSymbolInfo CreateImpl( + MethodDeclarationSyntax methodDeclaration, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); - if (methodSymbol == null) - return Default; + if (methodSymbol is null) + return Default; - IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; + IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; - if (overriddenMethod == null) - return Default; + if (overriddenMethod is null) + return Default; - return new OverriddenSymbolInfo(methodSymbol, overriddenMethod); - } + return new OverriddenSymbolInfo(methodSymbol, overriddenMethod); + } - private static OverriddenSymbolInfo CreateImpl( - BasePropertyDeclarationSyntax basePropertyDeclaration, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - var propertySymbol = (IPropertySymbol)semanticModel.GetDeclaredSymbol(basePropertyDeclaration, cancellationToken); + private static OverriddenSymbolInfo CreateImpl( + BasePropertyDeclarationSyntax basePropertyDeclaration, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + var propertySymbol = (IPropertySymbol)semanticModel.GetDeclaredSymbol(basePropertyDeclaration, cancellationToken); - if (propertySymbol == null) - return Default; + if (propertySymbol is null) + return Default; - IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; + IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty == null) - return Default; + if (overriddenProperty is null) + return Default; - return new OverriddenSymbolInfo(propertySymbol, overriddenProperty); - } + return new OverriddenSymbolInfo(propertySymbol, overriddenProperty); + } - private static OverriddenSymbolInfo CreateImpl( - EventDeclarationSyntax eventDeclaration, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - IEventSymbol eventSymbol = semanticModel.GetDeclaredSymbol(eventDeclaration, cancellationToken); + private static OverriddenSymbolInfo CreateImpl( + EventDeclarationSyntax eventDeclaration, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + IEventSymbol eventSymbol = semanticModel.GetDeclaredSymbol(eventDeclaration, cancellationToken); - if (eventSymbol == null) - return Default; + if (eventSymbol is null) + return Default; - IEventSymbol overriddenEvent = eventSymbol.OverriddenEvent; + IEventSymbol overriddenEvent = eventSymbol.OverriddenEvent; - if (overriddenEvent == null) - return Default; + if (overriddenEvent is null) + return Default; - return new OverriddenSymbolInfo(eventSymbol, overriddenEvent); - } + return new OverriddenSymbolInfo(eventSymbol, overriddenEvent); + } - private static OverriddenSymbolInfo CreateImpl( - VariableDeclaratorSyntax variableDeclarator, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - if (!variableDeclarator.IsParentKind(SyntaxKind.VariableDeclaration)) - return Default; + private static OverriddenSymbolInfo CreateImpl( + VariableDeclaratorSyntax variableDeclarator, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + if (!variableDeclarator.IsParentKind(SyntaxKind.VariableDeclaration)) + return Default; - if (!variableDeclarator.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration)) - return Default; + if (!variableDeclarator.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration)) + return Default; - if (semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken) is not IEventSymbol eventSymbol) - return Default; + if (semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken) is not IEventSymbol eventSymbol) + return Default; - IEventSymbol overriddenEvent = eventSymbol.OverriddenEvent; + IEventSymbol overriddenEvent = eventSymbol.OverriddenEvent; - if (overriddenEvent == null) - return Default; + if (overriddenEvent is null) + return Default; - return new OverriddenSymbolInfo(eventSymbol, overriddenEvent); - } + return new OverriddenSymbolInfo(eventSymbol, overriddenEvent); + } - private static OverriddenSymbolInfo CreateImpl( - AccessorDeclarationSyntax accessorDeclaration, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(accessorDeclaration, cancellationToken); + private static OverriddenSymbolInfo CreateImpl( + AccessorDeclarationSyntax accessorDeclaration, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(accessorDeclaration, cancellationToken); - if (methodSymbol == null) - return Default; + if (methodSymbol is null) + return Default; - IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; + IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; - if (overriddenMethod == null) - return Default; + if (overriddenMethod is null) + return Default; - return new OverriddenSymbolInfo(methodSymbol, overriddenMethod); + return new OverriddenSymbolInfo(methodSymbol, overriddenMethod); + } } } diff --git a/src/CSharp/CSharp/CSharpTypeAnalysis.cs b/src/CSharp/CSharp/CSharpTypeAnalysis.cs index f98c772dc8..f4d6060679 100644 --- a/src/CSharp/CSharp/CSharpTypeAnalysis.cs +++ b/src/CSharp/CSharp/CSharpTypeAnalysis.cs @@ -7,870 +7,871 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal static class CSharpTypeAnalysis +namespace Roslynator.CSharp { - public static TypeAnalysis AnalyzeType( - VariableDeclarationSyntax variableDeclaration, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) + internal static class CSharpTypeAnalysis { - TypeSyntax type = variableDeclaration.Type; - - Debug.Assert(type != null); + public static TypeAnalysis AnalyzeType( + VariableDeclarationSyntax variableDeclaration, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + TypeSyntax type = variableDeclaration.Type; - if (type == null) - return default; + Debug.Assert(type is not null); - SeparatedSyntaxList variables = variableDeclaration.Variables; + if (type is null) + return default; - Debug.Assert(variables.Any()); + SeparatedSyntaxList variables = variableDeclaration.Variables; - if (!variables.Any()) - return default; + Debug.Assert(variables.Any()); - if (variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration)) - return default; + if (!variables.Any()) + return default; - ExpressionSyntax expression = variables[0].Initializer?.Value?.WalkDownParentheses(); + if (variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration)) + return default; - if (expression == null) - return default; + ExpressionSyntax expression = variables[0].Initializer?.Value?.WalkDownParentheses(); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); + if (expression is null) + return default; - if (typeSymbol == null) - return default; + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); - SymbolKind kind = typeSymbol.Kind; + if (typeSymbol is null) + return default; - if (kind == SymbolKind.ErrorType) - return default; + SymbolKind kind = typeSymbol.Kind; - if (kind == SymbolKind.DynamicType) - return new TypeAnalysis(typeSymbol, TypeAnalysisFlags.Dynamic); + if (kind == SymbolKind.ErrorType) + return default; - var flags = TypeAnalysisFlags.None; + if (kind == SymbolKind.DynamicType) + return new TypeAnalysis(typeSymbol, TypeAnalysisFlags.Dynamic); - if (type.IsVar) - { - flags |= TypeAnalysisFlags.Implicit; - - if (typeSymbol.SupportsExplicitDeclaration()) - flags |= TypeAnalysisFlags.SupportsExplicit; - } - else - { - flags |= TypeAnalysisFlags.Explicit; + var flags = TypeAnalysisFlags.None; - if (variables.Count == 1 - && (variableDeclaration.Parent as LocalDeclarationStatementSyntax)?.IsConst != true - && !expression.IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression)) + if (type.IsVar) { - flags |= TypeAnalysisFlags.SupportsImplicit; + flags |= TypeAnalysisFlags.Implicit; + + if (typeSymbol.SupportsExplicitDeclaration()) + flags |= TypeAnalysisFlags.SupportsExplicit; } - } + else + { + flags |= TypeAnalysisFlags.Explicit; - switch (expression.Kind()) - { - case SyntaxKind.ObjectCreationExpression: - case SyntaxKind.ArrayCreationExpression: - case SyntaxKind.CastExpression: - case SyntaxKind.AsExpression: - case SyntaxKind.ThisExpression: - case SyntaxKind.DefaultExpression: + if (variables.Count == 1 + && (variableDeclaration.Parent as LocalDeclarationStatementSyntax)?.IsConst != true + && !expression.IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression)) { - flags |= TypeAnalysisFlags.TypeObvious; - break; + flags |= TypeAnalysisFlags.SupportsImplicit; } - case SyntaxKind.SimpleMemberAccessExpression: - { - ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); + } - if (symbol?.Kind == SymbolKind.Field - && symbol.ContainingType?.TypeKind == TypeKind.Enum) + switch (expression.Kind()) + { + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.ArrayCreationExpression: + case SyntaxKind.CastExpression: + case SyntaxKind.AsExpression: + case SyntaxKind.ThisExpression: + case SyntaxKind.DefaultExpression: { flags |= TypeAnalysisFlags.TypeObvious; + break; } + case SyntaxKind.SimpleMemberAccessExpression: + { + ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); - break; - } + if (symbol?.Kind == SymbolKind.Field + && symbol.ContainingType?.TypeKind == TypeKind.Enum) + { + flags |= TypeAnalysisFlags.TypeObvious; + } + + break; + } + } + + return new TypeAnalysis(typeSymbol, flags); } - return new TypeAnalysis(typeSymbol, flags); - } + public static bool IsImplicitThatCanBeExplicit( + VariableDeclarationSyntax variableDeclaration, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + return IsImplicitThatCanBeExplicit(variableDeclaration, semanticModel, TypeAppearance.None, cancellationToken); + } - public static bool IsImplicitThatCanBeExplicit( - VariableDeclarationSyntax variableDeclaration, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - return IsImplicitThatCanBeExplicit(variableDeclaration, semanticModel, TypeAppearance.None, cancellationToken); - } + public static bool IsImplicitThatCanBeExplicit( + VariableDeclarationSyntax variableDeclaration, + SemanticModel semanticModel, + TypeAppearance typeAppearance, + CancellationToken cancellationToken = default) + { + TypeSyntax type = variableDeclaration.Type; - public static bool IsImplicitThatCanBeExplicit( - VariableDeclarationSyntax variableDeclaration, - SemanticModel semanticModel, - TypeAppearance typeAppearance, - CancellationToken cancellationToken = default) - { - TypeSyntax type = variableDeclaration.Type; + Debug.Assert(type is not null); - Debug.Assert(type != null); + if (type is null) + return false; - if (type == null) - return false; + if (!type.IsVar) + return false; - if (!type.IsVar) - return false; + if (variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration)) + return false; - if (variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration)) - return false; + Debug.Assert(variableDeclaration.Variables.Any()); - Debug.Assert(variableDeclaration.Variables.Any()); + ExpressionSyntax expression = variableDeclaration + .Variables + .FirstOrDefault()? + .Initializer? + .Value? + .WalkDownParentheses(); - ExpressionSyntax expression = variableDeclaration - .Variables - .FirstOrDefault()? - .Initializer? - .Value? - .WalkDownParentheses(); + if (expression is null) + return false; - if (expression == null) - return false; + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); + if (typeSymbol is null) + return false; - if (typeSymbol == null) - return false; + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; + if (!typeSymbol.SupportsExplicitDeclaration()) + return false; - if (!typeSymbol.SupportsExplicitDeclaration()) - return false; + switch (typeAppearance) + { + case TypeAppearance.Obvious: + return IsTypeObvious(expression, typeSymbol, includeNullability: false, semanticModel, cancellationToken); + case TypeAppearance.NotObvious: + return !IsTypeObvious(expression, typeSymbol, includeNullability: false, semanticModel, cancellationToken); + } + + Debug.Assert(typeAppearance == TypeAppearance.None, typeAppearance.ToString()); + + return true; + } - switch (typeAppearance) + public static bool IsExplicitThatCanBeImplicit( + VariableDeclarationSyntax variableDeclaration, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) { - case TypeAppearance.Obvious: - return IsTypeObvious(expression, typeSymbol, includeNullability: false, semanticModel, cancellationToken); - case TypeAppearance.NotObvious: - return !IsTypeObvious(expression, typeSymbol, includeNullability: false, semanticModel, cancellationToken); + return IsExplicitThatCanBeImplicit(variableDeclaration, semanticModel, TypeAppearance.None, cancellationToken); } - Debug.Assert(typeAppearance == TypeAppearance.None, typeAppearance.ToString()); + public static bool IsExplicitThatCanBeImplicit( + VariableDeclarationSyntax variableDeclaration, + SemanticModel semanticModel, + TypeAppearance typeAppearance, + CancellationToken cancellationToken = default) + { + TypeSyntax type = variableDeclaration.Type; - return true; - } + Debug.Assert(type is not null); - public static bool IsExplicitThatCanBeImplicit( - VariableDeclarationSyntax variableDeclaration, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - return IsExplicitThatCanBeImplicit(variableDeclaration, semanticModel, TypeAppearance.None, cancellationToken); - } + if (type is null) + return false; - public static bool IsExplicitThatCanBeImplicit( - VariableDeclarationSyntax variableDeclaration, - SemanticModel semanticModel, - TypeAppearance typeAppearance, - CancellationToken cancellationToken = default) - { - TypeSyntax type = variableDeclaration.Type; + if (type.IsVar) + return false; - Debug.Assert(type != null); + switch (variableDeclaration.Parent.Kind()) + { + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + { + return false; + } + case SyntaxKind.LocalDeclarationStatement: + { + if (((LocalDeclarationStatementSyntax)variableDeclaration.Parent).IsConst) + return false; - if (type == null) - return false; + break; + } + } - if (type.IsVar) - return false; + Debug.Assert(variableDeclaration.Variables.Any()); - switch (variableDeclaration.Parent.Kind()) - { - case SyntaxKind.FieldDeclaration: - case SyntaxKind.EventFieldDeclaration: - { - return false; - } - case SyntaxKind.LocalDeclarationStatement: - { - if (((LocalDeclarationStatementSyntax)variableDeclaration.Parent).IsConst) - return false; + ExpressionSyntax expression = variableDeclaration + .Variables + .SingleOrDefault(shouldThrow: false)? + .Initializer? + .Value? + .WalkDownParentheses(); - break; - } - } + if (expression is null) + return false; - Debug.Assert(variableDeclaration.Variables.Any()); + if (expression.IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression)) + return false; - ExpressionSyntax expression = variableDeclaration - .Variables - .SingleOrDefault(shouldThrow: false)? - .Initializer? - .Value? - .WalkDownParentheses(); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); - if (expression == null) - return false; + if (typeSymbol is null) + return false; - if (expression.IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression)) - return false; + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); + if (!SymbolEqualityComparer.Default.Equals(typeSymbol, semanticModel.GetTypeSymbol(expression, cancellationToken))) + return false; - if (typeSymbol == null) - return false; + switch (typeAppearance) + { + case TypeAppearance.Obvious: + return IsTypeObvious(expression, typeSymbol, includeNullability: true, semanticModel, cancellationToken); + case TypeAppearance.NotObvious: + return !IsTypeObvious(expression, typeSymbol, includeNullability: true, semanticModel, cancellationToken); + } - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; + Debug.Assert(typeAppearance == TypeAppearance.None, typeAppearance.ToString()); - if (!SymbolEqualityComparer.Default.Equals(typeSymbol, semanticModel.GetTypeSymbol(expression, cancellationToken))) - return false; + return true; + } - switch (typeAppearance) + public static bool IsTypeObvious(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { - case TypeAppearance.Obvious: - return IsTypeObvious(expression, typeSymbol, includeNullability: true, semanticModel, cancellationToken); - case TypeAppearance.NotObvious: - return !IsTypeObvious(expression, typeSymbol, includeNullability: true, semanticModel, cancellationToken); + return IsTypeObvious(expression, typeSymbol: null, includeNullability: false, semanticModel, cancellationToken); } - Debug.Assert(typeAppearance == TypeAppearance.None, typeAppearance.ToString()); - - return true; - } + public static bool IsTypeObvious(ExpressionSyntax expression, ITypeSymbol typeSymbol, bool includeNullability, SemanticModel semanticModel, CancellationToken cancellationToken) + { + switch (expression.Kind()) + { + case SyntaxKind.StringLiteralExpression: + case SyntaxKind.CharacterLiteralExpression: + case SyntaxKind.TrueLiteralExpression: + case SyntaxKind.FalseLiteralExpression: + case SyntaxKind.ThisExpression: + { + return true; + } + case SyntaxKind.ObjectCreationExpression: + case SyntaxKind.ArrayCreationExpression: + case SyntaxKind.CastExpression: + case SyntaxKind.AsExpression: + case SyntaxKind.DefaultExpression: + { + return typeSymbol is null + || GetEqualityComparer(includeNullability).Equals( + typeSymbol, + semanticModel.GetTypeSymbol(expression, cancellationToken)); + } + case SyntaxKind.ImplicitArrayCreationExpression: + { + var implicitArrayCreation = (ImplicitArrayCreationExpressionSyntax)expression; - public static bool IsTypeObvious(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) - { - return IsTypeObvious(expression, typeSymbol: null, includeNullability: false, semanticModel, cancellationToken); - } + SeparatedSyntaxList expressions = implicitArrayCreation.Initializer?.Expressions ?? default; - public static bool IsTypeObvious(ExpressionSyntax expression, ITypeSymbol typeSymbol, bool includeNullability, SemanticModel semanticModel, CancellationToken cancellationToken) - { - switch (expression.Kind()) - { - case SyntaxKind.StringLiteralExpression: - case SyntaxKind.CharacterLiteralExpression: - case SyntaxKind.TrueLiteralExpression: - case SyntaxKind.FalseLiteralExpression: - case SyntaxKind.ThisExpression: - { - return true; - } - case SyntaxKind.ObjectCreationExpression: - case SyntaxKind.ArrayCreationExpression: - case SyntaxKind.CastExpression: - case SyntaxKind.AsExpression: - case SyntaxKind.DefaultExpression: - { - return typeSymbol == null - || GetEqualityComparer(includeNullability).Equals( - typeSymbol, - semanticModel.GetTypeSymbol(expression, cancellationToken)); - } - case SyntaxKind.ImplicitArrayCreationExpression: - { - 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 != 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) + case SyntaxKind.SimpleMemberAccessExpression: { - if (!IsTypeObvious(expression2, typeSymbol, includeNullability, semanticModel, cancellationToken)) - return false; - } + ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); - return true; - } - case SyntaxKind.SimpleMemberAccessExpression: - { - ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); - - return symbol?.Kind == SymbolKind.Field - && symbol.ContainingType?.TypeKind == TypeKind.Enum; - } - case SyntaxKind.InvocationExpression: - { - if (typeSymbol != null) + return symbol?.Kind == SymbolKind.Field + && symbol.ContainingType?.TypeKind == TypeKind.Enum; + } + case SyntaxKind.InvocationExpression: { - var invocationExpression = (InvocationExpressionSyntax)expression; - if (invocationExpression.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) + if (typeSymbol is not null) { - 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 invocationExpression = (InvocationExpressionSyntax)expression; + if (invocationExpression.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { - var simpleMemberAccess = (MemberAccessExpressionSyntax)invocationExpression.Expression; + ISymbol symbol = semanticModel.GetSymbol(expression, cancellationToken); - ISymbol symbol2 = semanticModel.GetSymbol(simpleMemberAccess.Expression, cancellationToken); - - if (SymbolEqualityComparer.Default.Equals(symbol2, typeSymbol) - && semanticModel.GetAliasInfo(simpleMemberAccess.Expression, cancellationToken) == null) + if (symbol?.IsStatic == true + && string.Equals(symbol.Name, "Parse", StringComparison.Ordinal) + && GetEqualityComparer(includeNullability).Equals( + ((IMethodSymbol)symbol).ReturnType, + typeSymbol)) { - return true; + var simpleMemberAccess = (MemberAccessExpressionSyntax)invocationExpression.Expression; + + ISymbol symbol2 = semanticModel.GetSymbol(simpleMemberAccess.Expression, cancellationToken); + + if (SymbolEqualityComparer.Default.Equals(symbol2, typeSymbol) + && semanticModel.GetAliasInfo(simpleMemberAccess.Expression, cancellationToken) is null) + { + return true; + } } } } + + break; } + } - break; - } + return false; } - return false; - } + private static SymbolEqualityComparer GetEqualityComparer(bool includeNullability) + { + return (includeNullability) ? SymbolEqualityComparer.IncludeNullability : SymbolEqualityComparer.Default; + } - private static SymbolEqualityComparer GetEqualityComparer(bool includeNullability) - { - return (includeNullability) ? SymbolEqualityComparer.IncludeNullability : SymbolEqualityComparer.Default; - } + public static TypeAnalysis AnalyzeType( + DeclarationExpressionSyntax declarationExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + TypeSyntax type = declarationExpression.Type; - public static TypeAnalysis AnalyzeType( - DeclarationExpressionSyntax declarationExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - TypeSyntax type = declarationExpression.Type; + if (type is null) + return default; - if (type == null) - return default; + if (declarationExpression.Designation is not SingleVariableDesignationSyntax singleVariableDesignation) + return default; - if (declarationExpression.Designation is not SingleVariableDesignationSyntax singleVariableDesignation) - return default; + if (semanticModel.GetDeclaredSymbol(singleVariableDesignation, cancellationToken) is not ILocalSymbol localSymbol) + return default; - if (semanticModel.GetDeclaredSymbol(singleVariableDesignation, cancellationToken) is not ILocalSymbol localSymbol) - return default; + ITypeSymbol typeSymbol = localSymbol.Type; - ITypeSymbol typeSymbol = localSymbol.Type; + Debug.Assert(typeSymbol is not null); - Debug.Assert(typeSymbol != null); + if (typeSymbol is null) + return default; - if (typeSymbol == null) - return default; + SymbolKind kind = typeSymbol.Kind; - SymbolKind kind = typeSymbol.Kind; + if (kind == SymbolKind.ErrorType) + return default; - if (kind == SymbolKind.ErrorType) - return default; + if (kind == SymbolKind.DynamicType) + return new TypeAnalysis(typeSymbol, TypeAnalysisFlags.Dynamic); - if (kind == SymbolKind.DynamicType) - return new TypeAnalysis(typeSymbol, TypeAnalysisFlags.Dynamic); + var flags = TypeAnalysisFlags.None; - var flags = TypeAnalysisFlags.None; + if (type.IsVar) + { + flags |= TypeAnalysisFlags.Implicit; - if (type.IsVar) - { - flags |= TypeAnalysisFlags.Implicit; + if (typeSymbol.SupportsExplicitDeclaration()) + flags |= TypeAnalysisFlags.SupportsExplicit; + } + else + { + flags |= TypeAnalysisFlags.Explicit; + flags |= TypeAnalysisFlags.SupportsImplicit; + } - if (typeSymbol.SupportsExplicitDeclaration()) - flags |= TypeAnalysisFlags.SupportsExplicit; + return new TypeAnalysis(typeSymbol, flags); } - else + + public static bool IsImplicitThatCanBeExplicit( + DeclarationExpressionSyntax declarationExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) { - flags |= TypeAnalysisFlags.Explicit; - flags |= TypeAnalysisFlags.SupportsImplicit; - } + TypeSyntax type = declarationExpression.Type; - return new TypeAnalysis(typeSymbol, flags); - } + Debug.Assert(type is not null); - public static bool IsImplicitThatCanBeExplicit( - DeclarationExpressionSyntax declarationExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - TypeSyntax type = declarationExpression.Type; + if (type is null) + return false; - Debug.Assert(type != null); + if (!type.IsVar) + return false; - if (type == null) - return false; + switch (declarationExpression.Designation) + { + case SingleVariableDesignationSyntax singleVariableDesignation: + { + return IsLocalThatSupportsExplicitDeclaration(singleVariableDesignation); + } + case DiscardDesignationSyntax discardDesignation: + { + return IsLocalThatSupportsExplicitDeclaration(discardDesignation); + } + case ParenthesizedVariableDesignationSyntax parenthesizedVariableDesignation: + { + foreach (VariableDesignationSyntax variableDesignation in parenthesizedVariableDesignation.Variables) + { + if (variableDesignation is not SingleVariableDesignationSyntax singleVariableDesignation2) + return false; - if (!type.IsVar) - return false; + if (!IsLocalThatSupportsExplicitDeclaration(singleVariableDesignation2)) + return false; + } - switch (declarationExpression.Designation) - { - case SingleVariableDesignationSyntax singleVariableDesignation: - { - return IsLocalThatSupportsExplicitDeclaration(singleVariableDesignation); - } - case DiscardDesignationSyntax discardDesignation: - { - return IsLocalThatSupportsExplicitDeclaration(discardDesignation); - } - case ParenthesizedVariableDesignationSyntax parenthesizedVariableDesignation: - { - foreach (VariableDesignationSyntax variableDesignation in parenthesizedVariableDesignation.Variables) + return true; + } + default: { - if (variableDesignation is not SingleVariableDesignationSyntax singleVariableDesignation2) - return false; - - if (!IsLocalThatSupportsExplicitDeclaration(singleVariableDesignation2)) - return false; + SyntaxDebug.Fail(declarationExpression.Designation); + return false; } + } - return true; - } - default: - { - SyntaxDebug.Fail(declarationExpression.Designation); + bool IsLocalThatSupportsExplicitDeclaration(VariableDesignationSyntax variableDesignation) + { + if (semanticModel.GetDeclaredSymbol(variableDesignation, cancellationToken) is not ILocalSymbol localSymbol) return false; - } - } - bool IsLocalThatSupportsExplicitDeclaration(VariableDesignationSyntax variableDesignation) - { - if (semanticModel.GetDeclaredSymbol(variableDesignation, cancellationToken) is not ILocalSymbol localSymbol) - return false; - - ITypeSymbol typeSymbol = localSymbol.Type; + ITypeSymbol typeSymbol = localSymbol.Type; - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; - return typeSymbol.SupportsExplicitDeclaration(); + return typeSymbol.SupportsExplicitDeclaration(); + } } - } - public static bool IsExplicitThatCanBeImplicit( - DeclarationExpressionSyntax declarationExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - TypeSyntax type = declarationExpression.Type; + public static bool IsExplicitThatCanBeImplicit( + DeclarationExpressionSyntax declarationExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + TypeSyntax type = declarationExpression.Type; - if (type == null) - return false; + if (type is null) + return false; - if (type.IsVar) - return false; + if (type.IsVar) + return false; - if (declarationExpression.Designation is not SingleVariableDesignationSyntax singleVariableDesignation) - return false; + if (declarationExpression.Designation is not SingleVariableDesignationSyntax singleVariableDesignation) + return false; - if (semanticModel.GetDeclaredSymbol(singleVariableDesignation, cancellationToken) is not ILocalSymbol localSymbol) - return false; + if (semanticModel.GetDeclaredSymbol(singleVariableDesignation, cancellationToken) is not ILocalSymbol localSymbol) + return false; - ITypeSymbol typeSymbol = localSymbol.Type; + ITypeSymbol typeSymbol = localSymbol.Type; - Debug.Assert(typeSymbol != null); + Debug.Assert(typeSymbol is not null); - if (typeSymbol == null) - return false; + if (typeSymbol is null) + return false; - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; - return true; - } + return true; + } - public static bool IsExplicitThatCanBeImplicit( - TupleExpressionSyntax tupleExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - return IsExplicitThatCanBeImplicit(tupleExpression, semanticModel, TypeAppearance.None, cancellationToken); - } + public static bool IsExplicitThatCanBeImplicit( + TupleExpressionSyntax tupleExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + return IsExplicitThatCanBeImplicit(tupleExpression, semanticModel, TypeAppearance.None, cancellationToken); + } - public static bool IsExplicitThatCanBeImplicit( - TupleExpressionSyntax tupleExpression, - SemanticModel semanticModel, - TypeAppearance typeAppearance, - CancellationToken cancellationToken = default) - { - switch (tupleExpression.Parent.Kind()) + public static bool IsExplicitThatCanBeImplicit( + TupleExpressionSyntax tupleExpression, + SemanticModel semanticModel, + TypeAppearance typeAppearance, + CancellationToken cancellationToken = default) { - case SyntaxKind.SimpleAssignmentExpression: - { - var assignment = (AssignmentExpressionSyntax)tupleExpression.Parent; + switch (tupleExpression.Parent.Kind()) + { + case SyntaxKind.SimpleAssignmentExpression: + { + var assignment = (AssignmentExpressionSyntax)tupleExpression.Parent; - return IsExplicitThatCanBeImplicit(tupleExpression, assignment, typeAppearance, semanticModel, cancellationToken); - } - case SyntaxKind.ForEachVariableStatement: - { - var forEachStatement = (ForEachVariableStatementSyntax)tupleExpression.Parent; + return IsExplicitThatCanBeImplicit(tupleExpression, assignment, typeAppearance, semanticModel, cancellationToken); + } + case SyntaxKind.ForEachVariableStatement: + { + var forEachStatement = (ForEachVariableStatementSyntax)tupleExpression.Parent; - return IsExplicitThatCanBeImplicit(tupleExpression, forEachStatement, semanticModel); - } + return IsExplicitThatCanBeImplicit(tupleExpression, forEachStatement, semanticModel); + } #if DEBUG - case SyntaxKind.Argument: - case SyntaxKind.ArrayInitializerExpression: - case SyntaxKind.ArrowExpressionClause: - case SyntaxKind.CollectionInitializerExpression: - case SyntaxKind.EqualsValueClause: - case SyntaxKind.ParenthesizedLambdaExpression: - case SyntaxKind.ReturnStatement: - case SyntaxKind.SimpleLambdaExpression: - case SyntaxKind.SimpleMemberAccessExpression: - case SyntaxKind.SwitchExpression: - case SyntaxKind.SwitchExpressionArm: - 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; - } + case SyntaxKind.Argument: + case SyntaxKind.ArrayInitializerExpression: + case SyntaxKind.ArrowExpressionClause: + case SyntaxKind.CollectionInitializerExpression: + case SyntaxKind.EqualsValueClause: + case SyntaxKind.ParenthesizedLambdaExpression: + case SyntaxKind.ReturnStatement: + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.SwitchExpression: + case SyntaxKind.SwitchExpressionArm: + 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; + } #endif - default: - { - SyntaxDebug.Fail(tupleExpression.Parent); - return false; - } + default: + { + SyntaxDebug.Fail(tupleExpression.Parent); + return false; + } + } } - } - private static bool IsExplicitThatCanBeImplicit( - TupleExpressionSyntax tupleExpression, - AssignmentExpressionSyntax assignment, - TypeAppearance typeAppearance, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - ExpressionSyntax expression = assignment.Right.WalkDownParentheses(); + private static bool IsExplicitThatCanBeImplicit( + TupleExpressionSyntax tupleExpression, + AssignmentExpressionSyntax assignment, + TypeAppearance typeAppearance, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + ExpressionSyntax expression = assignment.Right.WalkDownParentheses(); - if (expression?.IsMissing != false) - return false; + if (expression?.IsMissing != false) + return false; - if (expression.IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression)) - return false; + if (expression.IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression)) + return false; - ITypeSymbol tupleTypeSymbol = semanticModel.GetTypeSymbol(tupleExpression, cancellationToken); + ITypeSymbol tupleTypeSymbol = semanticModel.GetTypeSymbol(tupleExpression, cancellationToken); - if (tupleTypeSymbol == null) - return false; + if (tupleTypeSymbol is null) + return false; - ITypeSymbol expressionTypeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); + ITypeSymbol expressionTypeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (tupleTypeSymbol.IsTupleType - && expressionTypeSymbol.IsTupleType) - { - var tupleNamedTypeSymbol = (INamedTypeSymbol)tupleTypeSymbol; - var expressionNamedTypeSymbol = (INamedTypeSymbol)expressionTypeSymbol; + if (tupleTypeSymbol.IsTupleType + && expressionTypeSymbol.IsTupleType) + { + var tupleNamedTypeSymbol = (INamedTypeSymbol)tupleTypeSymbol; + var expressionNamedTypeSymbol = (INamedTypeSymbol)expressionTypeSymbol; - if (!SymbolEqualityComparer.Default.Equals( - tupleNamedTypeSymbol.TupleUnderlyingType ?? tupleNamedTypeSymbol, - expressionNamedTypeSymbol.TupleUnderlyingType ?? expressionNamedTypeSymbol)) + if (!SymbolEqualityComparer.Default.Equals( + tupleNamedTypeSymbol.TupleUnderlyingType ?? tupleNamedTypeSymbol, + expressionNamedTypeSymbol.TupleUnderlyingType ?? expressionNamedTypeSymbol)) + { + return false; + } + } + else if (!SymbolEqualityComparer.Default.Equals(tupleTypeSymbol, expressionTypeSymbol)) { return false; } - } - else if (!SymbolEqualityComparer.Default.Equals(tupleTypeSymbol, expressionTypeSymbol)) - { - return false; - } - - foreach (ArgumentSyntax argument in tupleExpression.Arguments) - { - if (argument.Expression is not DeclarationExpressionSyntax declarationExpression) - return false; - TypeSyntax type = declarationExpression.Type; + foreach (ArgumentSyntax argument in tupleExpression.Arguments) + { + if (argument.Expression is not DeclarationExpressionSyntax declarationExpression) + return false; - if (type == null) - return false; + TypeSyntax type = declarationExpression.Type; - if (declarationExpression.Designation is not SingleVariableDesignationSyntax singleVariableDesignation) - return false; + if (type is null) + return false; - if (semanticModel.GetDeclaredSymbol(singleVariableDesignation, cancellationToken) is not ILocalSymbol localSymbol) - return false; + if (declarationExpression.Designation is not SingleVariableDesignationSyntax singleVariableDesignation) + return false; - ITypeSymbol typeSymbol = localSymbol.Type; + if (semanticModel.GetDeclaredSymbol(singleVariableDesignation, cancellationToken) is not ILocalSymbol localSymbol) + return false; - Debug.Assert(typeSymbol != null); + ITypeSymbol typeSymbol = localSymbol.Type; - if (typeSymbol == null) - return false; + Debug.Assert(typeSymbol is not null); - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; - } + if (typeSymbol is null) + return false; - switch (typeAppearance) - { - case TypeAppearance.Obvious: - return IsTypeObvious(expression, semanticModel, cancellationToken); - case TypeAppearance.NotObvious: - return !IsTypeObvious(expression, semanticModel, cancellationToken); - } + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; + } - Debug.Assert(typeAppearance == TypeAppearance.None, typeAppearance.ToString()); + switch (typeAppearance) + { + 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()); - public static TypeAnalysis AnalyzeType(ForEachStatementSyntax forEachStatement, SemanticModel semanticModel) - { - TypeSyntax type = forEachStatement.Type; + return true; + } - Debug.Assert(type != null); + public static TypeAnalysis AnalyzeType(ForEachStatementSyntax forEachStatement, SemanticModel semanticModel) + { + TypeSyntax type = forEachStatement.Type; - if (type == null) - return default; + Debug.Assert(type is not null); - ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); + if (type is null) + return default; - ITypeSymbol typeSymbol = info.ElementType; + ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); - if (typeSymbol == null) - return default; + ITypeSymbol typeSymbol = info.ElementType; - SymbolKind kind = typeSymbol.Kind; + if (typeSymbol is null) + return default; - if (kind == SymbolKind.ErrorType) - return default; + SymbolKind kind = typeSymbol.Kind; - if (kind == SymbolKind.DynamicType) - return new TypeAnalysis(typeSymbol, TypeAnalysisFlags.Dynamic); + if (kind == SymbolKind.ErrorType) + return default; - var flags = TypeAnalysisFlags.None; + if (kind == SymbolKind.DynamicType) + return new TypeAnalysis(typeSymbol, TypeAnalysisFlags.Dynamic); - if (type.IsVar) - { - flags |= TypeAnalysisFlags.Implicit; + var flags = TypeAnalysisFlags.None; - if (typeSymbol.SupportsExplicitDeclaration()) - flags |= TypeAnalysisFlags.SupportsExplicit; - } - else - { - flags |= TypeAnalysisFlags.Explicit; + if (type.IsVar) + { + flags |= TypeAnalysisFlags.Implicit; - if (info.ElementConversion.IsIdentity) - flags |= TypeAnalysisFlags.SupportsImplicit; - } + if (typeSymbol.SupportsExplicitDeclaration()) + flags |= TypeAnalysisFlags.SupportsExplicit; + } + else + { + flags |= TypeAnalysisFlags.Explicit; - return new TypeAnalysis(typeSymbol, flags); - } + if (info.ElementConversion.IsIdentity) + flags |= TypeAnalysisFlags.SupportsImplicit; + } - public static TypeAnalysis AnalyzeType(ForEachVariableStatementSyntax forEachStatement, SemanticModel semanticModel) - { - var flags = TypeAnalysisFlags.None; + return new TypeAnalysis(typeSymbol, flags); + } - switch (forEachStatement.Variable) + public static TypeAnalysis AnalyzeType(ForEachVariableStatementSyntax forEachStatement, SemanticModel semanticModel) { - case DeclarationExpressionSyntax declarationExpression: - { - TypeSyntax type = declarationExpression.Type; + var flags = TypeAnalysisFlags.None; - Debug.Assert(type != null); + switch (forEachStatement.Variable) + { + case DeclarationExpressionSyntax declarationExpression: + { + TypeSyntax type = declarationExpression.Type; - if (type == null) - return default; + Debug.Assert(type is not null); - SyntaxDebug.Assert(type.IsVar, type); + if (type is null) + return default; - if (type.IsVar) - flags |= TypeAnalysisFlags.Implicit; + SyntaxDebug.Assert(type.IsVar, type); - break; - } - case TupleExpressionSyntax tupleExpression: - { - foreach (ArgumentSyntax argument in tupleExpression.Arguments) - { - SyntaxDebug.Assert(argument.Expression.IsKind(SyntaxKind.DeclarationExpression), argument.Expression); + if (type.IsVar) + flags |= TypeAnalysisFlags.Implicit; - if (argument.Expression is DeclarationExpressionSyntax declarationExpression) + break; + } + case TupleExpressionSyntax tupleExpression: + { + foreach (ArgumentSyntax argument in tupleExpression.Arguments) { - TypeSyntax type = declarationExpression.Type; + SyntaxDebug.Assert(argument.Expression.IsKind(SyntaxKind.DeclarationExpression), argument.Expression); - if (type.IsVar) + if (argument.Expression is DeclarationExpressionSyntax declarationExpression) { - flags |= TypeAnalysisFlags.Implicit; - } - else - { - flags |= TypeAnalysisFlags.Explicit; + TypeSyntax type = declarationExpression.Type; + + if (type.IsVar) + { + flags |= TypeAnalysisFlags.Implicit; + } + else + { + flags |= TypeAnalysisFlags.Explicit; + } } } + + break; } + default: + { + SyntaxDebug.Fail(forEachStatement.Variable); + return default; + } + } - break; - } - default: - { - SyntaxDebug.Fail(forEachStatement.Variable); - return default; - } - } + ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); - ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); + ITypeSymbol typeSymbol = info.ElementType; - ITypeSymbol typeSymbol = info.ElementType; + if (typeSymbol is null) + return default; - if (typeSymbol == null) - return default; + SymbolKind kind = typeSymbol.Kind; - SymbolKind kind = typeSymbol.Kind; + if (kind == SymbolKind.ErrorType) + return default; - if (kind == SymbolKind.ErrorType) - return default; + if (kind == SymbolKind.DynamicType) + return new TypeAnalysis(typeSymbol, TypeAnalysisFlags.Dynamic); - if (kind == SymbolKind.DynamicType) - return new TypeAnalysis(typeSymbol, TypeAnalysisFlags.Dynamic); + if ((flags & TypeAnalysisFlags.Implicit) != 0 + && typeSymbol.SupportsExplicitDeclaration()) + { + flags |= TypeAnalysisFlags.SupportsExplicit; + } - if ((flags & TypeAnalysisFlags.Implicit) != 0 - && typeSymbol.SupportsExplicitDeclaration()) - { - flags |= TypeAnalysisFlags.SupportsExplicit; - } + if ((flags & TypeAnalysisFlags.Explicit) != 0 + && info.ElementConversion.IsIdentity) + { + flags |= TypeAnalysisFlags.SupportsImplicit; + } - if ((flags & TypeAnalysisFlags.Explicit) != 0 - && info.ElementConversion.IsIdentity) - { - flags |= TypeAnalysisFlags.SupportsImplicit; + return new TypeAnalysis(typeSymbol, flags); } - return new TypeAnalysis(typeSymbol, flags); - } - - public static bool IsImplicitThatCanBeExplicit(ForEachStatementSyntax forEachStatement, SemanticModel semanticModel) - { - TypeSyntax type = forEachStatement.Type; + public static bool IsImplicitThatCanBeExplicit(ForEachStatementSyntax forEachStatement, SemanticModel semanticModel) + { + TypeSyntax type = forEachStatement.Type; - Debug.Assert(type != null); + Debug.Assert(type is not null); - if (type == null) - return false; + if (type is null) + return false; - if (!type.IsVar) - return false; + if (!type.IsVar) + return false; - ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); + ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); - ITypeSymbol typeSymbol = info.ElementType; + ITypeSymbol typeSymbol = info.ElementType; - if (typeSymbol == null) - return false; + if (typeSymbol is null) + return false; - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; - return typeSymbol.SupportsExplicitDeclaration(); - } + return typeSymbol.SupportsExplicitDeclaration(); + } - public static bool IsImplicitThatCanBeExplicit(ForEachVariableStatementSyntax forEachStatement, SemanticModel semanticModel) - { - ExpressionSyntax variable = forEachStatement.Variable; + public static bool IsImplicitThatCanBeExplicit(ForEachVariableStatementSyntax forEachStatement, SemanticModel semanticModel) + { + ExpressionSyntax variable = forEachStatement.Variable; - if (variable is not DeclarationExpressionSyntax declarationExpression) - return false; + if (variable is not DeclarationExpressionSyntax declarationExpression) + return false; - TypeSyntax type = declarationExpression.Type; + TypeSyntax type = declarationExpression.Type; - SyntaxDebug.Assert(type.IsVar, type); + SyntaxDebug.Assert(type.IsVar, type); - if (!type.IsVar) - return false; - - ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); + if (!type.IsVar) + return false; - ITypeSymbol typeSymbol = info.ElementType; + ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); - if (typeSymbol == null) - return false; + ITypeSymbol typeSymbol = info.ElementType; - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; + if (typeSymbol is null) + return false; - return typeSymbol.SupportsExplicitDeclaration(); - } + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; - public static bool IsExplicitThatCanBeImplicit(ForEachStatementSyntax forEachStatement, SemanticModel semanticModel) - { - TypeSyntax type = forEachStatement.Type; + return typeSymbol.SupportsExplicitDeclaration(); + } - Debug.Assert(type != null); + public static bool IsExplicitThatCanBeImplicit(ForEachStatementSyntax forEachStatement, SemanticModel semanticModel) + { + TypeSyntax type = forEachStatement.Type; - if (type == null) - return false; + Debug.Assert(type is not null); - if (type.IsVar) - return false; + if (type is null) + return false; - ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); + if (type.IsVar) + return false; - ITypeSymbol typeSymbol = info.ElementType; + ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); - if (typeSymbol == null) - return false; + ITypeSymbol typeSymbol = info.ElementType; - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; + if (typeSymbol is null) + return false; - return info.ElementConversion.IsIdentity; - } + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; - public static bool IsExplicitThatCanBeImplicit(ForEachVariableStatementSyntax forEachStatement, SemanticModel semanticModel) - { - ExpressionSyntax variable = forEachStatement.Variable; + return info.ElementConversion.IsIdentity; + } - if (variable is not TupleExpressionSyntax tupleExpression) - return false; + public static bool IsExplicitThatCanBeImplicit(ForEachVariableStatementSyntax forEachStatement, SemanticModel semanticModel) + { + ExpressionSyntax variable = forEachStatement.Variable; - return IsExplicitThatCanBeImplicit(tupleExpression, forEachStatement, semanticModel); - } + if (variable is not TupleExpressionSyntax tupleExpression) + return false; - private static bool IsExplicitThatCanBeImplicit( - TupleExpressionSyntax tupleExpression, - ForEachVariableStatementSyntax forEachStatement, - SemanticModel semanticModel) - { - var isAllVar = true; + return IsExplicitThatCanBeImplicit(tupleExpression, forEachStatement, semanticModel); + } - foreach (ArgumentSyntax argument in tupleExpression.Arguments) + private static bool IsExplicitThatCanBeImplicit( + TupleExpressionSyntax tupleExpression, + ForEachVariableStatementSyntax forEachStatement, + SemanticModel semanticModel) { - if (argument.Expression is not DeclarationExpressionSyntax declarationExpression) - return false; + var isAllVar = true; - TypeSyntax type = declarationExpression.Type; + foreach (ArgumentSyntax argument in tupleExpression.Arguments) + { + if (argument.Expression is not DeclarationExpressionSyntax declarationExpression) + return false; - if (type == null) - return false; + TypeSyntax type = declarationExpression.Type; - if (!type.IsVar) - { - isAllVar = false; - break; + if (type is null) + return false; + + if (!type.IsVar) + { + isAllVar = false; + break; + } } - } - if (isAllVar) - return false; + if (isAllVar) + return false; - ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); + ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); - ITypeSymbol typeSymbol = info.ElementType; + ITypeSymbol typeSymbol = info.ElementType; - if (typeSymbol == null) - return false; + if (typeSymbol is null) + return false; - if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) - return false; + if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) + return false; - return info.ElementConversion.IsIdentity; + return info.ElementConversion.IsIdentity; + } } } diff --git a/src/CSharp/CSharp/CSharpUtility.cs b/src/CSharp/CSharp/CSharpUtility.cs index 74a3c18b41..fb860fb402 100644 --- a/src/CSharp/CSharp/CSharpUtility.cs +++ b/src/CSharp/CSharp/CSharpUtility.cs @@ -7,773 +7,774 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal static class CSharpUtility +namespace Roslynator.CSharp { - public static bool IsNullableReferenceType( - TypeSyntax type, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) + internal static class CSharpUtility { - if (type.IsKind(SyntaxKind.NullableType)) + public static bool IsNullableReferenceType( + TypeSyntax type, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) { - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); + if (type.IsKind(SyntaxKind.NullableType)) + { + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); - return !typeSymbol.IsKind(SymbolKind.ErrorType) - && typeSymbol.IsReferenceType; - } + return !typeSymbol.IsKind(SymbolKind.ErrorType) + && typeSymbol.IsReferenceType; + } - return false; - } + return false; + } - public static string GetCountOrLengthPropertyName( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); + public static string GetCountOrLengthPropertyName( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (typeSymbol == null) - return null; + if (typeSymbol is null) + return null; - return SymbolUtility.GetCountOrLengthPropertyName(typeSymbol, semanticModel, expression.SpanStart); - } + return SymbolUtility.GetCountOrLengthPropertyName(typeSymbol, semanticModel, expression.SpanStart); + } - public static bool IsNamespaceInScope( - SyntaxNode node, - INamespaceSymbol namespaceSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + public static bool IsNamespaceInScope( + SyntaxNode node, + INamespaceSymbol namespaceSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - if (namespaceSymbol == null) - throw new ArgumentNullException(nameof(namespaceSymbol)); + if (namespaceSymbol is null) + throw new ArgumentNullException(nameof(namespaceSymbol)); - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - foreach (SyntaxNode ancestor in node.Ancestors()) - { - switch (ancestor) + foreach (SyntaxNode ancestor in node.Ancestors()) { - case NamespaceDeclarationSyntax namespaceDeclaration: - { - if (IsNamespace(namespaceSymbol, namespaceDeclaration.Name, semanticModel, cancellationToken) - || IsNamespace(namespaceSymbol, namespaceDeclaration.Usings, semanticModel, cancellationToken)) + switch (ancestor) + { + case NamespaceDeclarationSyntax namespaceDeclaration: { - return true; - } + if (IsNamespace(namespaceSymbol, namespaceDeclaration.Name, semanticModel, cancellationToken) + || IsNamespace(namespaceSymbol, namespaceDeclaration.Usings, semanticModel, cancellationToken)) + { + return true; + } - break; - } - case CompilationUnitSyntax compilationUnit: - { - if (IsNamespace(namespaceSymbol, compilationUnit.Usings, semanticModel, cancellationToken)) - return true; + break; + } + case CompilationUnitSyntax compilationUnit: + { + if (IsNamespace(namespaceSymbol, compilationUnit.Usings, semanticModel, cancellationToken)) + return true; - break; - } + break; + } + } } - } - return false; - } + return false; + } - private static bool IsNamespace( - INamespaceSymbol namespaceSymbol, - SyntaxList usings, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - foreach (UsingDirectiveSyntax usingDirective in usings) + private static bool IsNamespace( + INamespaceSymbol namespaceSymbol, + SyntaxList usings, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - if (!usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) - && usingDirective.Alias == null - && IsNamespace(namespaceSymbol, usingDirective.Name, semanticModel, cancellationToken)) + foreach (UsingDirectiveSyntax usingDirective in usings) { - return true; + if (!usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) + && usingDirective.Alias is null + && IsNamespace(namespaceSymbol, usingDirective.Name, semanticModel, cancellationToken)) + { + return true; + } } - } - return false; - } + return false; + } - private static bool IsNamespace( - INamespaceSymbol namespaceSymbol, - NameSyntax name, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - if (name != null) + private static bool IsNamespace( + INamespaceSymbol namespaceSymbol, + NameSyntax name, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - ISymbol symbol = semanticModel.GetSymbol(name, cancellationToken); - - if (symbol?.Kind == SymbolKind.Namespace) + if (name is not null) { - string namespaceText = namespaceSymbol.ToString(); + ISymbol symbol = semanticModel.GetSymbol(name, cancellationToken); - if (string.Equals(namespaceText, symbol.ToString(), StringComparison.Ordinal)) - { - return true; - } - else if (name.IsParentKind(SyntaxKind.NamespaceDeclaration)) + if (symbol?.Kind == SymbolKind.Namespace) { - INamespaceSymbol containingNamespace = symbol.ContainingNamespace; + string namespaceText = namespaceSymbol.ToString(); - while (containingNamespace != null) + if (string.Equals(namespaceText, symbol.ToString(), StringComparison.Ordinal)) { - if (string.Equals(namespaceText, containingNamespace.ToString(), StringComparison.Ordinal)) - return true; + return true; + } + else if (name.IsParentKind(SyntaxKind.NamespaceDeclaration)) + { + INamespaceSymbol containingNamespace = symbol.ContainingNamespace; - containingNamespace = containingNamespace.ContainingNamespace; + while (containingNamespace is not null) + { + if (string.Equals(namespaceText, containingNamespace.ToString(), StringComparison.Ordinal)) + return true; + + containingNamespace = containingNamespace.ContainingNamespace; + } } } } - } - return false; - } + return false; + } - public static bool IsStaticClassInScope( - SyntaxNode node, - INamedTypeSymbol staticClassSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + public static bool IsStaticClassInScope( + SyntaxNode node, + INamedTypeSymbol staticClassSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - if (staticClassSymbol == null) - throw new ArgumentNullException(nameof(staticClassSymbol)); + if (staticClassSymbol is null) + throw new ArgumentNullException(nameof(staticClassSymbol)); - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - foreach (SyntaxNode ancestor in node.Ancestors()) - { - foreach (UsingDirectiveSyntax usingDirective in SyntaxInfo.UsingDirectiveListInfo(ancestor).Usings) + foreach (SyntaxNode ancestor in node.Ancestors()) { - if (usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)) + foreach (UsingDirectiveSyntax usingDirective in SyntaxInfo.UsingDirectiveListInfo(ancestor).Usings) { - NameSyntax name = usingDirective.Name; - - if (name != null - && SymbolEqualityComparer.Default.Equals(staticClassSymbol, semanticModel.GetSymbol(name, cancellationToken))) + if (usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)) { - return true; + NameSyntax name = usingDirective.Name; + + if (name is not null + && SymbolEqualityComparer.Default.Equals(staticClassSymbol, semanticModel.GetSymbol(name, cancellationToken))) + { + return true; + } } } } - } - - return false; - } - public static bool IsEmptyStringExpression( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (expression == null) - throw new ArgumentNullException(nameof(expression)); + return false; + } - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + public static bool IsEmptyStringExpression( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (expression is null) + throw new ArgumentNullException(nameof(expression)); - SyntaxKind kind = expression.Kind(); + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - if (kind == SyntaxKind.StringLiteralExpression) - { - return ((LiteralExpressionSyntax)expression).Token.ValueText.Length == 0; - } - else if (kind == SyntaxKind.InterpolatedStringExpression) - { - return !((InterpolatedStringExpressionSyntax)expression).Contents.Any(); - } - else if (kind == SyntaxKind.SimpleMemberAccessExpression) - { - var memberAccess = (MemberAccessExpressionSyntax)expression; + SyntaxKind kind = expression.Kind(); - if (memberAccess.Name?.Identifier.ValueText == "Empty") + if (kind == SyntaxKind.StringLiteralExpression) + { + return ((LiteralExpressionSyntax)expression).Token.ValueText.Length == 0; + } + else if (kind == SyntaxKind.InterpolatedStringExpression) { - ISymbol symbol = semanticModel.GetSymbol(memberAccess, cancellationToken); + return !((InterpolatedStringExpressionSyntax)expression).Contents.Any(); + } + else if (kind == SyntaxKind.SimpleMemberAccessExpression) + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - if (symbol?.Kind == SymbolKind.Field) + if (memberAccess.Name?.Identifier.ValueText == "Empty") { - var fieldSymbol = (IFieldSymbol)symbol; + ISymbol symbol = semanticModel.GetSymbol(memberAccess, cancellationToken); - if (SymbolUtility.IsPublicStaticReadOnly(fieldSymbol, "Empty") - && fieldSymbol.ContainingType?.SpecialType == SpecialType.System_String - && fieldSymbol.Type.IsString()) + if (symbol?.Kind == SymbolKind.Field) { - return true; + var fieldSymbol = (IFieldSymbol)symbol; + + if (SymbolUtility.IsPublicStaticReadOnly(fieldSymbol, "Empty") + && fieldSymbol.ContainingType?.SpecialType == SpecialType.System_String + && fieldSymbol.Type.IsString()) + { + return true; + } } } } - } - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - if (optional.HasValue) - { - var value = optional.Value as string; - - return value?.Length == 0; - } + if (optional.HasValue) + { + var value = optional.Value as string; - return false; - } + return value?.Length == 0; + } - public static bool IsNameOfExpression( - SyntaxNode node, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - return node.IsKind(SyntaxKind.InvocationExpression) - && IsNameOfExpression((InvocationExpressionSyntax)node, semanticModel, cancellationToken); - } + return false; + } - public static bool IsNameOfExpression( - InvocationExpressionSyntax invocationExpression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - ExpressionSyntax expression = invocationExpression.Expression; + public static bool IsNameOfExpression( + SyntaxNode node, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + return node.IsKind(SyntaxKind.InvocationExpression) + && IsNameOfExpression((InvocationExpressionSyntax)node, semanticModel, cancellationToken); + } - if (expression?.Kind() == SyntaxKind.IdentifierName) + public static bool IsNameOfExpression( + InvocationExpressionSyntax invocationExpression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) { - var identifierName = (IdentifierNameSyntax)expression; + ExpressionSyntax expression = invocationExpression.Expression; - if (string.Equals(identifierName.Identifier.ValueText, "nameof", StringComparison.Ordinal) - && semanticModel.GetSymbol(invocationExpression, cancellationToken) == null) + if (expression?.Kind() == SyntaxKind.IdentifierName) { - return true; - } - } - - return false; - } + var identifierName = (IdentifierNameSyntax)expression; - public static bool IsStringConcatenation(BinaryExpressionSyntax addExpression, SemanticModel semanticModel, CancellationToken cancellationToken = default) - { - return addExpression.Kind() == SyntaxKind.AddExpression - && SymbolUtility.IsStringAdditionOperator(semanticModel.GetMethodSymbol(addExpression, cancellationToken)); - } + if (string.Equals(identifierName.Identifier.ValueText, "nameof", StringComparison.Ordinal) + && semanticModel.GetSymbol(invocationExpression, cancellationToken) is null) + { + return true; + } + } - public static bool IsStringLiteralConcatenation(BinaryExpressionSyntax binaryExpression) - { - if (binaryExpression?.Kind() != SyntaxKind.AddExpression) return false; + } - while (true) + public static bool IsStringConcatenation(BinaryExpressionSyntax addExpression, SemanticModel semanticModel, CancellationToken cancellationToken = default) { - if (binaryExpression.Right?.WalkDownParentheses().Kind() != SyntaxKind.StringLiteralExpression) - return false; + return addExpression.Kind() == SyntaxKind.AddExpression + && SymbolUtility.IsStringAdditionOperator(semanticModel.GetMethodSymbol(addExpression, cancellationToken)); + } - ExpressionSyntax left = binaryExpression.Left?.WalkDownParentheses(); + public static bool IsStringLiteralConcatenation(BinaryExpressionSyntax binaryExpression) + { + if (binaryExpression?.Kind() != SyntaxKind.AddExpression) + return false; - switch (left?.Kind()) + while (true) { - case SyntaxKind.StringLiteralExpression: - { - return true; - } - case SyntaxKind.AddExpression: - { - binaryExpression = (BinaryExpressionSyntax)left; - break; - } - default: - { - return false; - } + if (binaryExpression.Right?.WalkDownParentheses().Kind() != SyntaxKind.StringLiteralExpression) + return false; + + ExpressionSyntax left = binaryExpression.Left?.WalkDownParentheses(); + + switch (left?.Kind()) + { + case SyntaxKind.StringLiteralExpression: + { + return true; + } + case SyntaxKind.AddExpression: + { + binaryExpression = (BinaryExpressionSyntax)left; + break; + } + default: + { + return false; + } + } } } - } - - public static bool IsStringExpression(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) - { - if (expression == null) - return false; - if (expression - .WalkDownParentheses() - .Kind() - .Is(SyntaxKind.StringLiteralExpression, SyntaxKind.InterpolatedStringExpression)) + public static bool IsStringExpression(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { - return true; - } + if (expression is null) + return false; - return semanticModel.GetTypeInfo(expression, cancellationToken) - .Type? - .SpecialType == SpecialType.System_String; - } + if (expression + .WalkDownParentheses() + .Kind() + .Is(SyntaxKind.StringLiteralExpression, SyntaxKind.InterpolatedStringExpression)) + { + return true; + } - public static SyntaxToken GetIdentifier(SyntaxNode node) - { - switch (node.Kind()) - { - case SyntaxKind.ClassDeclaration: - return ((ClassDeclarationSyntax)node).Identifier; - case SyntaxKind.StructDeclaration: - return ((StructDeclarationSyntax)node).Identifier; - case SyntaxKind.InterfaceDeclaration: - return ((InterfaceDeclarationSyntax)node).Identifier; - case SyntaxKind.EnumDeclaration: - return ((EnumDeclarationSyntax)node).Identifier; - case SyntaxKind.DelegateDeclaration: - return ((DelegateDeclarationSyntax)node).Identifier; - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)node).Identifier; - case SyntaxKind.ConstructorDeclaration: - return ((ConstructorDeclarationSyntax)node).Identifier; - case SyntaxKind.PropertyDeclaration: - return ((PropertyDeclarationSyntax)node).Identifier; - case SyntaxKind.IndexerDeclaration: - return ((IndexerDeclarationSyntax)node).ThisKeyword; - case SyntaxKind.EventDeclaration: - return ((EventDeclarationSyntax)node).Identifier; - case SyntaxKind.EventFieldDeclaration: - return ((EventFieldDeclarationSyntax)node).Declaration?.Variables.FirstOrDefault()?.Identifier ?? default; - case SyntaxKind.FieldDeclaration: - return ((FieldDeclarationSyntax)node).Declaration?.Variables.FirstOrDefault()?.Identifier ?? default; - case SyntaxKind.VariableDeclarator: - return ((VariableDeclaratorSyntax)node).Identifier; - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return ((RecordDeclarationSyntax)node).Identifier; - case SyntaxKind.Parameter: - return ((ParameterSyntax)node).Identifier; - case SyntaxKind.TypeParameter: - return ((TypeParameterSyntax)node).Identifier; - case SyntaxKind.EnumMemberDeclaration: - return ((EnumMemberDeclarationSyntax)node).Identifier; - case SyntaxKind.ForEachStatement: - return ((ForEachStatementSyntax)node).Identifier; - case SyntaxKind.CatchDeclaration: - return ((CatchDeclarationSyntax)node).Identifier; - case SyntaxKind.SingleVariableDesignation: - return ((SingleVariableDesignationSyntax)node).Identifier; - case SyntaxKind.LocalFunctionStatement: - return ((LocalFunctionStatementSyntax)node).Identifier; + return semanticModel.GetTypeInfo(expression, cancellationToken) + .Type? + .SpecialType == SpecialType.System_String; } - return default; - } - - public static bool IsPartOfExpressionThatMustBeConstant(ExpressionSyntax expression) - { - for (SyntaxNode parent = expression.Parent; parent != null; parent = parent.Parent) + public static SyntaxToken GetIdentifier(SyntaxNode node) { - switch (parent.Kind()) + switch (node.Kind()) { - case SyntaxKind.AttributeArgument: - case SyntaxKind.Parameter: - case SyntaxKind.CaseSwitchLabel: - case SyntaxKind.ConstantPattern: - return true; - case SyntaxKind.FieldDeclaration: - return ((FieldDeclarationSyntax)parent).Modifiers.Contains(SyntaxKind.ConstKeyword); - case SyntaxKind.LocalDeclarationStatement: - return ((LocalDeclarationStatementSyntax)parent).Modifiers.Contains(SyntaxKind.ConstKeyword); - case SyntaxKind.Block: - case SyntaxKind.ExpressionStatement: - case SyntaxKind.EmptyStatement: - case SyntaxKind.LabeledStatement: - case SyntaxKind.GotoStatement: - case SyntaxKind.GotoCaseStatement: - case SyntaxKind.GotoDefaultStatement: - case SyntaxKind.BreakStatement: - case SyntaxKind.ContinueStatement: - case SyntaxKind.ReturnStatement: - case SyntaxKind.YieldReturnStatement: - case SyntaxKind.YieldBreakStatement: - case SyntaxKind.ThrowStatement: - case SyntaxKind.WhileStatement: - case SyntaxKind.DoStatement: - case SyntaxKind.ForStatement: - case SyntaxKind.ForEachStatement: - case SyntaxKind.ForEachVariableStatement: - case SyntaxKind.UsingStatement: - case SyntaxKind.FixedStatement: - case SyntaxKind.CheckedStatement: - case SyntaxKind.UncheckedStatement: - case SyntaxKind.UnsafeStatement: - case SyntaxKind.LockStatement: - case SyntaxKind.IfStatement: - case SyntaxKind.SwitchStatement: - case SyntaxKind.TryStatement: - case SyntaxKind.LocalFunctionStatement: - case SyntaxKind.GlobalStatement: - case SyntaxKind.NamespaceDeclaration: case SyntaxKind.ClassDeclaration: + return ((ClassDeclarationSyntax)node).Identifier; case SyntaxKind.StructDeclaration: - case SyntaxKind.RecordStructDeclaration: + return ((StructDeclarationSyntax)node).Identifier; case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.RecordDeclaration: + return ((InterfaceDeclarationSyntax)node).Identifier; case SyntaxKind.EnumDeclaration: + return ((EnumDeclarationSyntax)node).Identifier; case SyntaxKind.DelegateDeclaration: - case SyntaxKind.EnumMemberDeclaration: - case SyntaxKind.EventFieldDeclaration: + return ((DelegateDeclarationSyntax)node).Identifier; case SyntaxKind.MethodDeclaration: - case SyntaxKind.OperatorDeclaration: - case SyntaxKind.ConversionOperatorDeclaration: + return ((MethodDeclarationSyntax)node).Identifier; case SyntaxKind.ConstructorDeclaration: - case SyntaxKind.DestructorDeclaration: + return ((ConstructorDeclarationSyntax)node).Identifier; case SyntaxKind.PropertyDeclaration: - case SyntaxKind.EventDeclaration: + return ((PropertyDeclarationSyntax)node).Identifier; case SyntaxKind.IndexerDeclaration: - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.UnknownAccessorDeclaration: - case SyntaxKind.IncompleteMember: - case SyntaxKind.ArrowExpressionClause: - case SyntaxKind.ThisConstructorInitializer: - case SyntaxKind.BaseConstructorInitializer: - case SyntaxKind.SwitchExpressionArm: - case SyntaxKind.AnonymousObjectMemberDeclarator: - return false; -#if DEBUG - default: - { - if (parent is ExpressionSyntax) - break; + return ((IndexerDeclarationSyntax)node).ThisKeyword; + case SyntaxKind.EventDeclaration: + return ((EventDeclarationSyntax)node).Identifier; + case SyntaxKind.EventFieldDeclaration: + return ((EventFieldDeclarationSyntax)node).Declaration?.Variables.FirstOrDefault()?.Identifier ?? default; + case SyntaxKind.FieldDeclaration: + return ((FieldDeclarationSyntax)node).Declaration?.Variables.FirstOrDefault()?.Identifier ?? default; + case SyntaxKind.VariableDeclarator: + return ((VariableDeclaratorSyntax)node).Identifier; + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((RecordDeclarationSyntax)node).Identifier; + case SyntaxKind.Parameter: + return ((ParameterSyntax)node).Identifier; + case SyntaxKind.TypeParameter: + return ((TypeParameterSyntax)node).Identifier; + case SyntaxKind.EnumMemberDeclaration: + return ((EnumMemberDeclarationSyntax)node).Identifier; + case SyntaxKind.ForEachStatement: + return ((ForEachStatementSyntax)node).Identifier; + case SyntaxKind.CatchDeclaration: + return ((CatchDeclarationSyntax)node).Identifier; + case SyntaxKind.SingleVariableDesignation: + return ((SingleVariableDesignationSyntax)node).Identifier; + case SyntaxKind.LocalFunctionStatement: + return ((LocalFunctionStatementSyntax)node).Identifier; + } + + return default; + } - switch (parent.Kind()) + public static bool IsPartOfExpressionThatMustBeConstant(ExpressionSyntax expression) + { + for (SyntaxNode parent = expression.Parent; parent is not null; parent = parent.Parent) + { + switch (parent.Kind()) + { + case SyntaxKind.AttributeArgument: + case SyntaxKind.Parameter: + case SyntaxKind.CaseSwitchLabel: + case SyntaxKind.ConstantPattern: + return true; + case SyntaxKind.FieldDeclaration: + return ((FieldDeclarationSyntax)parent).Modifiers.Contains(SyntaxKind.ConstKeyword); + case SyntaxKind.LocalDeclarationStatement: + return ((LocalDeclarationStatementSyntax)parent).Modifiers.Contains(SyntaxKind.ConstKeyword); + case SyntaxKind.Block: + case SyntaxKind.ExpressionStatement: + case SyntaxKind.EmptyStatement: + case SyntaxKind.LabeledStatement: + case SyntaxKind.GotoStatement: + case SyntaxKind.GotoCaseStatement: + case SyntaxKind.GotoDefaultStatement: + case SyntaxKind.BreakStatement: + case SyntaxKind.ContinueStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.YieldBreakStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.WhileStatement: + case SyntaxKind.DoStatement: + case SyntaxKind.ForStatement: + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + case SyntaxKind.UsingStatement: + case SyntaxKind.FixedStatement: + case SyntaxKind.CheckedStatement: + case SyntaxKind.UncheckedStatement: + case SyntaxKind.UnsafeStatement: + case SyntaxKind.LockStatement: + case SyntaxKind.IfStatement: + case SyntaxKind.SwitchStatement: + case SyntaxKind.TryStatement: + case SyntaxKind.LocalFunctionStatement: + case SyntaxKind.GlobalStatement: + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.RecordStructDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.DelegateDeclaration: + case SyntaxKind.EnumMemberDeclaration: + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.DestructorDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.IndexerDeclaration: + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + case SyntaxKind.IncompleteMember: + case SyntaxKind.ArrowExpressionClause: + case SyntaxKind.ThisConstructorInitializer: + case SyntaxKind.BaseConstructorInitializer: + case SyntaxKind.SwitchExpressionArm: + case SyntaxKind.AnonymousObjectMemberDeclarator: + return false; +#if DEBUG + 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; - } - } + if (parent is ExpressionSyntax) + break; + + switch (parent.Kind()) + { + 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; + } + } - break; - } + break; + } #endif + } } + + return false; } - return false; - } + public static IEnumerable EnumerateExpressionChain(ExpressionSyntax expression) + { + SyntaxNode e = expression; - public static IEnumerable EnumerateExpressionChain(ExpressionSyntax expression) - { - SyntaxNode e = expression; + yield return e; - yield return e; + while (true) + { + ExpressionSyntax last = GetLastChild(e); - while (true) - { - ExpressionSyntax last = GetLastChild(e); + if (last is not null) + { + e = last; + } + else + { + while (e != expression + && IsFirstChild(e)) + { + e = e.Parent; + } - if (last != null) - { - e = last; + if (e == expression) + break; + + e = GetPreviousSibling(e); + } + + yield return e; } - else + + static ExpressionSyntax GetLastChild(SyntaxNode node) { - while (e != expression - && IsFirstChild(e)) + switch (node?.Kind()) { - e = e.Parent; + case SyntaxKind.ConditionalAccessExpression: + return ((ConditionalAccessExpressionSyntax)node).WhenNotNull; + case SyntaxKind.MemberBindingExpression: + return ((MemberBindingExpressionSyntax)node).Name; + case SyntaxKind.SimpleMemberAccessExpression: + return ((MemberAccessExpressionSyntax)node).Name; + case SyntaxKind.ElementAccessExpression: + return ((ElementAccessExpressionSyntax)node).Expression; + case SyntaxKind.InvocationExpression: + return ((InvocationExpressionSyntax)node).Expression; } - if (e == expression) - break; - - e = GetPreviousSibling(e); + return null; } - yield return e; - } - - static ExpressionSyntax GetLastChild(SyntaxNode node) - { - switch (node?.Kind()) + static SyntaxNode GetPreviousSibling(SyntaxNode node) { - case SyntaxKind.ConditionalAccessExpression: - return ((ConditionalAccessExpressionSyntax)node).WhenNotNull; - case SyntaxKind.MemberBindingExpression: - return ((MemberBindingExpressionSyntax)node).Name; - case SyntaxKind.SimpleMemberAccessExpression: - return ((MemberAccessExpressionSyntax)node).Name; - case SyntaxKind.ElementAccessExpression: - return ((ElementAccessExpressionSyntax)node).Expression; - case SyntaxKind.InvocationExpression: - return ((InvocationExpressionSyntax)node).Expression; - } + SyntaxNode parent = node.Parent; - return null; - } + switch (parent.Kind()) + { + case SyntaxKind.ConditionalAccessExpression: + { + var conditionalAccess = (ConditionalAccessExpressionSyntax)parent; - static SyntaxNode GetPreviousSibling(SyntaxNode node) - { - SyntaxNode parent = node.Parent; + if (conditionalAccess.WhenNotNull == node) + return conditionalAccess.Expression; - switch (parent.Kind()) - { - case SyntaxKind.ConditionalAccessExpression: - { - var conditionalAccess = (ConditionalAccessExpressionSyntax)parent; + break; + } + case SyntaxKind.SimpleMemberAccessExpression: + { + var memberAccess = (MemberAccessExpressionSyntax)parent; - if (conditionalAccess.WhenNotNull == node) - return conditionalAccess.Expression; + if (memberAccess.Name == node) + return memberAccess.Expression; - break; - } - case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)parent; + break; + } + } + + return null; + } - if (memberAccess.Name == node) - return memberAccess.Expression; + static bool IsFirstChild(SyntaxNode node) + { + SyntaxNode parent = node.Parent; - break; - } + switch (parent.Kind()) + { + case SyntaxKind.ConditionalAccessExpression: + return ((ConditionalAccessExpressionSyntax)parent).Expression == node; + case SyntaxKind.SimpleMemberAccessExpression: + return ((MemberAccessExpressionSyntax)parent).Expression == node; + } + + return true; } + } + + public static ArrowExpressionClauseSyntax GetExpressionBody(SyntaxNode node) + { + switch (node.Kind()) + { + case SyntaxKind.MethodDeclaration: + return ((MethodDeclarationSyntax)node).ExpressionBody; + case SyntaxKind.PropertyDeclaration: + return ((PropertyDeclarationSyntax)node).ExpressionBody; + case SyntaxKind.IndexerDeclaration: + return ((IndexerDeclarationSyntax)node).ExpressionBody; + case SyntaxKind.OperatorDeclaration: + return ((OperatorDeclarationSyntax)node).ExpressionBody; + case SyntaxKind.ConversionOperatorDeclaration: + return ((ConversionOperatorDeclarationSyntax)node).ExpressionBody; + case SyntaxKind.ConstructorDeclaration: + return ((ConstructorDeclarationSyntax)node).ExpressionBody; + case SyntaxKind.DestructorDeclaration: + return ((DestructorDeclarationSyntax)node).ExpressionBody; + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + return ((AccessorDeclarationSyntax)node).ExpressionBody; + case SyntaxKind.LocalFunctionStatement: + return ((LocalFunctionStatementSyntax)node).ExpressionBody; + } + + SyntaxDebug.Assert(!CSharpFacts.CanHaveExpressionBody(node.Kind()), node); return null; } - static bool IsFirstChild(SyntaxNode node) + public static bool IsConditionallyAccessed(SyntaxNode node) { - SyntaxNode parent = node.Parent; + SyntaxNode prev = node; - switch (parent.Kind()) + for (SyntaxNode parent = node.Parent; parent is not null; parent = parent.Parent) { - case SyntaxKind.ConditionalAccessExpression: - return ((ConditionalAccessExpressionSyntax)parent).Expression == node; - case SyntaxKind.SimpleMemberAccessExpression: - return ((MemberAccessExpressionSyntax)parent).Expression == node; + switch (parent.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.InvocationExpression: + { + break; + } + case SyntaxKind.ConditionalAccessExpression: + { + if (((ConditionalAccessExpressionSyntax)parent).WhenNotNull == prev) + return true; + + break; + } + default: + { + return false; + } + } + + prev = parent; } - return true; + return false; } - } - public static ArrowExpressionClauseSyntax GetExpressionBody(SyntaxNode node) - { - switch (node.Kind()) + public static ExpressionSyntax GetTopmostExpressionInCallChain(ExpressionSyntax expression) { - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)node).ExpressionBody; - case SyntaxKind.PropertyDeclaration: - return ((PropertyDeclarationSyntax)node).ExpressionBody; - case SyntaxKind.IndexerDeclaration: - return ((IndexerDeclarationSyntax)node).ExpressionBody; - case SyntaxKind.OperatorDeclaration: - return ((OperatorDeclarationSyntax)node).ExpressionBody; - case SyntaxKind.ConversionOperatorDeclaration: - return ((ConversionOperatorDeclarationSyntax)node).ExpressionBody; - case SyntaxKind.ConstructorDeclaration: - return ((ConstructorDeclarationSyntax)node).ExpressionBody; - case SyntaxKind.DestructorDeclaration: - return ((DestructorDeclarationSyntax)node).ExpressionBody; - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - return ((AccessorDeclarationSyntax)node).ExpressionBody; - case SyntaxKind.LocalFunctionStatement: - return ((LocalFunctionStatementSyntax)node).ExpressionBody; + return (ExpressionSyntax)expression.WalkUp(f => f.IsKind( + SyntaxKind.ConditionalAccessExpression, + SyntaxKind.SimpleMemberAccessExpression, + SyntaxKind.ElementAccessExpression, + SyntaxKind.MemberBindingExpression, + SyntaxKind.InvocationExpression)); } - SyntaxDebug.Assert(!CSharpFacts.CanHaveExpressionBody(node.Kind()), node); - - return null; - } + internal static IFieldSymbol FindEnumDefaultField(INamedTypeSymbol enumSymbol) + { + if (enumSymbol is null) + throw new ArgumentNullException(nameof(enumSymbol)); - public static bool IsConditionallyAccessed(SyntaxNode node) - { - SyntaxNode prev = node; + if (enumSymbol.EnumUnderlyingType is null) + throw new ArgumentException($"'{enumSymbol}' is not an enumeration.", nameof(enumSymbol)); - for (SyntaxNode parent = node.Parent; parent != null; parent = parent.Parent) - { - switch (parent.Kind()) + foreach (ISymbol symbol in enumSymbol.GetMembers()) { - case SyntaxKind.SimpleMemberAccessExpression: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.InvocationExpression: - { - break; - } - case SyntaxKind.ConditionalAccessExpression: - { - if (((ConditionalAccessExpressionSyntax)parent).WhenNotNull == prev) - return true; + if (symbol.Kind == SymbolKind.Field) + { + var fieldSymbol = (IFieldSymbol)symbol; - break; - } - default: + if (fieldSymbol.HasConstantValue + && SymbolUtility.GetEnumValueAsUInt64(fieldSymbol.ConstantValue, enumSymbol) == 0) { - return false; + return fieldSymbol; } + } } - prev = parent; + return default; } - return false; - } - - public static ExpressionSyntax GetTopmostExpressionInCallChain(ExpressionSyntax expression) - { - return (ExpressionSyntax)expression.WalkUp(f => f.IsKind( - SyntaxKind.ConditionalAccessExpression, - SyntaxKind.SimpleMemberAccessExpression, - SyntaxKind.ElementAccessExpression, - SyntaxKind.MemberBindingExpression, - SyntaxKind.InvocationExpression)); - } - - internal static IFieldSymbol FindEnumDefaultField(INamedTypeSymbol enumSymbol) - { - if (enumSymbol == null) - throw new ArgumentNullException(nameof(enumSymbol)); - - if (enumSymbol.EnumUnderlyingType == null) - throw new ArgumentException($"'{enumSymbol}' is not an enumeration.", nameof(enumSymbol)); - - foreach (ISymbol symbol in enumSymbol.GetMembers()) + public static TypeSyntax GetTypeOrReturnType(SyntaxNode node) { - if (symbol.Kind == SymbolKind.Field) + switch (node.Kind()) { - var fieldSymbol = (IFieldSymbol)symbol; + case SyntaxKind.MethodDeclaration: + return ((MethodDeclarationSyntax)node).ReturnType; + case SyntaxKind.OperatorDeclaration: + return ((OperatorDeclarationSyntax)node).ReturnType; + case SyntaxKind.ConversionOperatorDeclaration: + return ((ConversionOperatorDeclarationSyntax)node).Type; + case SyntaxKind.PropertyDeclaration: + return ((PropertyDeclarationSyntax)node).Type; + case SyntaxKind.IndexerDeclaration: + return ((IndexerDeclarationSyntax)node).Type; + case SyntaxKind.FieldDeclaration: + return ((FieldDeclarationSyntax)node).Declaration.Type; + case SyntaxKind.EventDeclaration: + return ((EventDeclarationSyntax)node).Type; + case SyntaxKind.EventFieldDeclaration: + return ((EventFieldDeclarationSyntax)node).Declaration.Type; + case SyntaxKind.LocalFunctionStatement: + return ((LocalFunctionStatementSyntax)node).ReturnType; + default: + return null; + } + } - if (fieldSymbol.HasConstantValue - && SymbolUtility.GetEnumValueAsUInt64(fieldSymbol.ConstantValue, enumSymbol) == 0) + public static bool ContainsOutArgumentWithLocalOrParameter( + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + foreach (SyntaxNode node in expression.DescendantNodes()) + { + if (node is ArgumentSyntax argument + && argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) { - return fieldSymbol; + ExpressionSyntax argumentExpression = argument.Expression; + + if (argumentExpression?.IsMissing == false + && semanticModel.GetSymbol(argumentExpression, cancellationToken)?.IsKind(SymbolKind.Local, SymbolKind.Parameter) == true) + { + return true; + } } } - } - return default; - } + return false; + } - public static TypeSyntax GetTypeOrReturnType(SyntaxNode node) - { - switch (node.Kind()) + public static SeparatedSyntaxList GetParameters(SyntaxNode declaration) { - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)node).ReturnType; - case SyntaxKind.OperatorDeclaration: - return ((OperatorDeclarationSyntax)node).ReturnType; - case SyntaxKind.ConversionOperatorDeclaration: - return ((ConversionOperatorDeclarationSyntax)node).Type; - case SyntaxKind.PropertyDeclaration: - return ((PropertyDeclarationSyntax)node).Type; - case SyntaxKind.IndexerDeclaration: - return ((IndexerDeclarationSyntax)node).Type; - case SyntaxKind.FieldDeclaration: - return ((FieldDeclarationSyntax)node).Declaration.Type; - case SyntaxKind.EventDeclaration: - return ((EventDeclarationSyntax)node).Type; - case SyntaxKind.EventFieldDeclaration: - return ((EventFieldDeclarationSyntax)node).Declaration.Type; - case SyntaxKind.LocalFunctionStatement: - return ((LocalFunctionStatementSyntax)node).ReturnType; - default: - return null; + return GetParameterList(declaration)?.Parameters ?? default; } - } - public static bool ContainsOutArgumentWithLocalOrParameter( - ExpressionSyntax expression, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - foreach (SyntaxNode node in expression.DescendantNodes()) + public static BaseParameterListSyntax GetParameterList(SyntaxNode declaration) { - if (node is ArgumentSyntax argument - && argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) + switch (declaration.Kind()) { - ExpressionSyntax argumentExpression = argument.Expression; - - if (argumentExpression?.IsMissing == false - && semanticModel.GetSymbol(argumentExpression, cancellationToken)?.IsKind(SymbolKind.Local, SymbolKind.Parameter) == true) - { - return true; - } + case SyntaxKind.MethodDeclaration: + return ((MethodDeclarationSyntax)declaration).ParameterList; + case SyntaxKind.ConstructorDeclaration: + return ((ConstructorDeclarationSyntax)declaration).ParameterList; + case SyntaxKind.OperatorDeclaration: + return ((OperatorDeclarationSyntax)declaration).ParameterList; + case SyntaxKind.ConversionOperatorDeclaration: + return ((ConversionOperatorDeclarationSyntax)declaration).ParameterList; + case SyntaxKind.DelegateDeclaration: + return ((DelegateDeclarationSyntax)declaration).ParameterList; + case SyntaxKind.IndexerDeclaration: + return ((IndexerDeclarationSyntax)declaration).ParameterList; + case SyntaxKind.LocalFunctionStatement: + return ((LocalFunctionStatementSyntax)declaration).ParameterList; + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((RecordDeclarationSyntax)declaration).ParameterList; + default: + return null; } } - return false; - } - - public static SeparatedSyntaxList GetParameters(SyntaxNode declaration) - { - return GetParameterList(declaration)?.Parameters ?? default; - } - - public static BaseParameterListSyntax GetParameterList(SyntaxNode declaration) - { - switch (declaration.Kind()) + public static SeparatedSyntaxList GetTypeParameters(SyntaxNode declaration) { - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)declaration).ParameterList; - case SyntaxKind.ConstructorDeclaration: - return ((ConstructorDeclarationSyntax)declaration).ParameterList; - case SyntaxKind.OperatorDeclaration: - return ((OperatorDeclarationSyntax)declaration).ParameterList; - case SyntaxKind.ConversionOperatorDeclaration: - return ((ConversionOperatorDeclarationSyntax)declaration).ParameterList; - case SyntaxKind.DelegateDeclaration: - return ((DelegateDeclarationSyntax)declaration).ParameterList; - case SyntaxKind.IndexerDeclaration: - return ((IndexerDeclarationSyntax)declaration).ParameterList; - case SyntaxKind.LocalFunctionStatement: - return ((LocalFunctionStatementSyntax)declaration).ParameterList; - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return ((RecordDeclarationSyntax)declaration).ParameterList; - default: - return null; + return GetTypeParameterList(declaration)?.Parameters ?? default; } - } - - public static SeparatedSyntaxList GetTypeParameters(SyntaxNode declaration) - { - return GetTypeParameterList(declaration)?.Parameters ?? default; - } - public static TypeParameterListSyntax GetTypeParameterList(SyntaxNode declaration) - { - switch (declaration.Kind()) + public static TypeParameterListSyntax GetTypeParameterList(SyntaxNode declaration) { - case SyntaxKind.ClassDeclaration: - return ((ClassDeclarationSyntax)declaration).TypeParameterList; - case SyntaxKind.InterfaceDeclaration: - return ((InterfaceDeclarationSyntax)declaration).TypeParameterList; - case SyntaxKind.StructDeclaration: - return ((StructDeclarationSyntax)declaration).TypeParameterList; - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)declaration).TypeParameterList; - case SyntaxKind.DelegateDeclaration: - return ((DelegateDeclarationSyntax)declaration).TypeParameterList; - case SyntaxKind.LocalFunctionStatement: - return ((LocalFunctionStatementSyntax)declaration).TypeParameterList; - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return ((RecordDeclarationSyntax)declaration).TypeParameterList; - default: - return null; + switch (declaration.Kind()) + { + case SyntaxKind.ClassDeclaration: + return ((ClassDeclarationSyntax)declaration).TypeParameterList; + case SyntaxKind.InterfaceDeclaration: + return ((InterfaceDeclarationSyntax)declaration).TypeParameterList; + case SyntaxKind.StructDeclaration: + return ((StructDeclarationSyntax)declaration).TypeParameterList; + case SyntaxKind.MethodDeclaration: + return ((MethodDeclarationSyntax)declaration).TypeParameterList; + case SyntaxKind.DelegateDeclaration: + return ((DelegateDeclarationSyntax)declaration).TypeParameterList; + case SyntaxKind.LocalFunctionStatement: + return ((LocalFunctionStatementSyntax)declaration).TypeParameterList; + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((RecordDeclarationSyntax)declaration).TypeParameterList; + default: + return null; + } } } } diff --git a/src/CSharp/CSharp/Documentation/AddNewDocumentationCommentRewriter.cs b/src/CSharp/CSharp/Documentation/AddNewDocumentationCommentRewriter.cs index ca2498cf18..1bab643cf8 100644 --- a/src/CSharp/CSharp/Documentation/AddNewDocumentationCommentRewriter.cs +++ b/src/CSharp/CSharp/Documentation/AddNewDocumentationCommentRewriter.cs @@ -1,5 +1,6 @@ // Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -27,6 +28,11 @@ protected virtual MemberDeclarationSyntax AddDocumentationComment(MemberDeclarat public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) { + if (node is null) + { + throw new ArgumentNullException(nameof(node)); + } + node = (NamespaceDeclarationSyntax)base.VisitNamespaceDeclaration(node); if (!SkipNamespaceDeclaration diff --git a/src/CSharp/CSharp/Documentation/DocumentationCommentGenerator.cs b/src/CSharp/CSharp/Documentation/DocumentationCommentGenerator.cs index 8bda79a4a1..fe9d58c7f2 100644 --- a/src/CSharp/CSharp/Documentation/DocumentationCommentGenerator.cs +++ b/src/CSharp/CSharp/Documentation/DocumentationCommentGenerator.cs @@ -15,630 +15,631 @@ using Roslynator.Documentation; using Roslynator.Text; -namespace Roslynator.CSharp.Documentation; - -internal static class DocumentationCommentGenerator +namespace Roslynator.CSharp.Documentation { - private static readonly XmlReaderSettings _xmlReaderSettings = new() { ConformanceLevel = ConformanceLevel.Fragment }; - - public static SyntaxTriviaList Generate(MemberDeclarationSyntax memberDeclaration, DocumentationCommentGeneratorSettings settings = null) + internal static class DocumentationCommentGenerator { - if (memberDeclaration == null) - throw new ArgumentNullException(nameof(memberDeclaration)); - - switch (memberDeclaration.Kind()) - { - case SyntaxKind.NamespaceDeclaration: - return Generate((NamespaceDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.ClassDeclaration: - return Generate((ClassDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.StructDeclaration: - return Generate((StructDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.InterfaceDeclaration: - return Generate((InterfaceDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.EnumDeclaration: - return Generate((EnumDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.DelegateDeclaration: - return Generate((DelegateDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.EnumMemberDeclaration: - return Generate((EnumMemberDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.FieldDeclaration: - return Generate((FieldDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.EventFieldDeclaration: - return Generate((EventFieldDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.MethodDeclaration: - return Generate((MethodDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.OperatorDeclaration: - return Generate((OperatorDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.ConversionOperatorDeclaration: - return Generate((ConversionOperatorDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.ConstructorDeclaration: - return Generate((ConstructorDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.DestructorDeclaration: - return Generate((DestructorDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.PropertyDeclaration: - return Generate((PropertyDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.EventDeclaration: - return Generate((EventDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.IndexerDeclaration: - return Generate((IndexerDeclarationSyntax)memberDeclaration, settings); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return Generate((RecordDeclarationSyntax)memberDeclaration, settings); - default: - throw new ArgumentException("", nameof(memberDeclaration)); + private static readonly XmlReaderSettings _xmlReaderSettings = new() { ConformanceLevel = ConformanceLevel.Fragment }; + + public static SyntaxTriviaList Generate(MemberDeclarationSyntax memberDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (memberDeclaration is null) + throw new ArgumentNullException(nameof(memberDeclaration)); + + switch (memberDeclaration.Kind()) + { + case SyntaxKind.NamespaceDeclaration: + return Generate((NamespaceDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.ClassDeclaration: + return Generate((ClassDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.StructDeclaration: + return Generate((StructDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.InterfaceDeclaration: + return Generate((InterfaceDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.EnumDeclaration: + return Generate((EnumDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.DelegateDeclaration: + return Generate((DelegateDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.EnumMemberDeclaration: + return Generate((EnumMemberDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.FieldDeclaration: + return Generate((FieldDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.EventFieldDeclaration: + return Generate((EventFieldDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.MethodDeclaration: + return Generate((MethodDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.OperatorDeclaration: + return Generate((OperatorDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.ConversionOperatorDeclaration: + return Generate((ConversionOperatorDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.ConstructorDeclaration: + return Generate((ConstructorDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.DestructorDeclaration: + return Generate((DestructorDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.PropertyDeclaration: + return Generate((PropertyDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.EventDeclaration: + return Generate((EventDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.IndexerDeclaration: + return Generate((IndexerDeclarationSyntax)memberDeclaration, settings); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return Generate((RecordDeclarationSyntax)memberDeclaration, settings); + default: + throw new ArgumentException("", nameof(memberDeclaration)); + } } - } - public static SyntaxTriviaList Generate(NamespaceDeclarationSyntax namespaceDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (namespaceDeclaration == null) - throw new ArgumentNullException(nameof(namespaceDeclaration)); + public static SyntaxTriviaList Generate(NamespaceDeclarationSyntax namespaceDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (namespaceDeclaration is null) + throw new ArgumentNullException(nameof(namespaceDeclaration)); - return Generate(settings: settings); - } + return Generate(settings: settings); + } - public static SyntaxTriviaList Generate(ClassDeclarationSyntax classDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (classDeclaration == null) - throw new ArgumentNullException(nameof(classDeclaration)); - - return Generate( - classDeclaration.TypeParameterList, - default(ParameterListSyntax), - canGenerateReturns: false, - settings: settings); - } + public static SyntaxTriviaList Generate(ClassDeclarationSyntax classDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (classDeclaration is null) + throw new ArgumentNullException(nameof(classDeclaration)); + + return Generate( + classDeclaration.TypeParameterList, + default(ParameterListSyntax), + canGenerateReturns: false, + settings: settings); + } - public static SyntaxTriviaList Generate(RecordDeclarationSyntax recordDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (recordDeclaration == null) - throw new ArgumentNullException(nameof(recordDeclaration)); - - return Generate( - recordDeclaration.TypeParameterList, - recordDeclaration.ParameterList, - canGenerateReturns: false, - settings: settings); - } + public static SyntaxTriviaList Generate(RecordDeclarationSyntax recordDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (recordDeclaration is null) + throw new ArgumentNullException(nameof(recordDeclaration)); + + return Generate( + recordDeclaration.TypeParameterList, + recordDeclaration.ParameterList, + canGenerateReturns: false, + settings: settings); + } - public static SyntaxTriviaList Generate(StructDeclarationSyntax structDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (structDeclaration == null) - throw new ArgumentNullException(nameof(structDeclaration)); - - return Generate( - structDeclaration.TypeParameterList, - default(ParameterListSyntax), - canGenerateReturns: false, - settings: settings); - } + public static SyntaxTriviaList Generate(StructDeclarationSyntax structDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (structDeclaration is null) + throw new ArgumentNullException(nameof(structDeclaration)); + + return Generate( + structDeclaration.TypeParameterList, + default(ParameterListSyntax), + canGenerateReturns: false, + settings: settings); + } - public static SyntaxTriviaList Generate(InterfaceDeclarationSyntax interfaceDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (interfaceDeclaration == null) - throw new ArgumentNullException(nameof(interfaceDeclaration)); - - return Generate( - interfaceDeclaration.TypeParameterList, - default(ParameterListSyntax), - canGenerateReturns: false, - settings: settings); - } + public static SyntaxTriviaList Generate(InterfaceDeclarationSyntax interfaceDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (interfaceDeclaration is null) + throw new ArgumentNullException(nameof(interfaceDeclaration)); + + return Generate( + interfaceDeclaration.TypeParameterList, + default(ParameterListSyntax), + canGenerateReturns: false, + settings: settings); + } - public static SyntaxTriviaList Generate(EnumDeclarationSyntax enumDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (enumDeclaration == null) - throw new ArgumentNullException(nameof(enumDeclaration)); + public static SyntaxTriviaList Generate(EnumDeclarationSyntax enumDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (enumDeclaration is null) + throw new ArgumentNullException(nameof(enumDeclaration)); - return Generate(settings: settings); - } + return Generate(settings: settings); + } - public static SyntaxTriviaList Generate(DelegateDeclarationSyntax delegateDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (delegateDeclaration == null) - throw new ArgumentNullException(nameof(delegateDeclaration)); - - return Generate( - delegateDeclaration.TypeParameterList, - delegateDeclaration.ParameterList, - canGenerateReturns: false, - settings: settings); - } + public static SyntaxTriviaList Generate(DelegateDeclarationSyntax delegateDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (delegateDeclaration is null) + throw new ArgumentNullException(nameof(delegateDeclaration)); + + return Generate( + delegateDeclaration.TypeParameterList, + delegateDeclaration.ParameterList, + canGenerateReturns: false, + settings: settings); + } - public static SyntaxTriviaList Generate(EnumMemberDeclarationSyntax enumMemberDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (enumMemberDeclaration == null) - throw new ArgumentNullException(nameof(enumMemberDeclaration)); + public static SyntaxTriviaList Generate(EnumMemberDeclarationSyntax enumMemberDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (enumMemberDeclaration is null) + throw new ArgumentNullException(nameof(enumMemberDeclaration)); - return Generate(settings: settings); - } + return Generate(settings: settings); + } - public static SyntaxTriviaList Generate(FieldDeclarationSyntax fieldDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (fieldDeclaration == null) - throw new ArgumentNullException(nameof(fieldDeclaration)); + public static SyntaxTriviaList Generate(FieldDeclarationSyntax fieldDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (fieldDeclaration is null) + throw new ArgumentNullException(nameof(fieldDeclaration)); - return Generate(settings: settings); - } + return Generate(settings: settings); + } - public static SyntaxTriviaList Generate(EventFieldDeclarationSyntax eventFieldDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (eventFieldDeclaration == null) - throw new ArgumentNullException(nameof(eventFieldDeclaration)); + public static SyntaxTriviaList Generate(EventFieldDeclarationSyntax eventFieldDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (eventFieldDeclaration is null) + throw new ArgumentNullException(nameof(eventFieldDeclaration)); - return Generate(settings: settings); - } + return Generate(settings: settings); + } - public static SyntaxTriviaList Generate(MethodDeclarationSyntax methodDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (methodDeclaration == null) - throw new ArgumentNullException(nameof(methodDeclaration)); - - return Generate( - methodDeclaration.TypeParameterList, - methodDeclaration.ParameterList, - canGenerateReturns: !methodDeclaration.ReturnsVoid(), - settings: settings); - } + public static SyntaxTriviaList Generate(MethodDeclarationSyntax methodDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (methodDeclaration is null) + throw new ArgumentNullException(nameof(methodDeclaration)); + + return Generate( + methodDeclaration.TypeParameterList, + methodDeclaration.ParameterList, + canGenerateReturns: !methodDeclaration.ReturnsVoid(), + settings: settings); + } - public static SyntaxTriviaList Generate(OperatorDeclarationSyntax operatorDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (operatorDeclaration == null) - throw new ArgumentNullException(nameof(operatorDeclaration)); - - return Generate( - default(TypeParameterListSyntax), - operatorDeclaration.ParameterList, - canGenerateReturns: true, - settings: settings); - } + public static SyntaxTriviaList Generate(OperatorDeclarationSyntax operatorDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (operatorDeclaration is null) + throw new ArgumentNullException(nameof(operatorDeclaration)); + + return Generate( + default(TypeParameterListSyntax), + operatorDeclaration.ParameterList, + canGenerateReturns: true, + settings: settings); + } - public static SyntaxTriviaList Generate(ConversionOperatorDeclarationSyntax conversionOperatorDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (conversionOperatorDeclaration == null) - throw new ArgumentNullException(nameof(conversionOperatorDeclaration)); - - return Generate( - default(TypeParameterListSyntax), - conversionOperatorDeclaration.ParameterList, - canGenerateReturns: false, - settings: settings); - } + public static SyntaxTriviaList Generate(ConversionOperatorDeclarationSyntax conversionOperatorDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (conversionOperatorDeclaration is null) + throw new ArgumentNullException(nameof(conversionOperatorDeclaration)); + + return Generate( + default(TypeParameterListSyntax), + conversionOperatorDeclaration.ParameterList, + canGenerateReturns: false, + settings: settings); + } - public static SyntaxTriviaList Generate(ConstructorDeclarationSyntax constructorDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (constructorDeclaration == null) - throw new ArgumentNullException(nameof(constructorDeclaration)); - - return Generate( - default(TypeParameterListSyntax), - constructorDeclaration.ParameterList, - canGenerateReturns: false, - settings: settings); - } + public static SyntaxTriviaList Generate(ConstructorDeclarationSyntax constructorDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (constructorDeclaration is null) + throw new ArgumentNullException(nameof(constructorDeclaration)); + + return Generate( + default(TypeParameterListSyntax), + constructorDeclaration.ParameterList, + canGenerateReturns: false, + settings: settings); + } - public static SyntaxTriviaList Generate(DestructorDeclarationSyntax destructorDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (destructorDeclaration == null) - throw new ArgumentNullException(nameof(destructorDeclaration)); + public static SyntaxTriviaList Generate(DestructorDeclarationSyntax destructorDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (destructorDeclaration is null) + throw new ArgumentNullException(nameof(destructorDeclaration)); - return Generate(settings: settings); - } + return Generate(settings: settings); + } - public static SyntaxTriviaList Generate(PropertyDeclarationSyntax propertyDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (propertyDeclaration == null) - throw new ArgumentNullException(nameof(propertyDeclaration)); + public static SyntaxTriviaList Generate(PropertyDeclarationSyntax propertyDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (propertyDeclaration is null) + throw new ArgumentNullException(nameof(propertyDeclaration)); - return Generate(settings: settings); - } + return Generate(settings: settings); + } - public static SyntaxTriviaList Generate(EventDeclarationSyntax eventDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (eventDeclaration == null) - throw new ArgumentNullException(nameof(eventDeclaration)); + public static SyntaxTriviaList Generate(EventDeclarationSyntax eventDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (eventDeclaration is null) + throw new ArgumentNullException(nameof(eventDeclaration)); - return Generate(settings: settings); - } + return Generate(settings: settings); + } - public static SyntaxTriviaList Generate(IndexerDeclarationSyntax indexerDeclaration, DocumentationCommentGeneratorSettings settings = null) - { - if (indexerDeclaration == null) - throw new ArgumentNullException(nameof(indexerDeclaration)); - - return Generate( - default(TypeParameterListSyntax), - indexerDeclaration.ParameterList, - canGenerateReturns: true, - settings: settings); - } + public static SyntaxTriviaList Generate(IndexerDeclarationSyntax indexerDeclaration, DocumentationCommentGeneratorSettings settings = null) + { + if (indexerDeclaration is null) + throw new ArgumentNullException(nameof(indexerDeclaration)); + + return Generate( + default(TypeParameterListSyntax), + indexerDeclaration.ParameterList, + canGenerateReturns: true, + settings: settings); + } - private static SyntaxTriviaList Generate( - TypeParameterListSyntax typeParameterList, - BaseParameterListSyntax parameterList, - bool canGenerateReturns = false, - DocumentationCommentGeneratorSettings settings = null) - { - SeparatedSyntaxList typeParameters = typeParameterList?.Parameters ?? default; + private static SyntaxTriviaList Generate( + TypeParameterListSyntax typeParameterList, + BaseParameterListSyntax parameterList, + bool canGenerateReturns = false, + DocumentationCommentGeneratorSettings settings = null) + { + SeparatedSyntaxList typeParameters = typeParameterList?.Parameters ?? default; - SeparatedSyntaxList parameters = parameterList?.Parameters ?? default; + SeparatedSyntaxList parameters = parameterList?.Parameters ?? default; - return Generate(typeParameters, parameters, canGenerateReturns, settings); - } + return Generate(typeParameters, parameters, canGenerateReturns, settings); + } - private static SyntaxTriviaList Generate( - SeparatedSyntaxList typeParameters = default, - SeparatedSyntaxList parameters = default, - bool canGenerateReturns = false, - DocumentationCommentGeneratorSettings settings = null) - { - settings ??= DocumentationCommentGeneratorSettings.Default; + private static SyntaxTriviaList Generate( + SeparatedSyntaxList typeParameters = default, + SeparatedSyntaxList parameters = default, + bool canGenerateReturns = false, + DocumentationCommentGeneratorSettings settings = null) + { + settings ??= DocumentationCommentGeneratorSettings.Default; - ImmutableArray summary = settings.Summary; + ImmutableArray summary = settings.Summary; - StringBuilder sb = StringBuilderCache.GetInstance(); + StringBuilder sb = StringBuilderCache.GetInstance(); - sb.Append(settings.Indentation); - sb.Append("/// "); + sb.Append(settings.Indentation); + sb.Append("/// "); - if (settings.SingleLineSummary - && summary.Length <= 1) - { - if (summary.Length == 1) - sb.Append(summary[0]); + if (settings.SingleLineSummary + && summary.Length <= 1) + { + if (summary.Length == 1) + sb.Append(summary[0]); - sb.AppendLine(""); - } - else - { - sb.AppendLine(); + sb.AppendLine(""); + } + else + { + sb.AppendLine(); - if (summary.Any()) + if (summary.Any()) + { + foreach (string comment in summary) + { + sb.Append(settings.Indentation); + sb.Append("/// "); + sb.AppendLine(comment); + } + } + else + { + sb.Append(settings.Indentation); + sb.AppendLine("/// "); + } + + sb.Append(settings.Indentation); + sb.AppendLine("/// "); + } + + if (!settings.IsTagIgnored(WellKnownXmlTags.TypeParam)) { - foreach (string comment in summary) + foreach (TypeParameterSyntax typeParameter in typeParameters) { sb.Append(settings.Indentation); - sb.Append("/// "); - sb.AppendLine(comment); + sb.Append("/// "); } } - else + + if (!settings.IsTagIgnored(WellKnownXmlTags.Param)) + { + foreach (ParameterSyntax parameter in parameters) + { + sb.Append(settings.Indentation); + sb.Append("/// "); + } + } + + if (canGenerateReturns + && !settings.IsTagIgnored(WellKnownXmlTags.Returns)) { sb.Append(settings.Indentation); - sb.AppendLine("/// "); + sb.AppendLine("/// "); } - sb.Append(settings.Indentation); - sb.AppendLine("/// "); + return SyntaxFactory.ParseLeadingTrivia(StringBuilderCache.GetStringAndFree(sb)); } - if (!settings.IsTagIgnored(WellKnownXmlTags.TypeParam)) + internal static bool CanGenerateFromBase(SyntaxKind kind) { - foreach (TypeParameterSyntax typeParameter in typeParameters) + switch (kind) { - sb.Append(settings.Indentation); - sb.Append("/// "); + case SyntaxKind.MethodDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.IndexerDeclaration: + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.ConstructorDeclaration: + return true; + default: + return false; } } - if (!settings.IsTagIgnored(WellKnownXmlTags.Param)) + internal static DocumentationCommentData GenerateFromBase(MemberDeclarationSyntax memberDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) { - foreach (ParameterSyntax parameter in parameters) + switch (memberDeclaration.Kind()) { - sb.Append(settings.Indentation); - sb.Append("/// "); + case SyntaxKind.MethodDeclaration: + return GenerateFromBase((MethodDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); + case SyntaxKind.PropertyDeclaration: + return GenerateFromBase((PropertyDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); + case SyntaxKind.IndexerDeclaration: + return GenerateFromBase((IndexerDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); + case SyntaxKind.EventFieldDeclaration: + return GenerateFromBase((EventFieldDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); + case SyntaxKind.EventDeclaration: + return GenerateFromBase((EventDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); + case SyntaxKind.ConstructorDeclaration: + return GenerateFromBase((ConstructorDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); + default: + throw new ArgumentException("", nameof(memberDeclaration)); } } - if (canGenerateReturns - && !settings.IsTagIgnored(WellKnownXmlTags.Returns)) + internal static DocumentationCommentData GenerateFromBase(MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) { - sb.Append(settings.Indentation); - sb.AppendLine("/// "); - } + if (!methodDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) + && methodDeclaration.ExplicitInterfaceSpecifier is null + && !ContainingTypeHasBaseType(methodDeclaration)) + { + return default; + } - return SyntaxFactory.ParseLeadingTrivia(StringBuilderCache.GetStringAndFree(sb)); - } + IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); - internal static bool CanGenerateFromBase(SyntaxKind kind) - { - switch (kind) - { - case SyntaxKind.MethodDeclaration: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.IndexerDeclaration: - case SyntaxKind.EventFieldDeclaration: - case SyntaxKind.EventDeclaration: - case SyntaxKind.ConstructorDeclaration: - return true; - default: - return false; - } - } + if (methodSymbol?.IsErrorType() == false) + { + string xml = GenerateFromOverriddenMethods(methodSymbol, cancellationToken); - internal static DocumentationCommentData GenerateFromBase(MemberDeclarationSyntax memberDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) - { - switch (memberDeclaration.Kind()) - { - case SyntaxKind.MethodDeclaration: - return GenerateFromBase((MethodDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); - case SyntaxKind.PropertyDeclaration: - return GenerateFromBase((PropertyDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); - case SyntaxKind.IndexerDeclaration: - return GenerateFromBase((IndexerDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); - case SyntaxKind.EventFieldDeclaration: - return GenerateFromBase((EventFieldDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); - case SyntaxKind.EventDeclaration: - return GenerateFromBase((EventDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); - case SyntaxKind.ConstructorDeclaration: - return GenerateFromBase((ConstructorDeclarationSyntax)memberDeclaration, semanticModel, cancellationToken); - default: - throw new ArgumentException("", nameof(memberDeclaration)); - } - } + if (xml is not null) + return new DocumentationCommentData(xml, DocumentationCommentOrigin.BaseMember); + + xml = GenerateFromInterfaceMember(methodSymbol, cancellationToken); + + if (xml is not null) + return new DocumentationCommentData(xml, DocumentationCommentOrigin.InterfaceMember); + } - internal static DocumentationCommentData GenerateFromBase(MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) - { - if (!methodDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) - && methodDeclaration.ExplicitInterfaceSpecifier == null - && !ContainingTypeHasBaseType(methodDeclaration)) - { return default; } - IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); - - if (methodSymbol?.IsErrorType() == false) + internal static DocumentationCommentData GenerateFromBase(PropertyDeclarationSyntax propertyDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) { - string xml = GenerateFromOverriddenMethods(methodSymbol, cancellationToken); - - if (xml != null) - return new DocumentationCommentData(xml, DocumentationCommentOrigin.BaseMember); + if (!propertyDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) + && propertyDeclaration.ExplicitInterfaceSpecifier is null + && !ContainingTypeHasBaseType(propertyDeclaration)) + { + return default; + } - xml = GenerateFromInterfaceMember(methodSymbol, cancellationToken); + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); - if (xml != null) - return new DocumentationCommentData(xml, DocumentationCommentOrigin.InterfaceMember); + return GenerateFromBase(propertySymbol, cancellationToken); } - return default; - } - - internal static DocumentationCommentData GenerateFromBase(PropertyDeclarationSyntax propertyDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) - { - if (!propertyDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) - && propertyDeclaration.ExplicitInterfaceSpecifier == null - && !ContainingTypeHasBaseType(propertyDeclaration)) + internal static DocumentationCommentData GenerateFromBase(IndexerDeclarationSyntax indexerDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) { - return default; - } - - IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); + if (!indexerDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) + && indexerDeclaration.ExplicitInterfaceSpecifier is null + && !ContainingTypeHasBaseType(indexerDeclaration)) + { + return default; + } - return GenerateFromBase(propertySymbol, cancellationToken); - } + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(indexerDeclaration, cancellationToken); - internal static DocumentationCommentData GenerateFromBase(IndexerDeclarationSyntax indexerDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) - { - if (!indexerDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) - && indexerDeclaration.ExplicitInterfaceSpecifier == null - && !ContainingTypeHasBaseType(indexerDeclaration)) - { - return default; + return GenerateFromBase(propertySymbol, cancellationToken); } - IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(indexerDeclaration, cancellationToken); - - return GenerateFromBase(propertySymbol, cancellationToken); - } - - private static DocumentationCommentData GenerateFromBase(IPropertySymbol propertySymbol, CancellationToken cancellationToken) - { - if (propertySymbol?.IsErrorType() == false) + private static DocumentationCommentData GenerateFromBase(IPropertySymbol propertySymbol, CancellationToken cancellationToken) { - string xml = GenerateFromOverriddenProperties(propertySymbol, cancellationToken); - - if (xml != null) - return new DocumentationCommentData(xml, DocumentationCommentOrigin.BaseMember); + if (propertySymbol?.IsErrorType() == false) + { + string xml = GenerateFromOverriddenProperties(propertySymbol, cancellationToken); - xml = GenerateFromInterfaceMember(propertySymbol, cancellationToken); + if (xml is not null) + return new DocumentationCommentData(xml, DocumentationCommentOrigin.BaseMember); - if (xml != null) - return new DocumentationCommentData(xml, DocumentationCommentOrigin.InterfaceMember); - } + xml = GenerateFromInterfaceMember(propertySymbol, cancellationToken); - return default; - } + if (xml is not null) + return new DocumentationCommentData(xml, DocumentationCommentOrigin.InterfaceMember); + } - internal static DocumentationCommentData GenerateFromBase(EventDeclarationSyntax eventDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) - { - if (!eventDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) - && eventDeclaration.ExplicitInterfaceSpecifier == null - && !ContainingTypeHasBaseType(eventDeclaration)) - { return default; } - IEventSymbol eventSymbol = semanticModel.GetDeclaredSymbol(eventDeclaration, cancellationToken); - - return GenerateFromBase(eventSymbol, cancellationToken); - } - - internal static DocumentationCommentData GenerateFromBase(EventFieldDeclarationSyntax eventFieldDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) - { - if (!eventFieldDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) - && !ContainingTypeHasBaseType(eventFieldDeclaration)) + internal static DocumentationCommentData GenerateFromBase(EventDeclarationSyntax eventDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) { - return default; - } - - VariableDeclaratorSyntax variableDeclarator = eventFieldDeclaration.Declaration?.Variables.FirstOrDefault(); + if (!eventDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) + && eventDeclaration.ExplicitInterfaceSpecifier is null + && !ContainingTypeHasBaseType(eventDeclaration)) + { + return default; + } - if (variableDeclarator != null) - { - var eventSymbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken) as IEventSymbol; + IEventSymbol eventSymbol = semanticModel.GetDeclaredSymbol(eventDeclaration, cancellationToken); return GenerateFromBase(eventSymbol, cancellationToken); } - return default; - } - - private static DocumentationCommentData GenerateFromBase(IEventSymbol eventSymbol, CancellationToken cancellationToken) - { - if (eventSymbol?.IsErrorType() == false) + internal static DocumentationCommentData GenerateFromBase(EventFieldDeclarationSyntax eventFieldDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) { - string xml = GenerateFromOverriddenEvents(eventSymbol, cancellationToken); - - if (xml != null) - return new DocumentationCommentData(xml, DocumentationCommentOrigin.BaseMember); + if (!eventFieldDeclaration.Modifiers.Contains(SyntaxKind.OverrideKeyword) + && !ContainingTypeHasBaseType(eventFieldDeclaration)) + { + return default; + } - xml = GenerateFromInterfaceMember(eventSymbol, cancellationToken); + VariableDeclaratorSyntax variableDeclarator = eventFieldDeclaration.Declaration?.Variables.FirstOrDefault(); - if (xml != null) - return new DocumentationCommentData(xml, DocumentationCommentOrigin.InterfaceMember); - } + if (variableDeclarator is not null) + { + var eventSymbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken) as IEventSymbol; - return default; - } + return GenerateFromBase(eventSymbol, cancellationToken); + } - internal static DocumentationCommentData GenerateFromBase(ConstructorDeclarationSyntax constructorDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) - { - ConstructorInitializerSyntax initializer = constructorDeclaration.Initializer; + return default; + } - if (initializer?.Kind() == SyntaxKind.BaseConstructorInitializer) + private static DocumentationCommentData GenerateFromBase(IEventSymbol eventSymbol, CancellationToken cancellationToken) { - ISymbol baseConstructor = semanticModel.GetSymbol(initializer, cancellationToken); - - if (baseConstructor?.IsErrorType() == false) + if (eventSymbol?.IsErrorType() == false) { - string xml = GetDocumentationCommentXml(baseConstructor, cancellationToken); + string xml = GenerateFromOverriddenEvents(eventSymbol, cancellationToken); - if (xml != null) + if (xml is not null) return new DocumentationCommentData(xml, DocumentationCommentOrigin.BaseMember); + + xml = GenerateFromInterfaceMember(eventSymbol, cancellationToken); + + if (xml is not null) + return new DocumentationCommentData(xml, DocumentationCommentOrigin.InterfaceMember); } - } - return default; - } + return default; + } - private static string GenerateFromOverriddenMethods(IMethodSymbol methodSymbol, CancellationToken cancellationToken) - { - for (IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; overriddenMethod != null; overriddenMethod = overriddenMethod.OverriddenMethod) + internal static DocumentationCommentData GenerateFromBase(ConstructorDeclarationSyntax constructorDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken = default) { - string xml = GetDocumentationCommentXml(overriddenMethod, cancellationToken); + ConstructorInitializerSyntax initializer = constructorDeclaration.Initializer; - if (xml != null) - return xml; - } + if (initializer?.Kind() == SyntaxKind.BaseConstructorInitializer) + { + ISymbol baseConstructor = semanticModel.GetSymbol(initializer, cancellationToken); - return null; - } + if (baseConstructor?.IsErrorType() == false) + { + string xml = GetDocumentationCommentXml(baseConstructor, cancellationToken); - private static string GenerateFromOverriddenProperties(IPropertySymbol propertySymbol, CancellationToken cancellationToken) - { - for (IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; overriddenProperty != null; overriddenProperty = overriddenProperty.OverriddenProperty) - { - string xml = GetDocumentationCommentXml(overriddenProperty, cancellationToken); + if (xml is not null) + return new DocumentationCommentData(xml, DocumentationCommentOrigin.BaseMember); + } + } - if (xml != null) - return xml; + return default; } - return null; - } - - private static string GenerateFromOverriddenEvents(IEventSymbol eventSymbol, CancellationToken cancellationToken) - { - for (IEventSymbol overriddenEvent = eventSymbol.OverriddenEvent; overriddenEvent != null; overriddenEvent = overriddenEvent.OverriddenEvent) + private static string GenerateFromOverriddenMethods(IMethodSymbol methodSymbol, CancellationToken cancellationToken) { - string xml = GetDocumentationCommentXml(overriddenEvent, cancellationToken); + for (IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; overriddenMethod is not null; overriddenMethod = overriddenMethod.OverriddenMethod) + { + string xml = GetDocumentationCommentXml(overriddenMethod, cancellationToken); + + if (xml is not null) + return xml; + } - if (xml != null) - return xml; + return null; } - return null; - } + private static string GenerateFromOverriddenProperties(IPropertySymbol propertySymbol, CancellationToken cancellationToken) + { + for (IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; overriddenProperty is not null; overriddenProperty = overriddenProperty.OverriddenProperty) + { + string xml = GetDocumentationCommentXml(overriddenProperty, cancellationToken); - private static string GenerateFromInterfaceMember( - ISymbol memberSymbol, - CancellationToken cancellationToken) where TInterfaceSymbol : ISymbol - { - TInterfaceSymbol interfaceMember = memberSymbol.FindFirstImplementedInterfaceMember(); + if (xml is not null) + return xml; + } - if (!EqualityComparer.Default.Equals(interfaceMember, default)) - { - return GetDocumentationCommentXml(interfaceMember, cancellationToken); + return null; } - else + + private static string GenerateFromOverriddenEvents(IEventSymbol eventSymbol, CancellationToken cancellationToken) { + for (IEventSymbol overriddenEvent = eventSymbol.OverriddenEvent; overriddenEvent is not null; overriddenEvent = overriddenEvent.OverriddenEvent) + { + string xml = GetDocumentationCommentXml(overriddenEvent, cancellationToken); + + if (xml is not null) + return xml; + } + return null; } - } - private static string GetDocumentationCommentXml(ISymbol symbol, CancellationToken cancellationToken = default) - { - string xml = symbol.GetDocumentationCommentXml(cancellationToken: cancellationToken); + private static string GenerateFromInterfaceMember( + ISymbol memberSymbol, + CancellationToken cancellationToken) where TInterfaceSymbol : ISymbol + { + TInterfaceSymbol interfaceMember = memberSymbol.FindFirstImplementedInterfaceMember(); - if (xml == null) - return null; + if (!EqualityComparer.Default.Equals(interfaceMember, default)) + { + return GetDocumentationCommentXml(interfaceMember, cancellationToken); + } + else + { + return null; + } + } - using (var sr = new StringReader(xml)) + private static string GetDocumentationCommentXml(ISymbol symbol, CancellationToken cancellationToken = default) { - using (XmlReader reader = XmlReader.Create(sr, _xmlReaderSettings)) + string xml = symbol.GetDocumentationCommentXml(cancellationToken: cancellationToken); + + if (xml is null) + return null; + + using (var sr = new StringReader(xml)) { - if (reader.Read() - && reader.NodeType == XmlNodeType.Element) + using (XmlReader reader = XmlReader.Create(sr, _xmlReaderSettings)) { - switch (reader.Name) + if (reader.Read() + && reader.NodeType == XmlNodeType.Element) { - case "member": - case "doc": - { - try + switch (reader.Name) + { + case "member": + case "doc": { - return reader.ReadInnerXml(); + try + { + return reader.ReadInnerXml(); + } + catch (XmlException ex) + { + Debug.Fail(symbol.ToDisplayString() + "\r\n\r\n" + ex.Message + "\r\n\r\n" + xml); + return null; + } } - catch (XmlException ex) + default: { - Debug.Fail(symbol.ToDisplayString() + "\r\n\r\n" + ex.Message + "\r\n\r\n" + xml); + Debug.Fail(reader.Name); return null; } - } - default: - { - Debug.Fail(reader.Name); - return null; - } + } } } } + + return null; } - return null; - } + private static bool ContainingTypeHasBaseType(MemberDeclarationSyntax memberDeclaration) + { + SyntaxNode parent = memberDeclaration.Parent; - private static bool ContainingTypeHasBaseType(MemberDeclarationSyntax memberDeclaration) - { - SyntaxNode parent = memberDeclaration.Parent; + switch (parent.Kind()) + { + case SyntaxKind.ClassDeclaration: + return ((ClassDeclarationSyntax)parent).BaseList?.Types.Any() == true; + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((RecordDeclarationSyntax)parent).BaseList?.Types.Any() == true; + case SyntaxKind.StructDeclaration: + return ((StructDeclarationSyntax)parent).BaseList?.Types.Any() == true; + } - switch (parent.Kind()) - { - case SyntaxKind.ClassDeclaration: - return ((ClassDeclarationSyntax)parent).BaseList?.Types.Any() == true; - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return ((RecordDeclarationSyntax)parent).BaseList?.Types.Any() == true; - case SyntaxKind.StructDeclaration: - return ((StructDeclarationSyntax)parent).BaseList?.Types.Any() == true; + return false; } - - return false; } } diff --git a/src/CSharp/CSharp/Documentation/DocumentationCommentTriviaFactory.cs b/src/CSharp/CSharp/Documentation/DocumentationCommentTriviaFactory.cs index 705b28b070..6b5651e53b 100644 --- a/src/CSharp/CSharp/Documentation/DocumentationCommentTriviaFactory.cs +++ b/src/CSharp/CSharp/Documentation/DocumentationCommentTriviaFactory.cs @@ -11,79 +11,80 @@ using Roslynator.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Roslynator.CSharp.Documentation; - -[DebuggerDisplay("{DebuggerDisplay,nq}")] -internal static class DocumentationCommentTriviaFactory +namespace Roslynator.CSharp.Documentation { - private static readonly Regex _commentedEmptyLineRegex = new(@"^///\s*(\r?\n|$)", RegexOptions.Multiline); - - public static SyntaxTrivia Parse(string xml, SemanticModel semanticModel, int position) + [DebuggerDisplay("{DebuggerDisplay,nq}")] + internal static class DocumentationCommentTriviaFactory { - string triviaText = AddSlashes(xml.TrimEnd()); + private static readonly Regex _commentedEmptyLineRegex = new(@"^///\s*(\r?\n|$)", RegexOptions.Multiline); - SyntaxTrivia trivia = ParseLeadingTrivia(triviaText).Single(); + public static SyntaxTrivia Parse(string xml, SemanticModel semanticModel, int position) + { + string triviaText = AddSlashes(xml.TrimEnd()); - var commentTrivia = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); + SyntaxTrivia trivia = ParseLeadingTrivia(triviaText).Single(); - var rewriter = new DocumentationCommentTriviaRewriter(position, semanticModel); + var commentTrivia = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); - // Remove T: from cref attribute and replace `1 with {T} - commentTrivia = (DocumentationCommentTriviaSyntax)rewriter.VisitDocumentationCommentTrivia(commentTrivia); + var rewriter = new DocumentationCommentTriviaRewriter(position, semanticModel); - // Remove element - commentTrivia = RemoveFilterPriorityElement(commentTrivia); + // Remove T: from cref attribute and replace `1 with {T} + commentTrivia = (DocumentationCommentTriviaSyntax)rewriter.VisitDocumentationCommentTrivia(commentTrivia); - string text = commentTrivia.ToFullString(); + // Remove element + commentTrivia = RemoveFilterPriorityElement(commentTrivia); - // Remove /// from empty lines - text = _commentedEmptyLineRegex.Replace(text, ""); + string text = commentTrivia.ToFullString(); - return ParseLeadingTrivia(text).Single(); - } + // Remove /// from empty lines + text = _commentedEmptyLineRegex.Replace(text, ""); - private static DocumentationCommentTriviaSyntax RemoveFilterPriorityElement(DocumentationCommentTriviaSyntax commentTrivia) - { - SyntaxList content = commentTrivia.Content; + return ParseLeadingTrivia(text).Single(); + } - for (int i = content.Count - 1; i >= 0; i--) + private static DocumentationCommentTriviaSyntax RemoveFilterPriorityElement(DocumentationCommentTriviaSyntax commentTrivia) { - XmlNodeSyntax xmlNode = content[i]; + SyntaxList content = commentTrivia.Content; - if (xmlNode is XmlElementSyntax xmlElement - && xmlElement.IsLocalName("filterpriority", StringComparison.OrdinalIgnoreCase)) + for (int i = content.Count - 1; i >= 0; i--) { - content = content.RemoveAt(i); - } - } - - return commentTrivia.WithContent(content); - } + XmlNodeSyntax xmlNode = content[i]; - private static string AddSlashes(string innerXml) - { - StringBuilder sb = StringBuilderCache.GetInstance(); + if (xmlNode is XmlElementSyntax xmlElement + && xmlElement.IsLocalName("filterpriority", StringComparison.OrdinalIgnoreCase)) + { + content = content.RemoveAt(i); + } + } - string indent = null; + return commentTrivia.WithContent(content); + } - using (var sr = new StringReader(innerXml)) + private static string AddSlashes(string innerXml) { - string s; + StringBuilder sb = StringBuilderCache.GetInstance(); - while ((s = sr.ReadLine()) != null) + string indent = null; + + using (var sr = new StringReader(innerXml)) { - if (s.Length > 0) + string s; + + while ((s = sr.ReadLine()) is not null) { - indent ??= Regex.Match(s, "^ *").Value; + if (s.Length > 0) + { + indent ??= Regex.Match(s, "^ *").Value; - sb.Append("/// "); - s = Regex.Replace(s, $"^{indent}", ""); + sb.Append("/// "); + s = Regex.Replace(s, $"^{indent}", ""); - sb.AppendLine(s); + sb.AppendLine(s); + } } } - } - return StringBuilderCache.GetStringAndFree(sb); + return StringBuilderCache.GetStringAndFree(sb); + } } } diff --git a/src/CSharp/CSharp/Documentation/DocumentationCommentTriviaRewriter.cs b/src/CSharp/CSharp/Documentation/DocumentationCommentTriviaRewriter.cs index 1df21284fe..aee9ff1d50 100644 --- a/src/CSharp/CSharp/Documentation/DocumentationCommentTriviaRewriter.cs +++ b/src/CSharp/CSharp/Documentation/DocumentationCommentTriviaRewriter.cs @@ -5,66 +5,67 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp.Documentation; - -internal class DocumentationCommentTriviaRewriter : CSharpSyntaxRewriter +namespace Roslynator.CSharp.Documentation { - private readonly SemanticModel _semanticModel; - - private readonly int _position; - - public DocumentationCommentTriviaRewriter(int position, SemanticModel semanticModel) - : base(visitIntoStructuredTrivia: true) + internal class DocumentationCommentTriviaRewriter : CSharpSyntaxRewriter { - _semanticModel = semanticModel ?? throw new ArgumentNullException(nameof(semanticModel)); - _position = position; - } + private readonly SemanticModel _semanticModel; - public override SyntaxNode VisitXmlTextAttribute(XmlTextAttributeSyntax node) - { - if (node.Name?.IsLocalName("cref", StringComparison.OrdinalIgnoreCase) == true) + private readonly int _position; + + public DocumentationCommentTriviaRewriter(int position, SemanticModel semanticModel) + : base(visitIntoStructuredTrivia: true) { - SyntaxTokenList tokens = node.TextTokens; + _semanticModel = semanticModel ?? throw new ArgumentNullException(nameof(semanticModel)); + _position = position; + } - if (tokens.Count == 1) + public override SyntaxNode VisitXmlTextAttribute(XmlTextAttributeSyntax node) + { + if (node.Name?.IsLocalName("cref", StringComparison.OrdinalIgnoreCase) == true) { - SyntaxToken token = tokens[0]; + SyntaxTokenList tokens = node.TextTokens; + + if (tokens.Count == 1) + { + SyntaxToken token = tokens[0]; - string text = token.Text; + string text = token.Text; - string valueText = token.ValueText; + string valueText = token.ValueText; - if (text.StartsWith("T:", StringComparison.Ordinal)) - text = GetMinimalDisplayString(text.Substring(2)); + if (text.StartsWith("T:", StringComparison.Ordinal)) + text = GetMinimalDisplayString(text.Substring(2)); - if (valueText.StartsWith("T:", StringComparison.Ordinal)) - valueText = GetMinimalDisplayString(valueText.Substring(2)); + if (valueText.StartsWith("T:", StringComparison.Ordinal)) + valueText = GetMinimalDisplayString(valueText.Substring(2)); - SyntaxToken newToken = SyntaxFactory.Token( - default(SyntaxTriviaList), - SyntaxKind.XmlTextLiteralToken, - text, - valueText, - default(SyntaxTriviaList)); + SyntaxToken newToken = SyntaxFactory.Token( + default(SyntaxTriviaList), + SyntaxKind.XmlTextLiteralToken, + text, + valueText, + default(SyntaxTriviaList)); - return node.WithTextTokens(tokens.Replace(token, newToken)); + return node.WithTextTokens(tokens.Replace(token, newToken)); + } } + + return base.VisitXmlTextAttribute(node); } - return base.VisitXmlTextAttribute(node); - } + private string GetMinimalDisplayString(string metadataName) + { + INamedTypeSymbol typeSymbol = _semanticModel.GetTypeByMetadataName(metadataName); - private string GetMinimalDisplayString(string metadataName) - { - INamedTypeSymbol typeSymbol = _semanticModel.GetTypeByMetadataName(metadataName); + if (typeSymbol is not null) + { + return SymbolDisplay.ToMinimalDisplayString(typeSymbol, _semanticModel, _position, SymbolDisplayFormats.DisplayName) + .Replace('<', '{') + .Replace('>', '}'); + } - if (typeSymbol != null) - { - return SymbolDisplay.ToMinimalDisplayString(typeSymbol, _semanticModel, _position, SymbolDisplayFormats.DisplayName) - .Replace('<', '{') - .Replace('>', '}'); + return metadataName; } - - return metadataName; } } diff --git a/src/CSharp/CSharp/EnumMemberDeclarationNameComparer.cs b/src/CSharp/CSharp/EnumMemberDeclarationNameComparer.cs index 2b78f2e401..3ac8c56e8f 100644 --- a/src/CSharp/CSharp/EnumMemberDeclarationNameComparer.cs +++ b/src/CSharp/CSharp/EnumMemberDeclarationNameComparer.cs @@ -4,32 +4,33 @@ using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal sealed class EnumMemberDeclarationNameComparer : IComparer +namespace Roslynator.CSharp { - private EnumMemberDeclarationNameComparer() + internal sealed class EnumMemberDeclarationNameComparer : IComparer { - } + private EnumMemberDeclarationNameComparer() + { + } - public static readonly EnumMemberDeclarationNameComparer Instance = new(); + public static readonly EnumMemberDeclarationNameComparer Instance = new(); - public int Compare(EnumMemberDeclarationSyntax x, EnumMemberDeclarationSyntax y) - { - return CompareCore(x, y); - } + public int Compare(EnumMemberDeclarationSyntax x, EnumMemberDeclarationSyntax y) + { + return CompareCore(x, y); + } - private static int CompareCore(EnumMemberDeclarationSyntax x, EnumMemberDeclarationSyntax y) - { - if (object.ReferenceEquals(x, y)) - return 0; + private static int CompareCore(EnumMemberDeclarationSyntax x, EnumMemberDeclarationSyntax y) + { + if (object.ReferenceEquals(x, y)) + return 0; - if (x == null) - return -1; + if (x is null) + return -1; - if (y == null) - return 1; + if (y is null) + return 1; - return string.Compare(x.Identifier.ValueText, y.Identifier.ValueText, StringComparison.CurrentCulture); + return string.Compare(x.Identifier.ValueText, y.Identifier.ValueText, StringComparison.CurrentCulture); + } } } diff --git a/src/CSharp/CSharp/EnumMemberDeclarationValueComparer.cs b/src/CSharp/CSharp/EnumMemberDeclarationValueComparer.cs index 3b039122ca..62b2ae4849 100644 --- a/src/CSharp/CSharp/EnumMemberDeclarationValueComparer.cs +++ b/src/CSharp/CSharp/EnumMemberDeclarationValueComparer.cs @@ -7,84 +7,85 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal class EnumMemberDeclarationValueComparer : IComparer +namespace Roslynator.CSharp { - private readonly IComparer _valueComparer; - private readonly SemanticModel _semanticModel; - private readonly CancellationToken _cancellationToken; - - public EnumMemberDeclarationValueComparer(IComparer valueComparer, SemanticModel semanticModel, CancellationToken cancellationToken = default) + internal class EnumMemberDeclarationValueComparer : IComparer { - _valueComparer = valueComparer; - _semanticModel = semanticModel; - _cancellationToken = cancellationToken; - } + private readonly IComparer _valueComparer; + private readonly SemanticModel _semanticModel; + private readonly CancellationToken _cancellationToken; - public int Compare(EnumMemberDeclarationSyntax x, EnumMemberDeclarationSyntax y) - { - if (object.ReferenceEquals(x, y)) - return 0; + public EnumMemberDeclarationValueComparer(IComparer valueComparer, SemanticModel semanticModel, CancellationToken cancellationToken = default) + { + _valueComparer = valueComparer; + _semanticModel = semanticModel; + _cancellationToken = cancellationToken; + } - if (x == null) - return -1; + public int Compare(EnumMemberDeclarationSyntax x, EnumMemberDeclarationSyntax y) + { + if (object.ReferenceEquals(x, y)) + return 0; - if (y == null) - return 1; + if (x is null) + return -1; - return Compare( - _semanticModel.GetDeclaredSymbol(x, _cancellationToken), - _semanticModel.GetDeclaredSymbol(y, _cancellationToken), - _valueComparer); - } + if (y is null) + return 1; - private static int Compare(IFieldSymbol fieldSymbol1, IFieldSymbol fieldSymbol2, IComparer comparer) - { - if (fieldSymbol1?.HasConstantValue == true - && fieldSymbol2?.HasConstantValue == true) - { - return comparer.Compare(fieldSymbol1.ConstantValue, fieldSymbol2.ConstantValue); + return Compare( + _semanticModel.GetDeclaredSymbol(x, _cancellationToken), + _semanticModel.GetDeclaredSymbol(y, _cancellationToken), + _valueComparer); } - else + + private static int Compare(IFieldSymbol fieldSymbol1, IFieldSymbol fieldSymbol2, IComparer comparer) { - return 0; + if (fieldSymbol1?.HasConstantValue == true + && fieldSymbol2?.HasConstantValue == true) + { + return comparer.Compare(fieldSymbol1.ConstantValue, fieldSymbol2.ConstantValue); + } + else + { + return 0; + } } - } - public static bool IsSorted( - IEnumerable enumMembers, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (enumMembers == null) - throw new ArgumentNullException(nameof(enumMembers)); + public static bool IsSorted( + IEnumerable enumMembers, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (enumMembers is null) + throw new ArgumentNullException(nameof(enumMembers)); - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - using (IEnumerator en = enumMembers.GetEnumerator()) - { - if (en.MoveNext()) + using (IEnumerator en = enumMembers.GetEnumerator()) { - IFieldSymbol fieldSymbol1 = semanticModel.GetDeclaredSymbol(en.Current, cancellationToken); + if (en.MoveNext()) + { + IFieldSymbol fieldSymbol1 = semanticModel.GetDeclaredSymbol(en.Current, cancellationToken); - SpecialType enumSpecialType = fieldSymbol1.ContainingType.EnumUnderlyingType.SpecialType; + SpecialType enumSpecialType = fieldSymbol1.ContainingType.EnumUnderlyingType.SpecialType; - IComparer comparer = EnumValueComparer.GetInstance(enumSpecialType); + IComparer comparer = EnumValueComparer.GetInstance(enumSpecialType); - while (en.MoveNext()) - { - IFieldSymbol fieldSymbol2 = semanticModel.GetDeclaredSymbol(en.Current, cancellationToken); + while (en.MoveNext()) + { + IFieldSymbol fieldSymbol2 = semanticModel.GetDeclaredSymbol(en.Current, cancellationToken); - if (Compare(fieldSymbol1, fieldSymbol2, comparer) > 0) - return false; + if (Compare(fieldSymbol1, fieldSymbol2, comparer) > 0) + return false; - fieldSymbol1 = fieldSymbol2; + fieldSymbol1 = fieldSymbol2; + } } } - } - return true; + return true; + } } } diff --git a/src/CSharp/CSharp/ExpressionChain.Reversed.cs b/src/CSharp/CSharp/ExpressionChain.Reversed.cs index becb88f6b5..67d8cc12b4 100644 --- a/src/CSharp/CSharp/ExpressionChain.Reversed.cs +++ b/src/CSharp/CSharp/ExpressionChain.Reversed.cs @@ -10,293 +10,294 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -namespace Roslynator.CSharp; - -public readonly partial struct ExpressionChain +namespace Roslynator.CSharp { - /// - /// Enables to enumerate expressions of in a reversed order. - /// - [SuppressMessage("Usage", "RCS1223:Mark publicly visible type with DebuggerDisplay attribute.")] - public readonly struct Reversed : IEquatable, IEnumerable + public readonly partial struct ExpressionChain { - private readonly ExpressionChain _chain; - - public Reversed(in ExpressionChain chain) + /// + /// Enables to enumerate expressions of in a reversed order. + /// + [SuppressMessage("Usage", "RCS1223:Mark publicly visible type with DebuggerDisplay attribute.")] + public readonly struct Reversed : IEquatable, IEnumerable { - _chain = chain; - } + private readonly ExpressionChain _chain; - internal bool IsStringConcatenation( - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - if (!_chain.BinaryExpression.IsKind(SyntaxKind.AddExpression)) - return false; + public Reversed(in ExpressionChain chain) + { + _chain = chain; + } - Enumerator en = GetEnumerator(); + internal bool IsStringConcatenation( + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (!_chain.BinaryExpression.IsKind(SyntaxKind.AddExpression)) + return false; - if (!en.MoveNext()) - return false; + Enumerator en = GetEnumerator(); - var binaryExpression = (BinaryExpressionSyntax)en.Current.Parent; + if (!en.MoveNext()) + return false; - if (!en.MoveNext()) - return false; + var binaryExpression = (BinaryExpressionSyntax)en.Current.Parent; - while (true) - { - if (!CSharpUtility.IsStringConcatenation(binaryExpression, semanticModel, cancellationToken)) + if (!en.MoveNext()) return false; - ExpressionSyntax prev = en.Current; - - if (en.MoveNext()) + while (true) { - binaryExpression = (BinaryExpressionSyntax)prev.Parent; + if (!CSharpUtility.IsStringConcatenation(binaryExpression, semanticModel, cancellationToken)) + return false; + + ExpressionSyntax prev = en.Current; + + if (en.MoveNext()) + { + binaryExpression = (BinaryExpressionSyntax)prev.Parent; + } + else + { + break; + } } - else - { - break; - } - } - - return true; - } - public Enumerator GetEnumerator() - { - return new Enumerator(_chain); - } - - IEnumerator IEnumerable.GetEnumerator() - { - if (_chain.BinaryExpression == null) - return Empty.Enumerator(); + return true; + } - return new EnumeratorImpl(_chain); - } + public Enumerator GetEnumerator() + { + return new Enumerator(_chain); + } - IEnumerator IEnumerable.GetEnumerator() - { - if (_chain.BinaryExpression == null) - return Empty.Enumerator(); + IEnumerator IEnumerable.GetEnumerator() + { + if (_chain.BinaryExpression is null) + return Empty.Enumerator(); - return new EnumeratorImpl(_chain); - } + return new EnumeratorImpl(_chain); + } - public override string ToString() - { - return _chain.ToString(); - } + IEnumerator IEnumerable.GetEnumerator() + { + if (_chain.BinaryExpression is null) + return Empty.Enumerator(); - public override bool Equals(object obj) - { - return obj is Reversed other && Equals(other); - } + return new EnumeratorImpl(_chain); + } - public bool Equals(Reversed other) - { - return _chain.Equals(other._chain); - } + public override string ToString() + { + return _chain.ToString(); + } - public override int GetHashCode() - { - return _chain.GetHashCode(); - } + public override bool Equals(object obj) + { + return obj is Reversed other && Equals(other); + } - public static bool operator ==(in Reversed reversed1, in Reversed reversed2) - { - return reversed1.Equals(reversed2); - } + public bool Equals(Reversed other) + { + return _chain.Equals(other._chain); + } - public static bool operator !=(in Reversed reversed1, in Reversed reversed2) - { - return !(reversed1 == reversed2); - } + public override int GetHashCode() + { + return _chain.GetHashCode(); + } - [SuppressMessage("Usage", "RCS1223:Mark publicly visible type with DebuggerDisplay attribute.")] - public struct Enumerator - { - private readonly ExpressionChain _chain; - private ExpressionSyntax _current; - private State _state; + public static bool operator ==(in Reversed reversed1, in Reversed reversed2) + { + return reversed1.Equals(reversed2); + } - internal Enumerator(in ExpressionChain chain) + public static bool operator !=(in Reversed reversed1, in Reversed reversed2) { - _chain = chain; - _current = null; - _state = State.Start; + return !(reversed1 == reversed2); } - public bool MoveNext() + [SuppressMessage("Usage", "RCS1223:Mark publicly visible type with DebuggerDisplay attribute.")] + public struct Enumerator { - switch (_state) + private readonly ExpressionChain _chain; + private ExpressionSyntax _current; + private State _state; + + internal Enumerator(in ExpressionChain chain) { - case State.Start: - { - if (_chain.BinaryExpression == null) - return false; + _chain = chain; + _current = null; + _state = State.Start; + } - if (_chain.Span == null) + public bool MoveNext() + { + switch (_state) + { + case State.Start: { - _current = _chain.BinaryExpression.Right; - _state = State.Right; - return true; - } + if (_chain.BinaryExpression is null) + return false; - ExpressionSyntax right = _chain.BinaryExpression.Right; + if (_chain.Span is null) + { + _current = _chain.BinaryExpression.Right; + _state = State.Right; + return true; + } - TextSpan span = _chain.Span.Value; + ExpressionSyntax right = _chain.BinaryExpression.Right; - if (IsInSpan(span, right.Span)) - { - _current = right; - _state = State.Right; - return true; - } + TextSpan span = _chain.Span.Value; - BinaryExpressionSyntax binaryExpression = _chain.BinaryExpression; + if (IsInSpan(span, right.Span)) + { + _current = right; + _state = State.Right; + return true; + } - ExpressionSyntax left; + BinaryExpressionSyntax binaryExpression = _chain.BinaryExpression; - while (true) - { - left = binaryExpression.Left; + ExpressionSyntax left; - if (left.RawKind == binaryExpression.RawKind) + while (true) { - binaryExpression = (BinaryExpressionSyntax)left; - right = binaryExpression.Right; + left = binaryExpression.Left; - if (IsInSpan(span, right.Span)) + if (left.RawKind == binaryExpression.RawKind) { - _current = right; - _state = State.Right; + 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; return true; } - } - else if (IsInSpan(span, left.Span)) - { - _current = left; - _state = State.Left; - return true; - } - else - { - _state = State.Left; - return false; + else + { + _state = State.Left; + return false; + } } } - } - case State.Right: - { - var binaryExpression = (BinaryExpressionSyntax)_current.Parent; + case State.Right: + { + var binaryExpression = (BinaryExpressionSyntax)_current.Parent; - ExpressionSyntax left = binaryExpression.Left; + ExpressionSyntax left = binaryExpression.Left; - if (_chain.Span == null) - { - if (left.RawKind == binaryExpression.RawKind) + if (_chain.Span is null) { - binaryExpression = (BinaryExpressionSyntax)left; + if (left.RawKind == binaryExpression.RawKind) + { + binaryExpression = (BinaryExpressionSyntax)left; - _current = binaryExpression.Right; - _state = State.Right; + _current = binaryExpression.Right; + _state = State.Right; + } + else + { + _current = left; + _state = State.Left; + } + + return true; } else { - _current = left; - _state = State.Left; - } + TextSpan span = _chain.Span.Value; - return true; - } - else - { - TextSpan span = _chain.Span.Value; + if (left.RawKind == binaryExpression.RawKind) + { + binaryExpression = (BinaryExpressionSyntax)left; - if (left.RawKind == binaryExpression.RawKind) - { - binaryExpression = (BinaryExpressionSyntax)left; + ExpressionSyntax right = binaryExpression.Right; - ExpressionSyntax right = binaryExpression.Right; + if (IsInSpan(span, right.Span)) + { + _current = right; + _state = State.Right; + return true; + } + } - if (IsInSpan(span, right.Span)) + if (IsInSpan(span, left.Span)) { - _current = right; - _state = State.Right; + _current = left; + _state = State.Left; return true; } - } - - if (IsInSpan(span, left.Span)) - { - _current = left; - _state = State.Left; - return true; - } - else - { - _current = null; - _state = State.Left; - return false; + else + { + _current = null; + _state = State.Left; + return false; + } } } - } - case State.Left: - { - return false; - } - default: - { - throw new InvalidOperationException(); - } + case State.Left: + { + return false; + } + default: + { + throw new InvalidOperationException(); + } + } } - } - public ExpressionSyntax Current - { - get { return _current ?? throw new InvalidOperationException(); } - } + public ExpressionSyntax Current + { + get { return _current ?? throw new InvalidOperationException(); } + } - public void Reset() - { - _current = null; - _state = State.Start; - } + public void Reset() + { + _current = null; + _state = State.Start; + } - public override bool Equals(object obj) => throw new NotSupportedException(); + public override bool Equals(object obj) => throw new NotSupportedException(); - public override int GetHashCode() => throw new NotSupportedException(); + public override int GetHashCode() => throw new NotSupportedException(); - private enum State - { - Start = 0, - Left = 1, - Right = 2, + private enum State + { + Start = 0, + Left = 1, + Right = 2, + } } - } - private class EnumeratorImpl : IEnumerator - { - private Enumerator _en; - - internal EnumeratorImpl(in ExpressionChain chain) + private class EnumeratorImpl : IEnumerator { - _en = new Enumerator(chain); - } + private Enumerator _en; - public ExpressionSyntax Current => _en.Current; + internal EnumeratorImpl(in ExpressionChain chain) + { + _en = new Enumerator(chain); + } - object IEnumerator.Current => _en.Current; + public ExpressionSyntax Current => _en.Current; - public bool MoveNext() => _en.MoveNext(); + object IEnumerator.Current => _en.Current; - public void Reset() => _en.Reset(); + public bool MoveNext() => _en.MoveNext(); - public void Dispose() - { + public void Reset() => _en.Reset(); + + public void Dispose() + { + } } } } diff --git a/src/CSharp/CSharp/ExpressionChain.cs b/src/CSharp/CSharp/ExpressionChain.cs index 8aeced5c71..db0e74b1e7 100644 --- a/src/CSharp/CSharp/ExpressionChain.cs +++ b/src/CSharp/CSharp/ExpressionChain.cs @@ -8,210 +8,242 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -namespace Roslynator.CSharp; - -/// -/// Enables to enumerate expressions of a binary expression and expressions of nested binary expressions of the same kind as parent binary expression. -/// -[DebuggerDisplay("{DebuggerDisplay,nq}")] -public readonly partial struct ExpressionChain : IEquatable, IEnumerable +namespace Roslynator.CSharp { - internal ExpressionChain(BinaryExpressionSyntax binaryExpression, TextSpan? span = null) - { - BinaryExpression = binaryExpression; - Span = span; - } - /// - /// The binary expression. + /// Enables to enumerate expressions of a binary expression and expressions of nested binary expressions of the same kind as parent binary expression. /// - public BinaryExpressionSyntax BinaryExpression { get; } - - /// - /// The span that represents selected expressions. - /// - public TextSpan? Span { get; } - - /// - /// The absolute span of expressions in characters, not including its leading and trailing trivia. - /// - internal TextSpan ExpressionsSpan + [DebuggerDisplay("{DebuggerDisplay,nq}")] + public readonly partial struct ExpressionChain : IEquatable, IEnumerable { - get + internal ExpressionChain(BinaryExpressionSyntax binaryExpression, TextSpan? span = null) { - if (Span == null) - return BinaryExpression?.Span ?? default; + BinaryExpression = binaryExpression; + Span = span; + } - Reversed.Enumerator en = Reverse().GetEnumerator(); + /// + /// The binary expression. + /// + public BinaryExpressionSyntax BinaryExpression { get; } - if (en.MoveNext()) + /// + /// The span that represents selected expressions. + /// + public TextSpan? Span { get; } + + /// + /// The absolute span of expressions in characters, not including its leading and trailing trivia. + /// + internal TextSpan ExpressionsSpan + { + get { - int end = en.Current.Span.End; + if (Span is null) + return BinaryExpression?.Span ?? default; - int start = en.Current.SpanStart; + Reversed.Enumerator en = Reverse().GetEnumerator(); - while (en.MoveNext()) - start = en.Current.SpanStart; + if (en.MoveNext()) + { + int end = en.Current.Span.End; - return TextSpan.FromBounds(start, end); - } + int start = en.Current.SpanStart; - return default; - } - } + while (en.MoveNext()) + start = en.Current.SpanStart; - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay - { - get { return BinaryExpression?.ToString(ExpressionsSpan) ?? "Uninitialized"; } - } + return TextSpan.FromBounds(start, end); + } - private static bool IsInSpan(TextSpan self, TextSpan span) - { - return self.OverlapsWith(span) - || (span.Length == 0 && self.IntersectsWith(span)); - } + return default; + } + } - /// - /// Returns a chain which contains all expressions of in reversed order. - /// - public Reversed Reverse() - { - return new Reversed(this); - } + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay + { + get { return BinaryExpression?.ToString(ExpressionsSpan) ?? "Uninitialized"; } + } - internal ExpressionSyntax First() - { - Enumerator en = GetEnumerator(); + private static bool IsInSpan(TextSpan self, TextSpan span) + { + return self.OverlapsWith(span) + || (span.Length == 0 && self.IntersectsWith(span)); + } - return (en.MoveNext()) ? en.Current : throw new InvalidOperationException(); - } + /// + /// Returns a chain which contains all expressions of in reversed order. + /// + public Reversed Reverse() + { + return new Reversed(this); + } - /// - /// Gets the enumerator for the expressions. - /// - public Enumerator GetEnumerator() - { - return new Enumerator(this); - } + internal ExpressionSyntax First() + { + Enumerator en = GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() - { - if (BinaryExpression != null) - return new EnumeratorImpl(this); + return (en.MoveNext()) ? en.Current : throw new InvalidOperationException(); + } - return Empty.Enumerator(); - } + /// + /// Gets the enumerator for the expressions. + /// + public Enumerator GetEnumerator() + { + return new Enumerator(this); + } - IEnumerator IEnumerable.GetEnumerator() - { - if (BinaryExpression != null) - return new EnumeratorImpl(this); + IEnumerator IEnumerable.GetEnumerator() + { + if (BinaryExpression is not null) + return new EnumeratorImpl(this); - return Empty.Enumerator(); - } + return Empty.Enumerator(); + } - /// - /// Returns the string representation of the expressions, not including its leading and trailing trivia. - /// - public override string ToString() - { - return BinaryExpression?.ToString(ExpressionsSpan) ?? ""; - } + IEnumerator IEnumerable.GetEnumerator() + { + if (BinaryExpression is not null) + return new EnumeratorImpl(this); - /// - /// Determines whether this instance and a specified object are equal. - /// - /// The object to compare with the current instance. - /// true if and this instance are the same type and represent the same value; otherwise, false. - public override bool Equals(object obj) - { - return obj is ExpressionChain other && Equals(other); - } + return Empty.Enumerator(); + } - /// - /// Determines whether this instance is equal to another object of the same type. - /// - /// An object to compare with this object. - /// true if the current object is equal to the parameter; otherwise, false. - public bool Equals(ExpressionChain other) - { - return EqualityComparer.Default.Equals(BinaryExpression, other.BinaryExpression); - } + /// + /// Returns the string representation of the expressions, not including its leading and trailing trivia. + /// + public override string ToString() + { + return BinaryExpression?.ToString(ExpressionsSpan) ?? ""; + } - /// - /// Returns the hash code for this instance. - /// - /// A 32-bit signed integer that is the hash code for this instance. - public override int GetHashCode() - { - return EqualityComparer.Default.GetHashCode(BinaryExpression); - } + /// + /// Determines whether this instance and a specified object are equal. + /// + /// The object to compare with the current instance. + /// true if and this instance are the same type and represent the same value; otherwise, false. + public override bool Equals(object obj) + { + return obj is ExpressionChain other && Equals(other); + } - public static bool operator ==(in ExpressionChain info1, in ExpressionChain info2) - { - return info1.Equals(info2); - } + /// + /// Determines whether this instance is equal to another object of the same type. + /// + /// An object to compare with this object. + /// true if the current object is equal to the parameter; otherwise, false. + public bool Equals(ExpressionChain other) + { + return EqualityComparer.Default.Equals(BinaryExpression, other.BinaryExpression); + } - public static bool operator !=(in ExpressionChain info1, in ExpressionChain info2) - { - return !(info1 == info2); - } + /// + /// Returns the hash code for this instance. + /// + /// A 32-bit signed integer that is the hash code for this instance. + public override int GetHashCode() + { + return EqualityComparer.Default.GetHashCode(BinaryExpression); + } - [SuppressMessage("Usage", "RCS1223:Use DebuggerDisplay attribute for publicly visible type.")] - public struct Enumerator - { - private readonly ExpressionChain _chain; - private ExpressionSyntax _last; - private ExpressionSyntax _current; - private State _state; + public static bool operator ==(in ExpressionChain info1, in ExpressionChain info2) + { + return info1.Equals(info2); + } - internal Enumerator(in ExpressionChain chain) + public static bool operator !=(in ExpressionChain info1, in ExpressionChain info2) { - _chain = chain; - _last = null; - _current = null; - _state = State.Start; + return !(info1 == info2); } - public bool MoveNext() + [SuppressMessage("Usage", "RCS1223:Use DebuggerDisplay attribute for publicly visible type.")] + public struct Enumerator { - switch (_state) + private readonly ExpressionChain _chain; + private ExpressionSyntax _last; + private ExpressionSyntax _current; + private State _state; + + internal Enumerator(in ExpressionChain chain) { - case State.Start: - { - if (_chain.BinaryExpression == null) - return false; + _chain = chain; + _last = null; + _current = null; + _state = State.Start; + } - BinaryExpressionSyntax binaryExpression = _chain.BinaryExpression; + public bool MoveNext() + { + switch (_state) + { + case State.Start: + { + if (_chain.BinaryExpression is null) + return false; - ExpressionSyntax left = binaryExpression.Left; + BinaryExpressionSyntax binaryExpression = _chain.BinaryExpression; - if (_chain.Span == null) - { - _last = binaryExpression.Right; + ExpressionSyntax left = binaryExpression.Left; - while (left.RawKind == binaryExpression.RawKind) + if (_chain.Span is null) { - binaryExpression = (BinaryExpressionSyntax)left; - left = binaryExpression.Left; + _last = binaryExpression.Right; + + while (left.RawKind == binaryExpression.RawKind) + { + binaryExpression = (BinaryExpressionSyntax)left; + left = binaryExpression.Left; + } + + _current = left; + _state = State.Left; + return true; } - _current = left; - _state = State.Left; - return true; - } + ExpressionSyntax right = binaryExpression.Right; - ExpressionSyntax right = binaryExpression.Right; + TextSpan span = _chain.Span.Value; - TextSpan span = _chain.Span.Value; + if (IsInSpan(span, right.Span)) + { + _last = right; + } + 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; + } + } + } + + ExpressionSyntax first = _last; - if (IsInSpan(span, right.Span)) - { - _last = right; - } - else - { while (true) { left = binaryExpression.Left; @@ -223,145 +255,114 @@ public bool MoveNext() if (IsInSpan(span, right.Span)) { - _last = right; + first = right; + } + else + { break; } } - else if (IsInSpan(span, left.Span)) - { - _last = left; - _current = _last; - _state = State.Left; - return true; - } else { - _state = State.End; - return false; + if (IsInSpan(span, left.Span)) + { + _current = left; + _state = State.Left; + return true; + } + + break; } } - } - ExpressionSyntax first = _last; + _current = first; + _state = State.Right; - while (true) + return true; + } + case State.Right: { - left = binaryExpression.Left; - - if (left.RawKind == binaryExpression.RawKind) + if (_current == _last) { - binaryExpression = (BinaryExpressionSyntax)left; - right = binaryExpression.Right; - - if (IsInSpan(span, right.Span)) - { - first = right; - } - else - { - break; - } + _current = null; + _last = null; + _state = State.End; + return false; } - else - { - if (IsInSpan(span, left.Span)) - { - _current = left; - _state = State.Left; - return true; - } - break; - } + _current = ((BinaryExpressionSyntax)_current.Parent.Parent).Right; + return true; } + case State.Left: + { + if (_current == _last) + { + _current = null; + _last = null; + _state = State.End; + return false; + } - _current = first; - _state = State.Right; - - return true; - } - case State.Right: - { - if (_current == _last) + _current = ((BinaryExpressionSyntax)_current.Parent).Right; + _state = State.Right; + return true; + } + case State.End: { - _current = null; - _last = null; - _state = State.End; return false; } - - _current = ((BinaryExpressionSyntax)_current.Parent.Parent).Right; - return true; - } - case State.Left: - { - if (_current == _last) + default: { - _current = null; - _last = null; - _state = State.End; - return false; + throw new InvalidOperationException(); } - - _current = ((BinaryExpressionSyntax)_current.Parent).Right; - _state = State.Right; - return true; - } - case State.End: - { - return false; - } - default: - { - throw new InvalidOperationException(); - } + } } - } - public ExpressionSyntax Current - { - get { return _current ?? throw new InvalidOperationException(); } - } + public ExpressionSyntax Current + { + get { return _current ?? throw new InvalidOperationException(); } + } - public void Reset() - { - _current = null; - _last = null; - _state = State.Start; - } + public void Reset() + { + _current = null; + _last = null; + _state = State.Start; + } - public override bool Equals(object obj) => throw new NotSupportedException(); + public override bool Equals(object obj) => throw new NotSupportedException(); - public override int GetHashCode() => throw new NotSupportedException(); + public override int GetHashCode() => throw new NotSupportedException(); - private enum State - { - Start = 0, - Left = 1, - Right = 2, - End = 3, + private enum State + { + Start = 0, + Left = 1, + Right = 2, + End = 3, + } } - } - - private class EnumeratorImpl : IEnumerator - { - private Enumerator _en; - internal EnumeratorImpl(in ExpressionChain chain) + private class EnumeratorImpl : IEnumerator { - _en = new Enumerator(chain); - } + private Enumerator _en; + + internal EnumeratorImpl(in ExpressionChain chain) + { + _en = new Enumerator(chain); + } - public ExpressionSyntax Current => _en.Current; + public ExpressionSyntax Current => _en.Current; - object IEnumerator.Current => _en.Current; + object IEnumerator.Current => _en.Current; - public bool MoveNext() => _en.MoveNext(); + public bool MoveNext() => _en.MoveNext(); - public void Reset() => _en.Reset(); + public void Reset() => _en.Reset(); - public void Dispose() - { + public void Dispose() + { + } } } } diff --git a/src/CSharp/CSharp/Extensions/CSharpExtensions.cs b/src/CSharp/CSharp/Extensions/CSharpExtensions.cs index 6e8f93dced..b4b7b9a89b 100644 --- a/src/CSharp/CSharp/Extensions/CSharpExtensions.cs +++ b/src/CSharp/CSharp/Extensions/CSharpExtensions.cs @@ -7,459 +7,363 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -/// -/// A set of extension methods for a . -/// -public static class CSharpExtensions +namespace Roslynator.CSharp { /// - /// Returns a method symbol for the specified local function syntax. - /// - /// - /// - /// - internal static IMethodSymbol GetDeclaredSymbol( - this SemanticModel semanticModel, - LocalFunctionStatementSyntax localFunction, - CancellationToken cancellationToken = default) - { - return (IMethodSymbol)ModelExtensions.GetDeclaredSymbol(semanticModel, localFunction, cancellationToken); - } - - /// - /// Returns what symbol, if any, the specified attribute syntax bound to. - /// - /// - /// - /// - public static ISymbol GetSymbol( - this SemanticModel semanticModel, - AttributeSyntax attribute, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetSymbolInfo(semanticModel, attribute, cancellationToken) - .Symbol; - } - - /// - /// Returns what symbol, if any, the specified constructor initializer syntax bound to. - /// - /// - /// - /// - public static ISymbol GetSymbol( - this SemanticModel semanticModel, - ConstructorInitializerSyntax constructorInitializer, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetSymbolInfo(semanticModel, constructorInitializer, cancellationToken) - .Symbol; - } - - /// - /// Returns what symbol, if any, the specified cref syntax bound to. - /// - /// - /// - /// - public static ISymbol GetSymbol( - this SemanticModel semanticModel, - CrefSyntax cref, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetSymbolInfo(semanticModel, cref, cancellationToken) - .Symbol; - } - - /// - /// Returns what symbol, if any, the specified expression syntax bound to. - /// - /// - /// - /// - public static ISymbol GetSymbol( - this SemanticModel semanticModel, - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetSymbolInfo(semanticModel, expression, cancellationToken) - .Symbol; - } - - /// - /// Returns what symbol, if any, the specified ordering syntax bound to. - /// - /// - /// - /// - public static ISymbol GetSymbol( - this SemanticModel semanticModel, - OrderingSyntax ordering, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetSymbolInfo(semanticModel, ordering, cancellationToken) - .Symbol; - } - - /// - /// Returns what symbol, if any, the specified select or group clause bound to. - /// - /// - /// - /// - public static ISymbol GetSymbol( - this SemanticModel semanticModel, - SelectOrGroupClauseSyntax selectOrGroupClause, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetSymbolInfo(semanticModel, selectOrGroupClause, cancellationToken) - .Symbol; - } - - /// - /// Returns type information about an attribute syntax. - /// - /// - /// - /// - public static ITypeSymbol GetTypeSymbol( - this SemanticModel semanticModel, - AttributeSyntax attribute, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetTypeInfo(semanticModel, attribute, cancellationToken) - .Type; - } - - /// - /// Returns type information about a constructor initializer syntax. - /// - /// - /// - /// - public static ITypeSymbol GetTypeSymbol( - this SemanticModel semanticModel, - ConstructorInitializerSyntax constructorInitializer, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetTypeInfo(semanticModel, constructorInitializer, cancellationToken) - .Type; - } - - /// - /// Returns type information about an expression syntax. - /// - /// - /// - /// - public static ITypeSymbol GetTypeSymbol( - this SemanticModel semanticModel, - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetTypeInfo(semanticModel, expression, cancellationToken) - .Type; - } - - /// - /// Returns type information about a select or group clause. + /// A set of extension methods for a . /// - /// - /// - /// - public static ITypeSymbol GetTypeSymbol( - this SemanticModel semanticModel, - SelectOrGroupClauseSyntax selectOrGroupClause, - CancellationToken cancellationToken = default) + public static class CSharpExtensions { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions - .GetTypeInfo(semanticModel, selectOrGroupClause, cancellationToken) - .Type; - } + /// + /// Returns a method symbol for the specified local function syntax. + /// + /// + /// + /// + internal static IMethodSymbol GetDeclaredSymbol( + this SemanticModel semanticModel, + LocalFunctionStatementSyntax localFunction, + CancellationToken cancellationToken = default) + { + return (IMethodSymbol)ModelExtensions.GetDeclaredSymbol(semanticModel, localFunction, cancellationToken); + } - internal static bool IsExplicitConversion( - this SemanticModel semanticModel, - ExpressionSyntax expression, - ITypeSymbol destinationType, - bool isExplicitInSource = false) - { - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + /// + /// Returns what symbol, if any, the specified attribute syntax bound to. + /// + /// + /// + /// + public static ISymbol GetSymbol( + this SemanticModel semanticModel, + AttributeSyntax attribute, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetSymbolInfo(semanticModel, attribute, cancellationToken) + .Symbol; + } - if (expression == null) - throw new ArgumentNullException(nameof(expression)); + /// + /// Returns what symbol, if any, the specified constructor initializer syntax bound to. + /// + /// + /// + /// + public static ISymbol GetSymbol( + this SemanticModel semanticModel, + ConstructorInitializerSyntax constructorInitializer, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetSymbolInfo(semanticModel, constructorInitializer, cancellationToken) + .Symbol; + } - if (destinationType == null) - throw new ArgumentNullException(nameof(destinationType)); + /// + /// Returns what symbol, if any, the specified cref syntax bound to. + /// + /// + /// + /// + public static ISymbol GetSymbol( + this SemanticModel semanticModel, + CrefSyntax cref, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetSymbolInfo(semanticModel, cref, cancellationToken) + .Symbol; + } - if (destinationType.Kind == SymbolKind.ErrorType) - return false; + /// + /// Returns what symbol, if any, the specified expression syntax bound to. + /// + /// + /// + /// + public static ISymbol GetSymbol( + this SemanticModel semanticModel, + ExpressionSyntax expression, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetSymbolInfo(semanticModel, expression, cancellationToken) + .Symbol; + } - if (destinationType.SpecialType == SpecialType.System_Void) - return false; + /// + /// Returns what symbol, if any, the specified ordering syntax bound to. + /// + /// + /// + /// + public static ISymbol GetSymbol( + this SemanticModel semanticModel, + OrderingSyntax ordering, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetSymbolInfo(semanticModel, ordering, cancellationToken) + .Symbol; + } - Conversion conversion = semanticModel.ClassifyConversion( - expression, - destinationType, - isExplicitInSource); + /// + /// Returns what symbol, if any, the specified select or group clause bound to. + /// + /// + /// + /// + public static ISymbol GetSymbol( + this SemanticModel semanticModel, + SelectOrGroupClauseSyntax selectOrGroupClause, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetSymbolInfo(semanticModel, selectOrGroupClause, cancellationToken) + .Symbol; + } - return conversion.IsExplicit; - } + /// + /// Returns type information about an attribute syntax. + /// + /// + /// + /// + public static ITypeSymbol GetTypeSymbol( + this SemanticModel semanticModel, + AttributeSyntax attribute, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetTypeInfo(semanticModel, attribute, cancellationToken) + .Type; + } - internal static bool IsImplicitConversion( - this SemanticModel semanticModel, - ExpressionSyntax expression, - ITypeSymbol destinationType, - bool isExplicitInSource = false) - { - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + /// + /// Returns type information about a constructor initializer syntax. + /// + /// + /// + /// + public static ITypeSymbol GetTypeSymbol( + this SemanticModel semanticModel, + ConstructorInitializerSyntax constructorInitializer, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetTypeInfo(semanticModel, constructorInitializer, cancellationToken) + .Type; + } - if (expression == null) - throw new ArgumentNullException(nameof(expression)); + /// + /// Returns type information about an expression syntax. + /// + /// + /// + /// + public static ITypeSymbol GetTypeSymbol( + this SemanticModel semanticModel, + ExpressionSyntax expression, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetTypeInfo(semanticModel, expression, cancellationToken) + .Type; + } - if (destinationType == null) - throw new ArgumentNullException(nameof(destinationType)); + /// + /// Returns type information about a select or group clause. + /// + /// + /// + /// + public static ITypeSymbol GetTypeSymbol( + this SemanticModel semanticModel, + SelectOrGroupClauseSyntax selectOrGroupClause, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions + .GetTypeInfo(semanticModel, selectOrGroupClause, cancellationToken) + .Type; + } - if (destinationType.Kind == SymbolKind.ErrorType) - return false; + internal static bool IsExplicitConversion( + this SemanticModel semanticModel, + ExpressionSyntax expression, + ITypeSymbol destinationType, + bool isExplicitInSource = false) + { + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - if (destinationType.SpecialType == SpecialType.System_Void) - return false; + if (expression is null) + throw new ArgumentNullException(nameof(expression)); - Conversion conversion = semanticModel.ClassifyConversion( - expression, - destinationType, - isExplicitInSource); + if (destinationType is null) + throw new ArgumentNullException(nameof(destinationType)); - return conversion.IsImplicit; - } + if (destinationType.Kind == SymbolKind.ErrorType) + return false; - /// - /// Determines a parameter symbol that matches to the specified argument. - /// Returns null if no matching parameter is found. - /// - /// - /// - /// - /// - /// - public static IParameterSymbol DetermineParameter( - this SemanticModel semanticModel, - ArgumentSyntax argument, - bool allowParams = false, - bool allowCandidate = false, - CancellationToken cancellationToken = default) - { - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + if (destinationType.SpecialType == SpecialType.System_Void) + return false; - if (argument == null) - throw new ArgumentNullException(nameof(argument)); + Conversion conversion = semanticModel.ClassifyConversion( + expression, + destinationType, + isExplicitInSource); - return DetermineParameterHelper.DetermineParameter(argument, semanticModel, allowParams, allowCandidate, cancellationToken); - } + return conversion.IsExplicit; + } - /// - /// Determines a parameter symbol that matches to the specified attribute argument. - /// Returns null if not matching parameter is found. - /// - /// - /// - /// - /// - /// - public static IParameterSymbol DetermineParameter( - this SemanticModel semanticModel, - AttributeArgumentSyntax attributeArgument, - bool allowParams = false, - bool allowCandidate = false, - CancellationToken cancellationToken = default) - { - if (attributeArgument == null) - throw new ArgumentNullException(nameof(attributeArgument)); + internal static bool IsImplicitConversion( + this SemanticModel semanticModel, + ExpressionSyntax expression, + ITypeSymbol destinationType, + bool isExplicitInSource = false) + { + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + if (expression is null) + throw new ArgumentNullException(nameof(expression)); - return DetermineParameterHelper.DetermineParameter(attributeArgument, semanticModel, allowParams, allowCandidate, cancellationToken); - } + if (destinationType is null) + throw new ArgumentNullException(nameof(destinationType)); - /// - /// Returns true if the specified expression represents default value of the specified type. - /// - /// - /// - /// - /// - public static bool IsDefaultValue( - this SemanticModel semanticModel, - ITypeSymbol typeSymbol, - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + if (destinationType.Kind == SymbolKind.ErrorType) + return false; - if (typeSymbol == null) - throw new ArgumentNullException(nameof(typeSymbol)); + if (destinationType.SpecialType == SpecialType.System_Void) + return false; - if (expression == null) - throw new ArgumentNullException(nameof(expression)); + Conversion conversion = semanticModel.ClassifyConversion( + expression, + destinationType, + isExplicitInSource); - if (typeSymbol.Kind == SymbolKind.ErrorType) - return false; + return conversion.IsImplicit; + } - switch (expression.WalkDownParentheses().Kind()) + /// + /// Determines a parameter symbol that matches to the specified argument. + /// Returns null if no matching parameter is found. + /// + /// + /// + /// + /// + /// + public static IParameterSymbol DetermineParameter( + this SemanticModel semanticModel, + ArgumentSyntax argument, + bool allowParams = false, + bool allowCandidate = false, + CancellationToken cancellationToken = default) { - case SyntaxKind.NullLiteralExpression: - { - return typeSymbol.IsReferenceTypeOrNullableType(); - } - case SyntaxKind.DefaultLiteralExpression: - { - return true; - } - case SyntaxKind.DefaultExpression: - { - var defaultExpression = (DefaultExpressionSyntax)expression; + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - TypeSyntax type = defaultExpression.Type; + if (argument is null) + throw new ArgumentNullException(nameof(argument)); - return type != null - && SymbolEqualityComparer.Default.Equals(typeSymbol, semanticModel.GetTypeSymbol(type, cancellationToken)); - } + return DetermineParameterHelper.DetermineParameter(argument, semanticModel, allowParams, allowCandidate, cancellationToken); } - switch (typeSymbol.SpecialType) + /// + /// Determines a parameter symbol that matches to the specified attribute argument. + /// Returns null if not matching parameter is found. + /// + /// + /// + /// + /// + /// + public static IParameterSymbol DetermineParameter( + this SemanticModel semanticModel, + AttributeArgumentSyntax attributeArgument, + bool allowParams = false, + bool allowCandidate = false, + CancellationToken cancellationToken = default) { - case SpecialType.System_Void: - { - return false; - } - case SpecialType.System_Boolean: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + if (attributeArgument is null) + throw new ArgumentNullException(nameof(attributeArgument)); - return optional.HasValue - && optional.Value is bool value - && !value; - } - case SpecialType.System_Char: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - 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 DetermineParameterHelper.DetermineParameter(attributeArgument, semanticModel, allowParams, allowCandidate, cancellationToken); + } - return optional.HasValue - && optional.Value is short value - && value == 0; - } - case SpecialType.System_UInt16: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + /// + /// Returns true if the specified expression represents default value of the specified type. + /// + /// + /// + /// + /// + public static bool IsDefaultValue( + this SemanticModel semanticModel, + ITypeSymbol typeSymbol, + ExpressionSyntax expression, + CancellationToken cancellationToken = default) + { + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - return optional.HasValue - && optional.Value is ushort value - && value == 0; - } - case SpecialType.System_Int32: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + if (typeSymbol is null) + throw new ArgumentNullException(nameof(typeSymbol)); - return optional.HasValue - && optional.Value is int value - && value == 0; - } - case SpecialType.System_UInt32: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + if (expression is null) + throw new ArgumentNullException(nameof(expression)); - return optional.HasValue - && optional.Value is uint value - && value == 0; - } - case SpecialType.System_Int64: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + if (typeSymbol.Kind == SymbolKind.ErrorType) + return false; - return optional.HasValue - && optional.Value is long value - && value == 0; - } - case SpecialType.System_UInt64: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + switch (expression.WalkDownParentheses().Kind()) + { + case SyntaxKind.NullLiteralExpression: + { + return typeSymbol.IsReferenceTypeOrNullableType(); + } + case SyntaxKind.DefaultLiteralExpression: + { + return true; + } + case SyntaxKind.DefaultExpression: + { + var defaultExpression = (DefaultExpressionSyntax)expression; - return optional.HasValue - && optional.Value is ulong value - && value == 0; - } - case SpecialType.System_Decimal: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + TypeSyntax type = defaultExpression.Type; - 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 type is not null + && SymbolEqualityComparer.Default.Equals(typeSymbol, semanticModel.GetTypeSymbol(type, cancellationToken)); + } + } - return optional.HasValue - && optional.Value is double value - && value == 0; - } - } + switch (typeSymbol.SpecialType) + { + case SpecialType.System_Void: + { + return false; + } + case SpecialType.System_Boolean: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - if (typeSymbol.TypeKind == TypeKind.Enum) - { - var enumSymbol = (INamedTypeSymbol)typeSymbol; + return optional.HasValue + && optional.Value is bool value + && !value; + } + case SpecialType.System_Char: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - switch (enumSymbol.EnumUnderlyingType.SpecialType) - { + return optional.HasValue + && optional.Value is char value + && value == '\0'; + } case SpecialType.System_SByte: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -524,112 +428,209 @@ public static class CSharpExtensions && 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()); + + return false; } - Debug.Fail(enumSymbol.EnumUnderlyingType.SpecialType.ToString()); + if (typeSymbol.IsReferenceTypeOrNullableType()) + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + if (optional.HasValue) + return optional.Value is null; + } return false; } - if (typeSymbol.IsReferenceTypeOrNullableType()) + /// + /// Returns what extension method symbol, if any, the specified expression syntax bound to. + /// + /// + /// + /// + public static ExtensionMethodSymbolInfo GetExtensionMethodInfo( + this SemanticModel semanticModel, + ExpressionSyntax expression, + CancellationToken cancellationToken = default) { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + if (GetSymbol(semanticModel, expression, cancellationToken) is IMethodSymbol methodSymbol + && methodSymbol.IsExtensionMethod) + { + IMethodSymbol reducedFrom = methodSymbol.ReducedFrom; - if (optional.HasValue) - return optional.Value == null; - } + if (reducedFrom is not null) + return new ExtensionMethodSymbolInfo(reducedFrom, methodSymbol); - return false; - } + return new ExtensionMethodSymbolInfo(methodSymbol, null); + } - /// - /// Returns what extension method symbol, if any, the specified expression syntax bound to. - /// - /// - /// - /// - public static ExtensionMethodSymbolInfo GetExtensionMethodInfo( - this SemanticModel semanticModel, - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - if (GetSymbol(semanticModel, expression, cancellationToken) is IMethodSymbol methodSymbol - && methodSymbol.IsExtensionMethod) + return default; + } + + /// + /// Returns what extension method symbol, if any, the specified expression syntax bound to. + /// + /// + /// + /// + public static ExtensionMethodSymbolInfo GetReducedExtensionMethodInfo( + this SemanticModel semanticModel, + ExpressionSyntax expression, + CancellationToken cancellationToken = default) { - IMethodSymbol reducedFrom = methodSymbol.ReducedFrom; + if (GetSymbol(semanticModel, expression, cancellationToken) is IMethodSymbol methodSymbol + && methodSymbol.IsExtensionMethod) + { + IMethodSymbol reducedFrom = methodSymbol.ReducedFrom; - if (reducedFrom != null) - return new ExtensionMethodSymbolInfo(reducedFrom, methodSymbol); + if (reducedFrom is not null) + return new ExtensionMethodSymbolInfo(reducedFrom, methodSymbol); + } - return new ExtensionMethodSymbolInfo(methodSymbol, null); + return default; } - return default; - } - - /// - /// Returns what extension method symbol, if any, the specified expression syntax bound to. - /// - /// - /// - /// - public static ExtensionMethodSymbolInfo GetReducedExtensionMethodInfo( - this SemanticModel semanticModel, - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - if (GetSymbol(semanticModel, expression, cancellationToken) is IMethodSymbol methodSymbol - && methodSymbol.IsExtensionMethod) + /// + /// Returns method symbol, if any, the specified expression syntax bound to. + /// + /// + /// + /// + public static IMethodSymbol GetMethodSymbol( + this SemanticModel semanticModel, + ExpressionSyntax expression, + CancellationToken cancellationToken = default) { - IMethodSymbol reducedFrom = methodSymbol.ReducedFrom; - - if (reducedFrom != null) - return new ExtensionMethodSymbolInfo(reducedFrom, methodSymbol); + return GetSymbol(semanticModel, expression, cancellationToken) as IMethodSymbol; } - return default; - } - - /// - /// Returns method symbol, if any, the specified expression syntax bound to. - /// - /// - /// - /// - public static IMethodSymbol GetMethodSymbol( - this SemanticModel semanticModel, - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - return GetSymbol(semanticModel, expression, cancellationToken) as IMethodSymbol; - } - - internal static MethodDeclarationSyntax GetOtherPart( - this SemanticModel semanticModel, - MethodDeclarationSyntax methodDeclaration, - CancellationToken cancellationToken = default) - { - IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); + internal static MethodDeclarationSyntax GetOtherPart( + this SemanticModel semanticModel, + MethodDeclarationSyntax methodDeclaration, + CancellationToken cancellationToken = default) + { + IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); - IMethodSymbol otherSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol.PartialImplementationPart; + IMethodSymbol otherSymbol = methodSymbol.PartialDefinitionPart ?? methodSymbol.PartialImplementationPart; - if (otherSymbol != null) - return (MethodDeclarationSyntax)otherSymbol.GetSyntax(cancellationToken); + if (otherSymbol is not null) + return (MethodDeclarationSyntax)otherSymbol.GetSyntax(cancellationToken); - return null; - } + return null; + } - /// - /// Returns true if the specified node has a constant value. - /// - /// - /// - /// - public static bool HasConstantValue( - this SemanticModel semanticModel, - ExpressionSyntax expression, - CancellationToken cancellationToken = default) - { - return Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetConstantValue(semanticModel, expression, cancellationToken).HasValue; + /// + /// Returns true if the specified node has a constant value. + /// + /// + /// + /// + public static bool HasConstantValue( + this SemanticModel semanticModel, + ExpressionSyntax expression, + CancellationToken cancellationToken = default) + { + return Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetConstantValue(semanticModel, expression, cancellationToken).HasValue; + } } } diff --git a/src/CSharp/CSharp/Extensions/SymbolExtensions.cs b/src/CSharp/CSharp/Extensions/SymbolExtensions.cs index a87b80c49c..affaf41f20 100644 --- a/src/CSharp/CSharp/Extensions/SymbolExtensions.cs +++ b/src/CSharp/CSharp/Extensions/SymbolExtensions.cs @@ -9,343 +9,344 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp; - -/// -/// A set of static methods for and derived types. -/// -public static class SymbolExtensions +namespace Roslynator.CSharp { - #region INamedTypeSymbol - internal static string ToDisplayString(this INamedTypeSymbol typeSymbol, SymbolDisplayFormat format, SymbolDisplayTypeDeclarationOptions typeDeclarationOptions) - { - return typeSymbol.ToDisplayParts(format, typeDeclarationOptions).ToDisplayString(); - } - - internal static ImmutableArray ToDisplayParts(this INamedTypeSymbol typeSymbol, SymbolDisplayFormat format, SymbolDisplayTypeDeclarationOptions typeDeclarationOptions) + /// + /// A set of static methods for and derived types. + /// + public static class SymbolExtensions { - if (typeDeclarationOptions == SymbolDisplayTypeDeclarationOptions.None) - return typeSymbol.ToDisplayParts(format); - - ImmutableArray parts = typeSymbol.ToDisplayParts(format); - - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(parts.Length); - - if ((typeDeclarationOptions & SymbolDisplayTypeDeclarationOptions.IncludeAccessibility) != 0) + #region INamedTypeSymbol + internal static string ToDisplayString(this INamedTypeSymbol typeSymbol, SymbolDisplayFormat format, SymbolDisplayTypeDeclarationOptions typeDeclarationOptions) { - switch (typeSymbol.DeclaredAccessibility) - { - case Accessibility.Public: - { - AddKeyword(SyntaxKind.PublicKeyword); - break; - } - case Accessibility.ProtectedOrInternal: - { - AddKeyword(SyntaxKind.ProtectedKeyword); - AddKeyword(SyntaxKind.InternalKeyword); - break; - } - case Accessibility.Internal: - { - AddKeyword(SyntaxKind.InternalKeyword); - break; - } - case Accessibility.Protected: - { - AddKeyword(SyntaxKind.ProtectedKeyword); - break; - } - case Accessibility.ProtectedAndInternal: - { - AddKeyword(SyntaxKind.PrivateKeyword); - AddKeyword(SyntaxKind.ProtectedKeyword); - break; - } - case Accessibility.Private: - { - AddKeyword(SyntaxKind.PrivateKeyword); - break; - } - default: - { - throw new InvalidOperationException(); - } - } + return typeSymbol.ToDisplayParts(format, typeDeclarationOptions).ToDisplayString(); } - if ((typeDeclarationOptions & SymbolDisplayTypeDeclarationOptions.IncludeModifiers) != 0) + internal static ImmutableArray ToDisplayParts(this INamedTypeSymbol typeSymbol, SymbolDisplayFormat format, SymbolDisplayTypeDeclarationOptions typeDeclarationOptions) { - if (typeSymbol.IsStatic) - AddKeyword(SyntaxKind.StaticKeyword); + if (typeDeclarationOptions == SymbolDisplayTypeDeclarationOptions.None) + return typeSymbol.ToDisplayParts(format); + + ImmutableArray parts = typeSymbol.ToDisplayParts(format); - if (typeSymbol.IsSealed - && !typeSymbol.TypeKind.Is(TypeKind.Struct, TypeKind.Enum, TypeKind.Delegate)) + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(parts.Length); + + if ((typeDeclarationOptions & SymbolDisplayTypeDeclarationOptions.IncludeAccessibility) != 0) { - AddKeyword(SyntaxKind.SealedKeyword); + switch (typeSymbol.DeclaredAccessibility) + { + case Accessibility.Public: + { + AddKeyword(SyntaxKind.PublicKeyword); + break; + } + case Accessibility.ProtectedOrInternal: + { + AddKeyword(SyntaxKind.ProtectedKeyword); + AddKeyword(SyntaxKind.InternalKeyword); + break; + } + case Accessibility.Internal: + { + AddKeyword(SyntaxKind.InternalKeyword); + break; + } + case Accessibility.Protected: + { + AddKeyword(SyntaxKind.ProtectedKeyword); + break; + } + case Accessibility.ProtectedAndInternal: + { + AddKeyword(SyntaxKind.PrivateKeyword); + AddKeyword(SyntaxKind.ProtectedKeyword); + break; + } + case Accessibility.Private: + { + AddKeyword(SyntaxKind.PrivateKeyword); + break; + } + default: + { + throw new InvalidOperationException(); + } + } } - if (typeSymbol.IsAbstract - && typeSymbol.TypeKind != TypeKind.Interface) + if ((typeDeclarationOptions & SymbolDisplayTypeDeclarationOptions.IncludeModifiers) != 0) { - AddKeyword(SyntaxKind.AbstractKeyword); - } - } + if (typeSymbol.IsStatic) + AddKeyword(SyntaxKind.StaticKeyword); - builder.AddRange(parts); + if (typeSymbol.IsSealed + && !typeSymbol.TypeKind.Is(TypeKind.Struct, TypeKind.Enum, TypeKind.Delegate)) + { + AddKeyword(SyntaxKind.SealedKeyword); + } - return builder.ToImmutableArray(); + if (typeSymbol.IsAbstract + && typeSymbol.TypeKind != TypeKind.Interface) + { + AddKeyword(SyntaxKind.AbstractKeyword); + } + } - void AddKeyword(SyntaxKind kind) - { - builder.Add(SymbolDisplayPartFactory.Keyword(SyntaxFacts.GetText(kind))); - AddSpace(); - } + builder.AddRange(parts); - void AddSpace() - { - builder.Add(SymbolDisplayPartFactory.Space()); - } - } - #endregion INamedTypeSymbol + return builder.ToImmutableArray(); - #region INamespaceOrTypeSymbol - /// - /// Creates a new based on the specified namespace or type symbol. - /// - /// - /// - public static TypeSyntax ToTypeSyntax(this INamespaceOrTypeSymbol namespaceOrTypeSymbol, SymbolDisplayFormat format = null) - { - if (namespaceOrTypeSymbol == null) - throw new ArgumentNullException(nameof(namespaceOrTypeSymbol)); + void AddKeyword(SyntaxKind kind) + { + builder.Add(SymbolDisplayPartFactory.Keyword(SyntaxFacts.GetText(kind))); + AddSpace(); + } - if (namespaceOrTypeSymbol.IsType) - { - return ToTypeSyntax((ITypeSymbol)namespaceOrTypeSymbol, format); + void AddSpace() + { + builder.Add(SymbolDisplayPartFactory.Space()); + } } - else + #endregion INamedTypeSymbol + + #region INamespaceOrTypeSymbol + /// + /// Creates a new based on the specified namespace or type symbol. + /// + /// + /// + public static TypeSyntax ToTypeSyntax(this INamespaceOrTypeSymbol namespaceOrTypeSymbol, SymbolDisplayFormat format = null) { - return ToTypeSyntax((INamespaceSymbol)namespaceOrTypeSymbol, format); + if (namespaceOrTypeSymbol is null) + throw new ArgumentNullException(nameof(namespaceOrTypeSymbol)); + + if (namespaceOrTypeSymbol.IsType) + { + return ToTypeSyntax((ITypeSymbol)namespaceOrTypeSymbol, format); + } + else + { + return ToTypeSyntax((INamespaceSymbol)namespaceOrTypeSymbol, format); + } } - } - /// - /// Creates a new based on the specified namespace or type symbol - /// - /// - /// - /// - /// - public static TypeSyntax ToMinimalTypeSyntax(this INamespaceOrTypeSymbol namespaceOrTypeSymbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) - { - if (namespaceOrTypeSymbol == null) - throw new ArgumentNullException(nameof(namespaceOrTypeSymbol)); + /// + /// Creates a new based on the specified namespace or type symbol + /// + /// + /// + /// + /// + public static TypeSyntax ToMinimalTypeSyntax(this INamespaceOrTypeSymbol namespaceOrTypeSymbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) + { + if (namespaceOrTypeSymbol is null) + throw new ArgumentNullException(nameof(namespaceOrTypeSymbol)); - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - if (namespaceOrTypeSymbol.IsType) - { - return ToMinimalTypeSyntax((ITypeSymbol)namespaceOrTypeSymbol, semanticModel, position, format); + if (namespaceOrTypeSymbol.IsType) + { + return ToMinimalTypeSyntax((ITypeSymbol)namespaceOrTypeSymbol, semanticModel, position, format); + } + else + { + return ToMinimalTypeSyntax((INamespaceSymbol)namespaceOrTypeSymbol, semanticModel, position, format); + } } - else + #endregion INamespaceOrTypeSymbol + + #region INamespaceSymbol + /// + /// Creates a new based on the specified namespace symbol. + /// + /// + /// + public static TypeSyntax ToTypeSyntax(this INamespaceSymbol namespaceSymbol, SymbolDisplayFormat format = null) { - return ToMinimalTypeSyntax((INamespaceSymbol)namespaceOrTypeSymbol, semanticModel, position, format); - } - } - #endregion INamespaceOrTypeSymbol + if (namespaceSymbol is null) + throw new ArgumentNullException(nameof(namespaceSymbol)); - #region INamespaceSymbol - /// - /// Creates a new based on the specified namespace symbol. - /// - /// - /// - public static TypeSyntax ToTypeSyntax(this INamespaceSymbol namespaceSymbol, SymbolDisplayFormat format = null) - { - if (namespaceSymbol == null) - throw new ArgumentNullException(nameof(namespaceSymbol)); - - ThrowIfExplicitDeclarationIsNotSupported(namespaceSymbol); + ThrowIfExplicitDeclarationIsNotSupported(namespaceSymbol); - return ParseTypeName(namespaceSymbol.ToDisplayString(format ?? SymbolDisplayFormats.FullName)); - } + return ParseTypeName(namespaceSymbol.ToDisplayString(format ?? SymbolDisplayFormats.FullName)); + } - /// - /// Creates a new based on the specified namespace symbol. - /// - /// - /// - /// - /// - public static TypeSyntax ToMinimalTypeSyntax(this INamespaceSymbol namespaceSymbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) - { - if (namespaceSymbol == null) - throw new ArgumentNullException(nameof(namespaceSymbol)); + /// + /// Creates a new based on the specified namespace symbol. + /// + /// + /// + /// + /// + public static TypeSyntax ToMinimalTypeSyntax(this INamespaceSymbol namespaceSymbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) + { + if (namespaceSymbol is null) + throw new ArgumentNullException(nameof(namespaceSymbol)); - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - ThrowIfExplicitDeclarationIsNotSupported(namespaceSymbol); + ThrowIfExplicitDeclarationIsNotSupported(namespaceSymbol); - return ParseTypeName(namespaceSymbol.ToMinimalDisplayString(semanticModel, position, format ?? SymbolDisplayFormats.FullName)); - } + return ParseTypeName(namespaceSymbol.ToMinimalDisplayString(semanticModel, position, format ?? SymbolDisplayFormats.FullName)); + } - private static void ThrowIfExplicitDeclarationIsNotSupported(INamespaceSymbol namespaceSymbol) - { - if (namespaceSymbol.IsGlobalNamespace) - throw new ArgumentException("Global namespace does not support explicit declaration.", nameof(namespaceSymbol)); - } - #endregion INamespaceSymbol + private static void ThrowIfExplicitDeclarationIsNotSupported(INamespaceSymbol namespaceSymbol) + { + if (namespaceSymbol.IsGlobalNamespace) + throw new ArgumentException("Global namespace does not support explicit declaration.", nameof(namespaceSymbol)); + } + #endregion INamespaceSymbol - #region IParameterSymbol - internal static ExpressionSyntax GetDefaultValueMinimalSyntax(this IParameterSymbol parameterSymbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) - { - if (parameterSymbol == null) - throw new ArgumentNullException(nameof(parameterSymbol)); + #region IParameterSymbol + internal static ExpressionSyntax GetDefaultValueMinimalSyntax(this IParameterSymbol parameterSymbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) + { + if (parameterSymbol is null) + throw new ArgumentNullException(nameof(parameterSymbol)); - if (!parameterSymbol.HasExplicitDefaultValue) - throw new ArgumentException("Parameter does not specify default value.", nameof(parameterSymbol)); + if (!parameterSymbol.HasExplicitDefaultValue) + throw new ArgumentException("Parameter does not specify default value.", nameof(parameterSymbol)); - object value = parameterSymbol.ExplicitDefaultValue; + object value = parameterSymbol.ExplicitDefaultValue; - ITypeSymbol typeSymbol = parameterSymbol.Type; + ITypeSymbol typeSymbol = parameterSymbol.Type; - if (typeSymbol.TypeKind == TypeKind.Enum) - { - if (value == null) - return NullLiteralExpression(); + if (typeSymbol.TypeKind == TypeKind.Enum) + { + if (value is null) + return NullLiteralExpression(); - IFieldSymbol fieldSymbol = FindFieldWithConstantValue(); + IFieldSymbol fieldSymbol = FindFieldWithConstantValue(); - TypeSyntax type = typeSymbol.ToMinimalTypeSyntax(semanticModel, position, format); + TypeSyntax type = typeSymbol.ToMinimalTypeSyntax(semanticModel, position, format); - if (fieldSymbol != null) - { - return SimpleMemberAccessExpression(type, IdentifierName(fieldSymbol.Name)); + if (fieldSymbol is not null) + { + return SimpleMemberAccessExpression(type, IdentifierName(fieldSymbol.Name)); + } + else + { + return CastExpression(type, LiteralExpression(value)); + } } - else + + if (value is null + && !typeSymbol.IsReferenceTypeOrNullableType()) { - return CastExpression(type, LiteralExpression(value)); + return DefaultExpression(typeSymbol.ToMinimalTypeSyntax(semanticModel, position, format)); } - } - if (value == null - && !typeSymbol.IsReferenceTypeOrNullableType()) - { - return DefaultExpression(typeSymbol.ToMinimalTypeSyntax(semanticModel, position, format)); - } + return LiteralExpression(value); - return LiteralExpression(value); - - IFieldSymbol FindFieldWithConstantValue() - { - foreach (ISymbol symbol in typeSymbol.GetMembers()) + IFieldSymbol FindFieldWithConstantValue() { - if (symbol.Kind == SymbolKind.Field) + foreach (ISymbol symbol in typeSymbol.GetMembers()) { - var fieldSymbol = (IFieldSymbol)symbol; - - if (fieldSymbol.HasConstantValue - && object.Equals(fieldSymbol.ConstantValue, value)) + if (symbol.Kind == SymbolKind.Field) { - return fieldSymbol; + var fieldSymbol = (IFieldSymbol)symbol; + + if (fieldSymbol.HasConstantValue + && object.Equals(fieldSymbol.ConstantValue, value)) + { + return fieldSymbol; + } } } - } - return null; + return null; + } } - } - #endregion IParameterSymbol - - #region ITypeSymbol - /// - /// Creates a new based on the specified type symbol. - /// - /// - /// - public static TypeSyntax ToTypeSyntax(this ITypeSymbol typeSymbol, SymbolDisplayFormat format = null) - { - if (typeSymbol == null) - throw new ArgumentNullException(nameof(typeSymbol)); - - ThrowIfExplicitDeclarationIsNotSupported(typeSymbol); + #endregion IParameterSymbol + + #region ITypeSymbol + /// + /// Creates a new based on the specified type symbol. + /// + /// + /// + public static TypeSyntax ToTypeSyntax(this ITypeSymbol typeSymbol, SymbolDisplayFormat format = null) + { + if (typeSymbol is null) + throw new ArgumentNullException(nameof(typeSymbol)); - return ParseTypeName(typeSymbol.ToDisplayString(format ?? SymbolDisplayFormats.FullName)); - } + ThrowIfExplicitDeclarationIsNotSupported(typeSymbol); - /// - /// Creates a new based on the specified type symbol. - /// - /// - /// - /// - /// - public static TypeSyntax ToMinimalTypeSyntax(this ITypeSymbol typeSymbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) - { - if (typeSymbol == null) - throw new ArgumentNullException(nameof(typeSymbol)); + return ParseTypeName(typeSymbol.ToDisplayString(format ?? SymbolDisplayFormats.FullName)); + } - if (semanticModel == null) - throw new ArgumentNullException(nameof(semanticModel)); + /// + /// Creates a new based on the specified type symbol. + /// + /// + /// + /// + /// + public static TypeSyntax ToMinimalTypeSyntax(this ITypeSymbol typeSymbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) + { + if (typeSymbol is null) + throw new ArgumentNullException(nameof(typeSymbol)); - ThrowIfExplicitDeclarationIsNotSupported(typeSymbol); + if (semanticModel is null) + throw new ArgumentNullException(nameof(semanticModel)); - return ParseTypeName(typeSymbol.ToMinimalDisplayString(semanticModel, position, format ?? SymbolDisplayFormats.FullName)); - } + ThrowIfExplicitDeclarationIsNotSupported(typeSymbol); - private static void ThrowIfExplicitDeclarationIsNotSupported(ITypeSymbol typeSymbol) - { - if (!typeSymbol.SupportsExplicitDeclaration()) - throw new ArgumentException($"Type '{typeSymbol.ToDisplayString()}' does not support explicit declaration.", nameof(typeSymbol)); - } + return ParseTypeName(typeSymbol.ToMinimalDisplayString(semanticModel, position, format ?? SymbolDisplayFormats.FullName)); + } - /// - /// Returns true if the specified type can be used to declare constant value. - /// - /// - public static bool SupportsConstantValue(this ITypeSymbol typeSymbol) - { - if (typeSymbol == null) - throw new ArgumentNullException(nameof(typeSymbol)); + private static void ThrowIfExplicitDeclarationIsNotSupported(ITypeSymbol typeSymbol) + { + if (!typeSymbol.SupportsExplicitDeclaration()) + throw new ArgumentException($"Type '{typeSymbol.ToDisplayString()}' does not support explicit declaration.", nameof(typeSymbol)); + } - switch (typeSymbol.SpecialType) + /// + /// Returns true if the specified type can be used to declare constant value. + /// + /// + public static bool SupportsConstantValue(this ITypeSymbol typeSymbol) { - case SpecialType.System_Boolean: - case SpecialType.System_Char: - case SpecialType.System_SByte: - case SpecialType.System_Byte: - 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_Decimal: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_String: - return true; - default: - return typeSymbol.TypeKind == TypeKind.Enum; + if (typeSymbol is null) + throw new ArgumentNullException(nameof(typeSymbol)); + + switch (typeSymbol.SpecialType) + { + case SpecialType.System_Boolean: + case SpecialType.System_Char: + case SpecialType.System_SByte: + case SpecialType.System_Byte: + 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_Decimal: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_String: + return true; + default: + return typeSymbol.TypeKind == TypeKind.Enum; + } } - } - internal static bool SupportsPrefixOrPostfixUnaryOperator(this ITypeSymbol typeSymbol) - { - if (typeSymbol == null) - throw new ArgumentNullException(nameof(typeSymbol)); + internal static bool SupportsPrefixOrPostfixUnaryOperator(this ITypeSymbol typeSymbol) + { + if (typeSymbol is null) + throw new ArgumentNullException(nameof(typeSymbol)); - return CSharpFacts.SupportsPrefixOrPostfixUnaryOperator(typeSymbol.SpecialType) - || typeSymbol.TypeKind == TypeKind.Enum; - } + return CSharpFacts.SupportsPrefixOrPostfixUnaryOperator(typeSymbol.SpecialType) + || typeSymbol.TypeKind == TypeKind.Enum; + } - internal static bool IsReadOnlyStruct(this ITypeSymbol type) - { - return type.IsReadOnly - && type.TypeKind == TypeKind.Struct; + internal static bool IsReadOnlyStruct(this ITypeSymbol type) + { + return type.IsReadOnly + && type.TypeKind == TypeKind.Struct; + } + #endregion ITypeSymbol } - #endregion ITypeSymbol } diff --git a/src/CSharp/CSharp/Extensions/SyntaxExtensions.cs b/src/CSharp/CSharp/Extensions/SyntaxExtensions.cs index 1694788aed..12660a011e 100644 --- a/src/CSharp/CSharp/Extensions/SyntaxExtensions.cs +++ b/src/CSharp/CSharp/Extensions/SyntaxExtensions.cs @@ -18,4381 +18,4382 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp; - -/// -/// A set of extension methods for syntax (types derived from ). -/// -public static class SyntaxExtensions +namespace Roslynator.CSharp { - #region AccessorDeclarationSyntax - /// - /// Returns true is the specified accessor is auto-implemented accessor. - /// - /// - public static bool IsAutoImplemented(this AccessorDeclarationSyntax accessorDeclaration) - { - return accessorDeclaration?.SemicolonToken.IsKind(SyntaxKind.SemicolonToken) == true - && accessorDeclaration.BodyOrExpressionBody() == null; - } - - /// - /// Returns accessor body or an expression body if the body is null. - /// - /// - public static CSharpSyntaxNode BodyOrExpressionBody(this AccessorDeclarationSyntax accessorDeclaration) - { - if (accessorDeclaration == null) - throw new ArgumentNullException(nameof(accessorDeclaration)); - - return accessorDeclaration.Body ?? (CSharpSyntaxNode)accessorDeclaration.ExpressionBody; - } - #endregion AccessorDeclarationSyntax - - #region AccessorListSyntax - /// - /// Returns a get accessor contained in the specified list. - /// - /// - public static AccessorDeclarationSyntax Getter(this AccessorListSyntax accessorList) - { - return Accessor(accessorList, SyntaxKind.GetAccessorDeclaration); - } - /// - /// Returns a set accessor contained in the specified list. + /// A set of extension methods for syntax (types derived from ). /// - /// - public static AccessorDeclarationSyntax Setter(this AccessorListSyntax accessorList) - { - return Accessor(accessorList, SyntaxKind.SetAccessorDeclaration, SyntaxKind.InitAccessorDeclaration); - } - - private static AccessorDeclarationSyntax Accessor(this AccessorListSyntax accessorList, SyntaxKind kind) + public static class SyntaxExtensions { - if (accessorList == null) - throw new ArgumentNullException(nameof(accessorList)); - - foreach (AccessorDeclarationSyntax accessor in accessorList.Accessors) + #region AccessorDeclarationSyntax + /// + /// Returns true is the specified accessor is auto-implemented accessor. + /// + /// + public static bool IsAutoImplemented(this AccessorDeclarationSyntax accessorDeclaration) { - if (accessor.IsKind(kind)) - return accessor; + return accessorDeclaration?.SemicolonToken.IsKind(SyntaxKind.SemicolonToken) == true + && accessorDeclaration.BodyOrExpressionBody() is null; } - return null; - } - - private static AccessorDeclarationSyntax Accessor(this AccessorListSyntax accessorList, SyntaxKind kind1, SyntaxKind kind2) - { - if (accessorList == null) - throw new ArgumentNullException(nameof(accessorList)); + /// + /// Returns accessor body or an expression body if the body is null. + /// + /// + public static CSharpSyntaxNode BodyOrExpressionBody(this AccessorDeclarationSyntax accessorDeclaration) + { + if (accessorDeclaration is null) + throw new ArgumentNullException(nameof(accessorDeclaration)); - foreach (AccessorDeclarationSyntax accessor in accessorList.Accessors) + return accessorDeclaration.Body ?? (CSharpSyntaxNode)accessorDeclaration.ExpressionBody; + } + #endregion AccessorDeclarationSyntax + + #region AccessorListSyntax + /// + /// Returns a get accessor contained in the specified list. + /// + /// + public static AccessorDeclarationSyntax Getter(this AccessorListSyntax accessorList) { - if (accessor.IsKind(kind1, kind2)) - return accessor; + return Accessor(accessorList, SyntaxKind.GetAccessorDeclaration); } - return null; - } - #endregion AccessorListSyntax + /// + /// Returns a set accessor contained in the specified list. + /// + /// + public static AccessorDeclarationSyntax Setter(this AccessorListSyntax accessorList) + { + return Accessor(accessorList, SyntaxKind.SetAccessorDeclaration, SyntaxKind.InitAccessorDeclaration); + } - #region BlockSyntax - internal static StatementSyntax SingleNonBlockStatementOrDefault(this BlockSyntax body, bool recursive = false) - { - if (recursive) + private static AccessorDeclarationSyntax Accessor(this AccessorListSyntax accessorList, SyntaxKind kind) { - StatementSyntax statement; + if (accessorList is null) + throw new ArgumentNullException(nameof(accessorList)); - do + foreach (AccessorDeclarationSyntax accessor in accessorList.Accessors) { - statement = body.Statements.SingleOrDefault(shouldThrow: false); - - body = statement as BlockSyntax; + if (accessor.IsKind(kind)) + return accessor; } - while (body != null); - return statement; + return null; } - else + + private static AccessorDeclarationSyntax Accessor(this AccessorListSyntax accessorList, SyntaxKind kind1, SyntaxKind kind2) { - StatementSyntax statement = body.Statements.SingleOrDefault(shouldThrow: false); + if (accessorList is null) + throw new ArgumentNullException(nameof(accessorList)); - if (statement != null - && statement.Kind() != SyntaxKind.Block) + foreach (AccessorDeclarationSyntax accessor in accessorList.Accessors) { - return statement; + if (accessor.IsKind(kind1, kind2)) + return accessor; } return null; } - } + #endregion AccessorListSyntax - internal static bool ContainsYield(this BlockSyntax block, bool yieldReturn = true, bool yieldBreak = true) - { - return ContainsYieldWalker.ContainsYield(block, yieldReturn, yieldBreak); - } - #endregion BlockSyntax - - #region BaseArgumentListSyntax - internal static BaseArgumentListSyntax WithArguments(this BaseArgumentListSyntax baseArgumentList, SeparatedSyntaxList arguments) - { - switch (baseArgumentList.Kind()) + #region BlockSyntax + internal static StatementSyntax SingleNonBlockStatementOrDefault(this BlockSyntax body, bool recursive = false) { - case SyntaxKind.ArgumentList: - return ((ArgumentListSyntax)baseArgumentList).WithArguments(arguments); - case SyntaxKind.BracketedArgumentList: - return ((BracketedArgumentListSyntax)baseArgumentList).WithArguments(arguments); - } + if (recursive) + { + StatementSyntax statement; - Debug.Fail(baseArgumentList?.Kind().ToString()); + do + { + statement = body.Statements.SingleOrDefault(shouldThrow: false); - return null; - } - #endregion BaseArgumentListSyntax + body = statement as BlockSyntax; + } + while (body is not null); - #region BinaryExpressionSyntax - /// - /// Returns that enables to enumerate expressions of a binary expression. - /// - /// - /// - public static ExpressionChain AsChain(this BinaryExpressionSyntax binaryExpression, TextSpan? span = null) - { - return new ExpressionChain(binaryExpression, span); - } - #endregion BinaryExpressionSyntax + return statement; + } + else + { + StatementSyntax statement = body.Statements.SingleOrDefault(shouldThrow: false); - #region CastExpressionSyntax - /// - /// The absolute span of the parentheses, not including its leading and trailing trivia. - /// - /// - public static TextSpan ParenthesesSpan(this CastExpressionSyntax castExpression) - { - if (castExpression == null) - throw new ArgumentNullException(nameof(castExpression)); + if (statement is not null + && statement.Kind() != SyntaxKind.Block) + { + return statement; + } - return TextSpan.FromBounds( - castExpression.OpenParenToken.SpanStart, - castExpression.CloseParenToken.Span.End); - } - #endregion CastExpressionSyntax + return null; + } + } - #region ClassDeclarationSyntax - /// - /// Creates a new with the members updated. - /// - /// - /// - public static ClassDeclarationSyntax WithMembers( - this ClassDeclarationSyntax classDeclaration, - MemberDeclarationSyntax member) - { - if (classDeclaration == null) - throw new ArgumentNullException(nameof(classDeclaration)); + internal static bool ContainsYield(this BlockSyntax block, bool yieldReturn = true, bool yieldBreak = true) + { + return ContainsYieldWalker.ContainsYield(block, yieldReturn, yieldBreak); + } + #endregion BlockSyntax - return classDeclaration.WithMembers(SingletonList(member)); - } + #region BaseArgumentListSyntax + internal static BaseArgumentListSyntax WithArguments(this BaseArgumentListSyntax baseArgumentList, SeparatedSyntaxList arguments) + { + switch (baseArgumentList.Kind()) + { + case SyntaxKind.ArgumentList: + return ((ArgumentListSyntax)baseArgumentList).WithArguments(arguments); + case SyntaxKind.BracketedArgumentList: + return ((BracketedArgumentListSyntax)baseArgumentList).WithArguments(arguments); + } - /// - /// Creates a new with the members updated. - /// - /// - /// - public static ClassDeclarationSyntax WithMembers( - this ClassDeclarationSyntax classDeclaration, - IEnumerable members) - { - if (classDeclaration == null) - throw new ArgumentNullException(nameof(classDeclaration)); + Debug.Fail(baseArgumentList?.Kind().ToString()); - return classDeclaration.WithMembers(List(members)); - } + return null; + } + #endregion BaseArgumentListSyntax + + #region BinaryExpressionSyntax + /// + /// Returns that enables to enumerate expressions of a binary expression. + /// + /// + /// + public static ExpressionChain AsChain(this BinaryExpressionSyntax binaryExpression, TextSpan? span = null) + { + return new ExpressionChain(binaryExpression, span); + } + #endregion BinaryExpressionSyntax + + #region CastExpressionSyntax + /// + /// The absolute span of the parentheses, not including its leading and trailing trivia. + /// + /// + public static TextSpan ParenthesesSpan(this CastExpressionSyntax castExpression) + { + if (castExpression is null) + throw new ArgumentNullException(nameof(castExpression)); - /// - /// The absolute span of the braces, not including its leading and trailing trivia. - /// - /// - public static TextSpan BracesSpan(this ClassDeclarationSyntax classDeclaration) - { - if (classDeclaration == null) - throw new ArgumentNullException(nameof(classDeclaration)); + return TextSpan.FromBounds( + castExpression.OpenParenToken.SpanStart, + castExpression.CloseParenToken.Span.End); + } + #endregion CastExpressionSyntax + + #region ClassDeclarationSyntax + /// + /// Creates a new with the members updated. + /// + /// + /// + public static ClassDeclarationSyntax WithMembers( + this ClassDeclarationSyntax classDeclaration, + MemberDeclarationSyntax member) + { + if (classDeclaration is null) + throw new ArgumentNullException(nameof(classDeclaration)); - return TextSpan.FromBounds( - classDeclaration.OpenBraceToken.SpanStart, - classDeclaration.CloseBraceToken.Span.End); - } - #endregion ClassDeclarationSyntax + return classDeclaration.WithMembers(SingletonList(member)); + } - #region CommonForEachStatementSyntax - /// - /// The absolute span of the parentheses, not including its leading and trailing trivia. - /// - /// - public static TextSpan ParenthesesSpan(this CommonForEachStatementSyntax forEachStatement) - { - if (forEachStatement == null) - throw new ArgumentNullException(nameof(forEachStatement)); + /// + /// Creates a new with the members updated. + /// + /// + /// + public static ClassDeclarationSyntax WithMembers( + this ClassDeclarationSyntax classDeclaration, + IEnumerable members) + { + if (classDeclaration is null) + throw new ArgumentNullException(nameof(classDeclaration)); - return TextSpan.FromBounds(forEachStatement.OpenParenToken.SpanStart, forEachStatement.CloseParenToken.Span.End); - } + return classDeclaration.WithMembers(List(members)); + } - internal static StatementSyntax EmbeddedStatement(this CommonForEachStatementSyntax forEachStatement) - { - StatementSyntax statement = forEachStatement.Statement; + /// + /// The absolute span of the braces, not including its leading and trailing trivia. + /// + /// + public static TextSpan BracesSpan(this ClassDeclarationSyntax classDeclaration) + { + if (classDeclaration is null) + throw new ArgumentNullException(nameof(classDeclaration)); - return (statement?.Kind() == SyntaxKind.Block) ? null : statement; - } - #endregion CommonForEachStatementSyntax + return TextSpan.FromBounds( + classDeclaration.OpenBraceToken.SpanStart, + classDeclaration.CloseBraceToken.Span.End); + } + #endregion ClassDeclarationSyntax + + #region CommonForEachStatementSyntax + /// + /// The absolute span of the parentheses, not including its leading and trailing trivia. + /// + /// + public static TextSpan ParenthesesSpan(this CommonForEachStatementSyntax forEachStatement) + { + if (forEachStatement is null) + throw new ArgumentNullException(nameof(forEachStatement)); - #region CompilationUnitSyntax - /// - /// Creates a new with the members updated. - /// - /// - /// - public static CompilationUnitSyntax WithMembers( - this CompilationUnitSyntax compilationUnit, - MemberDeclarationSyntax member) - { - if (compilationUnit == null) - throw new ArgumentNullException(nameof(compilationUnit)); + return TextSpan.FromBounds(forEachStatement.OpenParenToken.SpanStart, forEachStatement.CloseParenToken.Span.End); + } - return compilationUnit.WithMembers(SingletonList(member)); - } + internal static StatementSyntax EmbeddedStatement(this CommonForEachStatementSyntax forEachStatement) + { + StatementSyntax statement = forEachStatement.Statement; - /// - /// Creates a new with the members updated. - /// - /// - /// - public static CompilationUnitSyntax WithMembers( - this CompilationUnitSyntax compilationUnit, - IEnumerable members) - { - if (compilationUnit == null) - throw new ArgumentNullException(nameof(compilationUnit)); + return (statement?.Kind() == SyntaxKind.Block) ? null : statement; + } + #endregion CommonForEachStatementSyntax + + #region CompilationUnitSyntax + /// + /// Creates a new with the members updated. + /// + /// + /// + public static CompilationUnitSyntax WithMembers( + this CompilationUnitSyntax compilationUnit, + MemberDeclarationSyntax member) + { + if (compilationUnit is null) + throw new ArgumentNullException(nameof(compilationUnit)); - return compilationUnit.WithMembers(List(members)); - } + return compilationUnit.WithMembers(SingletonList(member)); + } - /// - /// Creates a new with the specified using directives added. - /// - /// - /// - /// - public static CompilationUnitSyntax AddUsings(this CompilationUnitSyntax compilationUnit, bool keepSingleLineCommentsOnTop, params UsingDirectiveSyntax[] usings) - { - if (compilationUnit == null) - throw new ArgumentNullException(nameof(compilationUnit)); + /// + /// Creates a new with the members updated. + /// + /// + /// + public static CompilationUnitSyntax WithMembers( + this CompilationUnitSyntax compilationUnit, + IEnumerable members) + { + if (compilationUnit is null) + throw new ArgumentNullException(nameof(compilationUnit)); - if (usings == null) - throw new ArgumentNullException(nameof(usings)); + return compilationUnit.WithMembers(List(members)); + } - if (keepSingleLineCommentsOnTop - && usings.Length > 0 - && !compilationUnit.Usings.Any()) + /// + /// Creates a new with the specified using directives added. + /// + /// + /// + /// + public static CompilationUnitSyntax AddUsings(this CompilationUnitSyntax compilationUnit, bool keepSingleLineCommentsOnTop, params UsingDirectiveSyntax[] usings) { - List topTrivia = null; - - SyntaxTriviaList leadingTrivia = compilationUnit.GetLeadingTrivia(); + if (compilationUnit is null) + throw new ArgumentNullException(nameof(compilationUnit)); - SyntaxTriviaList.Enumerator en = leadingTrivia.GetEnumerator(); + if (usings is null) + throw new ArgumentNullException(nameof(usings)); - while (en.MoveNext()) + if (keepSingleLineCommentsOnTop + && usings.Length > 0 + && !compilationUnit.Usings.Any()) { - if (en.Current.IsKind(SyntaxKind.SingleLineCommentTrivia)) - { - SyntaxTrivia trivia = en.Current; + List topTrivia = null; + + SyntaxTriviaList leadingTrivia = compilationUnit.GetLeadingTrivia(); - if (en.MoveNext() - && en.Current.IsEndOfLineTrivia()) + SyntaxTriviaList.Enumerator en = leadingTrivia.GetEnumerator(); + + while (en.MoveNext()) + { + if (en.Current.IsKind(SyntaxKind.SingleLineCommentTrivia)) { - (topTrivia ??= new List()).Add(trivia); - topTrivia.Add(en.Current); + SyntaxTrivia trivia = en.Current; + + if (en.MoveNext() + && en.Current.IsEndOfLineTrivia()) + { + (topTrivia ??= new List()).Add(trivia); + topTrivia.Add(en.Current); + } + else + { + break; + } } else { break; } } - else + + if (topTrivia?.Count > 0) { - break; + compilationUnit = compilationUnit.WithoutLeadingTrivia(); + + usings[0] = usings[0].WithLeadingTrivia(topTrivia); + + usings[usings.Length - 1] = usings[usings.Length - 1].WithTrailingTrivia(leadingTrivia.Skip(topTrivia.Count)); } } - if (topTrivia?.Count > 0) - { - compilationUnit = compilationUnit.WithoutLeadingTrivia(); + return compilationUnit.AddUsings(usings); + } + #endregion CompilationUnitSyntax - usings[0] = usings[0].WithLeadingTrivia(topTrivia); + internal static ExpressionSyntax RemoveOperatorToken(this ConditionalAccessExpressionSyntax conditionalAccessExpression) + { + SyntaxToken operatorToken = conditionalAccessExpression.OperatorToken; - usings[usings.Length - 1] = usings[usings.Length - 1].WithTrailingTrivia(leadingTrivia.Skip(topTrivia.Count)); - } - } + string text = conditionalAccessExpression + .ToFullString() + .Remove(operatorToken.FullSpan.Start - conditionalAccessExpression.FullSpan.Start, operatorToken.FullSpan.Length); - return compilationUnit.AddUsings(usings); - } - #endregion CompilationUnitSyntax + return ParseExpression(text); + } - internal static ExpressionSyntax RemoveOperatorToken(this ConditionalAccessExpressionSyntax conditionalAccessExpression) - { - SyntaxToken operatorToken = conditionalAccessExpression.OperatorToken; + #region ConstructorDeclarationSyntax + internal static TextSpan HeaderSpan(this ConstructorDeclarationSyntax constructorDeclaration) + { + int start; - string text = conditionalAccessExpression - .ToFullString() - .Remove(operatorToken.FullSpan.Start - conditionalAccessExpression.FullSpan.Start, operatorToken.FullSpan.Length); + SyntaxList attributeLists = constructorDeclaration.AttributeLists; - return ParseExpression(text); - } + if (attributeLists.Any()) + { + SyntaxTokenList modifiers = constructorDeclaration.Modifiers; - #region ConstructorDeclarationSyntax - internal static TextSpan HeaderSpan(this ConstructorDeclarationSyntax constructorDeclaration) - { - int start; + start = (modifiers.Any()) + ? modifiers[0].SpanStart + : constructorDeclaration.Identifier.SpanStart; + } + else + { + start = constructorDeclaration.SpanStart; + } - SyntaxList attributeLists = constructorDeclaration.AttributeLists; + return TextSpan.FromBounds( + start, + constructorDeclaration.Initializer?.Span.End + ?? constructorDeclaration.ParameterList?.Span.End + ?? constructorDeclaration.Identifier.Span.End); + } - if (attributeLists.Any()) + /// + /// Returns constructor body or an expression body if the body is null. + /// + /// + public static CSharpSyntaxNode BodyOrExpressionBody(this ConstructorDeclarationSyntax constructorDeclaration) { - SyntaxTokenList modifiers = constructorDeclaration.Modifiers; + if (constructorDeclaration is null) + throw new ArgumentNullException(nameof(constructorDeclaration)); - start = (modifiers.Any()) - ? modifiers[0].SpanStart - : constructorDeclaration.Identifier.SpanStart; + return constructorDeclaration.Body ?? (CSharpSyntaxNode)constructorDeclaration.ExpressionBody; } - else + #endregion ConstructorDeclarationSyntax + + #region ConversionOperatorDeclarationSyntax + /// + /// Returns conversion operator body or an expression body if the body is null. + /// + /// + public static CSharpSyntaxNode BodyOrExpressionBody(this ConversionOperatorDeclarationSyntax conversionOperatorDeclaration) { - start = constructorDeclaration.SpanStart; - } - - return TextSpan.FromBounds( - start, - constructorDeclaration.Initializer?.Span.End - ?? constructorDeclaration.ParameterList?.Span.End - ?? constructorDeclaration.Identifier.Span.End); - } + if (conversionOperatorDeclaration is null) + throw new ArgumentNullException(nameof(conversionOperatorDeclaration)); - /// - /// Returns constructor body or an expression body if the body is null. - /// - /// - public static CSharpSyntaxNode BodyOrExpressionBody(this ConstructorDeclarationSyntax constructorDeclaration) - { - if (constructorDeclaration == null) - throw new ArgumentNullException(nameof(constructorDeclaration)); + return conversionOperatorDeclaration.Body ?? (CSharpSyntaxNode)conversionOperatorDeclaration.ExpressionBody; + } - return constructorDeclaration.Body ?? (CSharpSyntaxNode)constructorDeclaration.ExpressionBody; - } - #endregion ConstructorDeclarationSyntax + internal static TextSpan HeaderSpan(this ConversionOperatorDeclarationSyntax operatorDeclaration) + { + int start; - #region ConversionOperatorDeclarationSyntax - /// - /// Returns conversion operator body or an expression body if the body is null. - /// - /// - public static CSharpSyntaxNode BodyOrExpressionBody(this ConversionOperatorDeclarationSyntax conversionOperatorDeclaration) - { - if (conversionOperatorDeclaration == null) - throw new ArgumentNullException(nameof(conversionOperatorDeclaration)); + SyntaxList attributeLists = operatorDeclaration.AttributeLists; - return conversionOperatorDeclaration.Body ?? (CSharpSyntaxNode)conversionOperatorDeclaration.ExpressionBody; - } + if (attributeLists.Any()) + { + SyntaxTokenList modifiers = operatorDeclaration.Modifiers; - internal static TextSpan HeaderSpan(this ConversionOperatorDeclarationSyntax operatorDeclaration) - { - int start; + start = (modifiers.Any()) + ? modifiers[0].SpanStart + : operatorDeclaration.ImplicitOrExplicitKeyword.SpanStart; + } + else + { + start = operatorDeclaration.SpanStart; + } - SyntaxList attributeLists = operatorDeclaration.AttributeLists; + return TextSpan.FromBounds( + start, + operatorDeclaration.ParameterList?.Span.End + ?? operatorDeclaration.Type.Span.End); + } + #endregion ConversionOperatorDeclarationSyntax - if (attributeLists.Any()) + #region DefaultExpressionSyntax + internal static TextSpan ParenthesesSpan(this DefaultExpressionSyntax defaultExpression) { - SyntaxTokenList modifiers = operatorDeclaration.Modifiers; - - start = (modifiers.Any()) - ? modifiers[0].SpanStart - : operatorDeclaration.ImplicitOrExplicitKeyword.SpanStart; + return TextSpan.FromBounds(defaultExpression.OpenParenToken.SpanStart, defaultExpression.CloseParenToken.Span.End); } - else + #endregion DefaultExpressionSyntax + + #region DelegateDeclarationSyntax + /// + /// Returns true the specified delegate return type is . + /// + /// + public static bool ReturnsVoid(this DelegateDeclarationSyntax delegateDeclaration) { - start = operatorDeclaration.SpanStart; + return delegateDeclaration?.ReturnType?.IsVoid() == true; } + #endregion DelegateDeclarationSyntax + + #region DestructorDeclarationSyntax + /// + /// Returns destructor body or an expression body if the body is null. + /// + /// + public static CSharpSyntaxNode BodyOrExpressionBody(this DestructorDeclarationSyntax destructorDeclaration) + { + if (destructorDeclaration is null) + throw new ArgumentNullException(nameof(destructorDeclaration)); - return TextSpan.FromBounds( - start, - operatorDeclaration.ParameterList?.Span.End - ?? operatorDeclaration.Type.Span.End); - } - #endregion ConversionOperatorDeclarationSyntax - - #region DefaultExpressionSyntax - internal static TextSpan ParenthesesSpan(this DefaultExpressionSyntax defaultExpression) - { - return TextSpan.FromBounds(defaultExpression.OpenParenToken.SpanStart, defaultExpression.CloseParenToken.Span.End); - } - #endregion DefaultExpressionSyntax - - #region DelegateDeclarationSyntax - /// - /// Returns true the specified delegate return type is . - /// - /// - public static bool ReturnsVoid(this DelegateDeclarationSyntax delegateDeclaration) - { - return delegateDeclaration?.ReturnType?.IsVoid() == true; - } - #endregion DelegateDeclarationSyntax - - #region DestructorDeclarationSyntax - /// - /// Returns destructor body or an expression body if the body is null. - /// - /// - public static CSharpSyntaxNode BodyOrExpressionBody(this DestructorDeclarationSyntax destructorDeclaration) - { - if (destructorDeclaration == null) - throw new ArgumentNullException(nameof(destructorDeclaration)); + return destructorDeclaration.Body ?? (CSharpSyntaxNode)destructorDeclaration.ExpressionBody; + } - return destructorDeclaration.Body ?? (CSharpSyntaxNode)destructorDeclaration.ExpressionBody; - } + internal static TextSpan HeaderSpan(this DestructorDeclarationSyntax destructorDeclaration) + { + int start; - internal static TextSpan HeaderSpan(this DestructorDeclarationSyntax destructorDeclaration) - { - int start; + SyntaxList attributeLists = destructorDeclaration.AttributeLists; - SyntaxList attributeLists = destructorDeclaration.AttributeLists; + if (attributeLists.Any()) + { + SyntaxTokenList modifiers = destructorDeclaration.Modifiers; - if (attributeLists.Any()) - { - SyntaxTokenList modifiers = destructorDeclaration.Modifiers; + start = (modifiers.Any()) + ? modifiers[0].SpanStart + : destructorDeclaration.TildeToken.SpanStart; + } + else + { + start = destructorDeclaration.SpanStart; + } - start = (modifiers.Any()) - ? modifiers[0].SpanStart - : destructorDeclaration.TildeToken.SpanStart; + return TextSpan.FromBounds( + start, + destructorDeclaration.ParameterList?.Span.End + ?? destructorDeclaration.TildeToken.Span.End); } - else + #endregion DestructorDeclarationSyntax + + #region DirectiveTriviaSyntax + /// + /// Returns the next related directive. + /// + /// + public static DirectiveTriviaSyntax GetNextRelatedDirective(this DirectiveTriviaSyntax directiveTrivia) { - start = destructorDeclaration.SpanStart; - } - - return TextSpan.FromBounds( - start, - destructorDeclaration.ParameterList?.Span.End - ?? destructorDeclaration.TildeToken.Span.End); - } - #endregion DestructorDeclarationSyntax + DirectiveTriviaSyntax d = directiveTrivia; - #region DirectiveTriviaSyntax - /// - /// Returns the next related directive. - /// - /// - public static DirectiveTriviaSyntax GetNextRelatedDirective(this DirectiveTriviaSyntax directiveTrivia) - { - DirectiveTriviaSyntax d = directiveTrivia; - - switch (d.Kind()) - { - case SyntaxKind.IfDirectiveTrivia: - case SyntaxKind.ElifDirectiveTrivia: - { - while (true) + switch (d.Kind()) + { + case SyntaxKind.IfDirectiveTrivia: + case SyntaxKind.ElifDirectiveTrivia: { - d = d.GetNextPossiblyRelatedDirective(); + while (true) + { + d = d.GetNextPossiblyRelatedDirective(); - if (d == 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; - } - case SyntaxKind.ElseDirectiveTrivia: - { - while (true) + break; + } + case SyntaxKind.ElseDirectiveTrivia: { - d = d.GetNextPossiblyRelatedDirective(); + while (true) + { + d = d.GetNextPossiblyRelatedDirective(); - if (d == null) - break; + if (d is null) + break; - if (d.Kind() == SyntaxKind.EndIfDirectiveTrivia) - return d; - } + if (d.Kind() == SyntaxKind.EndIfDirectiveTrivia) + return d; + } - break; - } - case SyntaxKind.RegionDirectiveTrivia: - { - while (true) + break; + } + case SyntaxKind.RegionDirectiveTrivia: { - d = d.GetNextPossiblyRelatedDirective(); + while (true) + { + d = d.GetNextPossiblyRelatedDirective(); - if (d == null) - break; + if (d is null) + break; + + if (d.Kind() == SyntaxKind.EndRegionDirectiveTrivia) + return d; + } - if (d.Kind() == SyntaxKind.EndRegionDirectiveTrivia) - return d; + break; } + } - break; - } + return null; } - return null; - } - - private static DirectiveTriviaSyntax GetNextPossiblyRelatedDirective(this DirectiveTriviaSyntax directiveTrivia) - { - DirectiveTriviaSyntax d = directiveTrivia; - - while (d != null) + private static DirectiveTriviaSyntax GetNextPossiblyRelatedDirective(this DirectiveTriviaSyntax directiveTrivia) { - d = d.GetNextDirective(); + DirectiveTriviaSyntax d = directiveTrivia; - if (d != null) + while (d is not null) { - switch (d.Kind()) + d = d.GetNextDirective(); + + if (d is not null) { - case SyntaxKind.IfDirectiveTrivia: - { - do + switch (d.Kind()) + { + case SyntaxKind.IfDirectiveTrivia: { - d = d.GetNextRelatedDirective(); - } - while (d != null && d.Kind() != SyntaxKind.EndIfDirectiveTrivia); + do + { + d = d.GetNextRelatedDirective(); + } + while (d is not null && d.Kind() != SyntaxKind.EndIfDirectiveTrivia); - continue; - } - case SyntaxKind.RegionDirectiveTrivia: - { - do - { - d = d.GetNextRelatedDirective(); + continue; } - while (d != null && d.Kind() != SyntaxKind.EndRegionDirectiveTrivia); + case SyntaxKind.RegionDirectiveTrivia: + { + do + { + d = d.GetNextRelatedDirective(); + } + while (d is not null && d.Kind() != SyntaxKind.EndRegionDirectiveTrivia); - continue; - } + continue; + } + } } + + return d; } - return d; + return null; } + #endregion DirectiveTriviaSyntax - return null; - } - #endregion DirectiveTriviaSyntax - - #region DocumentationCommentTriviaSyntax - internal static XmlElementSyntax SummaryElement(this DocumentationCommentTriviaSyntax documentationComment) - { - if (documentationComment == null) - throw new ArgumentNullException(nameof(documentationComment)); - - foreach (XmlNodeSyntax node in documentationComment.Content) + #region DocumentationCommentTriviaSyntax + internal static XmlElementSyntax SummaryElement(this DocumentationCommentTriviaSyntax documentationComment) { - if (node is XmlElementSyntax element - && element.IsLocalName("summary", StringComparison.OrdinalIgnoreCase)) + if (documentationComment is null) + throw new ArgumentNullException(nameof(documentationComment)); + + foreach (XmlNodeSyntax node in documentationComment.Content) { - return element; + if (node is XmlElementSyntax element + && element.IsLocalName("summary", StringComparison.OrdinalIgnoreCase)) + { + return element; + } } + + return null; } - return null; - } + /// + /// Gets a list of xml elements with the specified local name. + /// + /// + /// + public static IEnumerable Elements(this DocumentationCommentTriviaSyntax documentationComment, string localName) + { + if (documentationComment is null) + throw new ArgumentNullException(nameof(documentationComment)); - /// - /// Gets a list of xml elements with the specified local name. - /// - /// - /// - public static IEnumerable Elements(this DocumentationCommentTriviaSyntax documentationComment, string localName) - { - if (documentationComment == null) - throw new ArgumentNullException(nameof(documentationComment)); + return ElementsIterator(); - return ElementsIterator(); + IEnumerable ElementsIterator() + { + foreach (XmlNodeSyntax node in documentationComment.Content) + { + if (node is XmlElementSyntax xmlElement + && xmlElement.IsLocalName(localName)) + { + yield return xmlElement; + } + } + } + } - IEnumerable ElementsIterator() + internal static IEnumerable Elements(this DocumentationCommentTriviaSyntax documentationComment, XmlTag tag) { foreach (XmlNodeSyntax node in documentationComment.Content) { if (node is XmlElementSyntax xmlElement - && xmlElement.IsLocalName(localName)) + && xmlElement.HasTag(tag)) { yield return xmlElement; } } } - } - internal static IEnumerable Elements(this DocumentationCommentTriviaSyntax documentationComment, XmlTag tag) - { - foreach (XmlNodeSyntax node in documentationComment.Content) + internal static bool IsPartOfMemberDeclaration(this DocumentationCommentTriviaSyntax documentationComment) { - if (node is XmlElementSyntax xmlElement - && xmlElement.HasTag(tag)) - { - yield return xmlElement; - } - } - } - - internal static bool IsPartOfMemberDeclaration(this DocumentationCommentTriviaSyntax documentationComment) - { - SyntaxNode node = documentationComment.ParentTrivia.Token.Parent; - - return node is MemberDeclarationSyntax - || node.Parent is MemberDeclarationSyntax; - } - #endregion DocumentationCommentTriviaSyntax - - #region DoStatementSyntax - internal static StatementSyntax EmbeddedStatement(this DoStatementSyntax doStatement) - { - StatementSyntax statement = doStatement.Statement; + SyntaxNode node = documentationComment.ParentTrivia.Token.Parent; - return (statement?.Kind() == SyntaxKind.Block) ? null : statement; - } - #endregion DoStatementSyntax - - #region ElseClauseSyntax - internal static StatementSyntax SingleNonBlockStatementOrDefault(this ElseClauseSyntax elseClause) - { - return SingleNonBlockStatementOrDefault(elseClause.Statement); - } - - /// - /// Returns topmost if statement of the if-else cascade the specified else clause is part of. - /// - /// - public static IfStatementSyntax GetTopmostIf(this ElseClauseSyntax elseClause) - { - if (elseClause == null) - throw new ArgumentNullException(nameof(elseClause)); - - if (elseClause.Parent is IfStatementSyntax ifStatement) - return ifStatement.GetTopmostIf(); - - return null; - } - - internal static StatementSyntax EmbeddedStatement(this ElseClauseSyntax elseClause, bool allowIfStatement = true) - { - StatementSyntax statement = elseClause.Statement; - - if (statement == null) - return null; + return node is MemberDeclarationSyntax + || node.Parent is MemberDeclarationSyntax; + } + #endregion DocumentationCommentTriviaSyntax - SyntaxKind kind = statement.Kind(); + #region DoStatementSyntax + internal static StatementSyntax EmbeddedStatement(this DoStatementSyntax doStatement) + { + StatementSyntax statement = doStatement.Statement; - if (kind == SyntaxKind.Block) - return null; + return (statement?.Kind() == SyntaxKind.Block) ? null : statement; + } + #endregion DoStatementSyntax - if (!allowIfStatement - && kind == SyntaxKind.IfStatement) + #region ElseClauseSyntax + internal static StatementSyntax SingleNonBlockStatementOrDefault(this ElseClauseSyntax elseClause) { - return null; + return SingleNonBlockStatementOrDefault(elseClause.Statement); } - return statement; - } - #endregion ElseClauseSyntax + /// + /// Returns topmost if statement of the if-else cascade the specified else clause is part of. + /// + /// + public static IfStatementSyntax GetTopmostIf(this ElseClauseSyntax elseClause) + { + if (elseClause is null) + throw new ArgumentNullException(nameof(elseClause)); - #region EndRegionDirectiveTriviaSyntax - /// - /// Returns region directive that is related to the specified endregion directive. Returns null if no matching region directive is found. - /// - /// - public static RegionDirectiveTriviaSyntax GetRegionDirective(this EndRegionDirectiveTriviaSyntax endRegionDirective) - { - if (endRegionDirective == null) - throw new ArgumentNullException(nameof(endRegionDirective)); + if (elseClause.Parent is IfStatementSyntax ifStatement) + return ifStatement.GetTopmostIf(); - RegionInfo region = SyntaxInfo.RegionInfo(endRegionDirective); + return null; + } - return (region.Success) ? region.Directive : null; - } + internal static StatementSyntax EmbeddedStatement(this ElseClauseSyntax elseClause, bool allowIfStatement = true) + { + StatementSyntax statement = elseClause.Statement; - /// - /// Gets preprocessing message for the specified endregion directive if such message exists. - /// - /// - public static SyntaxTrivia GetPreprocessingMessageTrivia(this EndRegionDirectiveTriviaSyntax endRegionDirective) - { - if (endRegionDirective == null) - throw new ArgumentNullException(nameof(endRegionDirective)); + if (statement is null) + return null; - SyntaxToken endOfDirective = endRegionDirective.EndOfDirectiveToken; + SyntaxKind kind = statement.Kind(); - SyntaxTriviaList leading = endOfDirective.LeadingTrivia; + if (kind == SyntaxKind.Block) + return null; - if (leading.Count == 1) - { - SyntaxTrivia trivia = leading[0]; + if (!allowIfStatement + && kind == SyntaxKind.IfStatement) + { + return null; + } - if (trivia.IsKind(SyntaxKind.PreprocessingMessageTrivia)) - return trivia; + return statement; } + #endregion ElseClauseSyntax + + #region EndRegionDirectiveTriviaSyntax + /// + /// Returns region directive that is related to the specified endregion directive. Returns null if no matching region directive is found. + /// + /// + public static RegionDirectiveTriviaSyntax GetRegionDirective(this EndRegionDirectiveTriviaSyntax endRegionDirective) + { + if (endRegionDirective is null) + throw new ArgumentNullException(nameof(endRegionDirective)); - return default; - } - - /// - /// Returns true the specified endregion directive has preprocessing message trivia. - /// - /// - internal static bool HasPreprocessingMessageTrivia(this EndRegionDirectiveTriviaSyntax endRegionDirective) - { - return GetPreprocessingMessageTrivia(endRegionDirective).IsKind(SyntaxKind.PreprocessingMessageTrivia); - } - #endregion EndRegionDirectiveTriviaSyntax + RegionInfo region = SyntaxInfo.RegionInfo(endRegionDirective); - #region EnumDeclarationSyntax - /// - /// The absolute span of the braces, not including its leading and trailing trivia. - /// - /// - public static TextSpan BracesSpan(this EnumDeclarationSyntax enumDeclaration) - { - if (enumDeclaration == null) - throw new ArgumentNullException(nameof(enumDeclaration)); + return (region.Success) ? region.Directive : null; + } - return TextSpan.FromBounds( - enumDeclaration.OpenBraceToken.SpanStart, - enumDeclaration.CloseBraceToken.Span.End); - } - #endregion EnumDeclarationSyntax + /// + /// Gets preprocessing message for the specified endregion directive if such message exists. + /// + /// + public static SyntaxTrivia GetPreprocessingMessageTrivia(this EndRegionDirectiveTriviaSyntax endRegionDirective) + { + if (endRegionDirective is null) + throw new ArgumentNullException(nameof(endRegionDirective)); - #region EventDeclarationSyntax - internal static TextSpan HeaderSpan(this EventDeclarationSyntax eventDeclaration) - { - if (eventDeclaration == null) - throw new ArgumentNullException(nameof(eventDeclaration)); + SyntaxToken endOfDirective = endRegionDirective.EndOfDirectiveToken; - return TextSpan.FromBounds( - eventDeclaration.SpanStart, - eventDeclaration.Identifier.Span.End); - } - #endregion EventDeclarationSyntax + SyntaxTriviaList leading = endOfDirective.LeadingTrivia; - #region ExpressionSyntax - /// - /// Returns topmost parenthesized expression or self if the expression if not parenthesized. - /// - /// - public static ExpressionSyntax WalkUpParentheses(this ExpressionSyntax expression) - { - while (expression.IsParentKind(SyntaxKind.ParenthesizedExpression)) - expression = (ExpressionSyntax)expression.Parent; + if (leading.Count == 1) + { + SyntaxTrivia trivia = leading[0]; - return expression; - } + if (trivia.IsKind(SyntaxKind.PreprocessingMessageTrivia)) + return trivia; + } - /// - /// Returns lowest expression in parentheses or self if the expression is not parenthesized. - /// - /// - public static ExpressionSyntax WalkDownParentheses(this ExpressionSyntax expression) - { - if (expression == null) - throw new ArgumentNullException(nameof(expression)); + return default; + } - while (expression.Kind() == SyntaxKind.ParenthesizedExpression) - expression = ((ParenthesizedExpressionSyntax)expression).Expression; + /// + /// Returns true the specified endregion directive has preprocessing message trivia. + /// + /// + internal static bool HasPreprocessingMessageTrivia(this EndRegionDirectiveTriviaSyntax endRegionDirective) + { + return GetPreprocessingMessageTrivia(endRegionDirective).IsKind(SyntaxKind.PreprocessingMessageTrivia); + } + #endregion EndRegionDirectiveTriviaSyntax + + #region EnumDeclarationSyntax + /// + /// The absolute span of the braces, not including its leading and trailing trivia. + /// + /// + public static TextSpan BracesSpan(this EnumDeclarationSyntax enumDeclaration) + { + if (enumDeclaration is null) + throw new ArgumentNullException(nameof(enumDeclaration)); - return expression; - } + return TextSpan.FromBounds( + enumDeclaration.OpenBraceToken.SpanStart, + enumDeclaration.CloseBraceToken.Span.End); + } + #endregion EnumDeclarationSyntax - internal static ExpressionSyntax WalkDownParenthesesIf(this ExpressionSyntax expression, bool condition) - { - return (condition) ? WalkDownParentheses(expression) : expression; - } + #region EventDeclarationSyntax + internal static TextSpan HeaderSpan(this EventDeclarationSyntax eventDeclaration) + { + if (eventDeclaration is null) + throw new ArgumentNullException(nameof(eventDeclaration)); - internal static bool IsNumericLiteralExpression(this ExpressionSyntax expression, string valueText) - { - return expression.IsKind(SyntaxKind.NumericLiteralExpression) - && string.Equals(((LiteralExpressionSyntax)expression).Token.ValueText, valueText, StringComparison.Ordinal); - } - #endregion ExpressionSyntax + return TextSpan.FromBounds( + eventDeclaration.SpanStart, + eventDeclaration.Identifier.Span.End); + } + #endregion EventDeclarationSyntax + + #region ExpressionSyntax + /// + /// Returns topmost parenthesized expression or self if the expression if not parenthesized. + /// + /// + public static ExpressionSyntax WalkUpParentheses(this ExpressionSyntax expression) + { + while (expression.IsParentKind(SyntaxKind.ParenthesizedExpression)) + expression = (ExpressionSyntax)expression.Parent; - #region FixedStatementSyntax - internal static StatementSyntax EmbeddedStatement(this FixedStatementSyntax fixedStatement) - { - StatementSyntax statement = fixedStatement.Statement; + return expression; + } - return (statement?.Kind() == SyntaxKind.Block) ? null : statement; - } - #endregion FixedStatementSyntax + /// + /// Returns lowest expression in parentheses or self if the expression is not parenthesized. + /// + /// + public static ExpressionSyntax WalkDownParentheses(this ExpressionSyntax expression) + { + if (expression is null) + throw new ArgumentNullException(nameof(expression)); - #region ForStatementSyntax - /// - /// Absolute span of the parentheses, not including the leading and trailing trivia. - /// - /// - public static TextSpan ParenthesesSpan(this ForStatementSyntax forStatement) - { - if (forStatement == null) - throw new ArgumentNullException(nameof(forStatement)); + while (expression.Kind() == SyntaxKind.ParenthesizedExpression) + expression = ((ParenthesizedExpressionSyntax)expression).Expression; - return TextSpan.FromBounds(forStatement.OpenParenToken.SpanStart, forStatement.CloseParenToken.Span.End); - } + return expression; + } - internal static StatementSyntax EmbeddedStatement(this ForStatementSyntax forStatement) - { - StatementSyntax statement = forStatement.Statement; + internal static ExpressionSyntax WalkDownParenthesesIf(this ExpressionSyntax expression, bool condition) + { + return (condition) ? WalkDownParentheses(expression) : expression; + } - return (statement?.Kind() == SyntaxKind.Block) ? null : statement; - } - #endregion ForStatementSyntax + internal static bool IsNumericLiteralExpression(this ExpressionSyntax expression, string valueText) + { + return expression.IsKind(SyntaxKind.NumericLiteralExpression) + && string.Equals(((LiteralExpressionSyntax)expression).Token.ValueText, valueText, StringComparison.Ordinal); + } + #endregion ExpressionSyntax - #region IfStatementSyntax - internal static StatementSyntax SingleNonBlockStatementOrDefault(this IfStatementSyntax ifStatement) - { - return SingleNonBlockStatementOrDefault(ifStatement.Statement); - } + #region FixedStatementSyntax + internal static StatementSyntax EmbeddedStatement(this FixedStatementSyntax fixedStatement) + { + StatementSyntax statement = fixedStatement.Statement; - /// - /// Returns true if the specified if statement is a simple if statement. - /// Simple if statement is defined as follows: it is not a child of an else clause and it has no else clause. - /// - /// - public static bool IsSimpleIf(this IfStatementSyntax ifStatement) - { - return ifStatement?.IsParentKind(SyntaxKind.ElseClause) == false - && ifStatement.Else == null; - } + return (statement?.Kind() == SyntaxKind.Block) ? null : statement; + } + #endregion FixedStatementSyntax + + #region ForStatementSyntax + /// + /// Absolute span of the parentheses, not including the leading and trailing trivia. + /// + /// + public static TextSpan ParenthesesSpan(this ForStatementSyntax forStatement) + { + if (forStatement is null) + throw new ArgumentNullException(nameof(forStatement)); - /// - /// Returns topmost if statement of the if-else cascade the specified if statement is part of. - /// - /// - public static IfStatementSyntax GetTopmostIf(this IfStatementSyntax ifStatement) - { - if (ifStatement == null) - throw new ArgumentNullException(nameof(ifStatement)); + return TextSpan.FromBounds(forStatement.OpenParenToken.SpanStart, forStatement.CloseParenToken.Span.End); + } - while (true) + internal static StatementSyntax EmbeddedStatement(this ForStatementSyntax forStatement) { - IfStatementSyntax parentIf = GetPreviousIf(ifStatement); + StatementSyntax statement = forStatement.Statement; - if (parentIf != null) - { - ifStatement = parentIf; - } - else - { - break; - } + return (statement?.Kind() == SyntaxKind.Block) ? null : statement; } + #endregion ForStatementSyntax - return ifStatement; - } + #region IfStatementSyntax + internal static StatementSyntax SingleNonBlockStatementOrDefault(this IfStatementSyntax ifStatement) + { + return SingleNonBlockStatementOrDefault(ifStatement.Statement); + } - /// - /// Returns true if the specified if statement is not a child of an else clause. - /// - /// - public static bool IsTopmostIf(this IfStatementSyntax ifStatement) - { - return ifStatement?.IsParentKind(SyntaxKind.ElseClause) == false; - } + /// + /// Returns true if the specified if statement is a simple if statement. + /// Simple if statement is defined as follows: it is not a child of an else clause and it has no else clause. + /// + /// + public static bool IsSimpleIf(this IfStatementSyntax ifStatement) + { + return ifStatement?.IsParentKind(SyntaxKind.ElseClause) == false + && ifStatement.Else is null; + } - internal static IfStatementSyntax GetNextIf(this IfStatementSyntax ifStatement) - { - StatementSyntax statement = ifStatement.Else?.Statement; + /// + /// Returns topmost if statement of the if-else cascade the specified if statement is part of. + /// + /// + public static IfStatementSyntax GetTopmostIf(this IfStatementSyntax ifStatement) + { + if (ifStatement is null) + throw new ArgumentNullException(nameof(ifStatement)); - if (statement?.Kind() == SyntaxKind.IfStatement) - return (IfStatementSyntax)statement; + while (true) + { + IfStatementSyntax parentIf = GetPreviousIf(ifStatement); - return null; - } + if (parentIf is not null) + { + ifStatement = parentIf; + } + else + { + break; + } + } - internal static IfStatementSyntax GetPreviousIf(this IfStatementSyntax ifStatement) - { - SyntaxNode parent = ifStatement.Parent; + return ifStatement; + } - if (parent.IsKind(SyntaxKind.ElseClause)) + /// + /// Returns true if the specified if statement is not a child of an else clause. + /// + /// + public static bool IsTopmostIf(this IfStatementSyntax ifStatement) { - parent = parent.Parent; - - if (parent.IsKind(SyntaxKind.IfStatement)) - return (IfStatementSyntax)parent; + return ifStatement?.IsParentKind(SyntaxKind.ElseClause) == false; } - return null; - } - - internal static StatementSyntax EmbeddedStatement(this IfStatementSyntax ifStatement) - { - StatementSyntax statement = ifStatement.Statement; + internal static IfStatementSyntax GetNextIf(this IfStatementSyntax ifStatement) + { + StatementSyntax statement = ifStatement.Else?.Statement; - return (statement?.Kind() == SyntaxKind.Block) ? null : statement; - } + if (statement?.Kind() == SyntaxKind.IfStatement) + return (IfStatementSyntax)statement; - /// - /// Returns that enables to enumerate if-else cascade. - /// - /// - public static IfStatementCascade AsCascade(this IfStatementSyntax ifStatement) - { - if (ifStatement == null) - throw new ArgumentNullException(nameof(ifStatement)); + return null; + } - return new IfStatementCascade(ifStatement); - } + internal static IfStatementSyntax GetPreviousIf(this IfStatementSyntax ifStatement) + { + SyntaxNode parent = ifStatement.Parent; - /// - /// Returns that summarizes information about if-else cascade. - /// - /// - public static IfStatementCascadeInfo GetCascadeInfo(this IfStatementSyntax ifStatement) - { - if (ifStatement == null) - throw new ArgumentNullException(nameof(ifStatement)); + if (parent.IsKind(SyntaxKind.ElseClause)) + { + parent = parent.Parent; - return new IfStatementCascadeInfo(ifStatement); - } - #endregion IfStatementSyntax + if (parent.IsKind(SyntaxKind.IfStatement)) + return (IfStatementSyntax)parent; + } - #region IEnumerable - /// - /// Creates a list of syntax nodes from a sequence of nodes. - /// - /// - /// - public static SyntaxList ToSyntaxList(this IEnumerable nodes) where TNode : SyntaxNode - { - return List(nodes); - } + return null; + } - /// - /// Creates a separated list of syntax nodes from a sequence of nodes. - /// - /// - /// - public static SeparatedSyntaxList ToSeparatedSyntaxList(this IEnumerable nodes) where TNode : SyntaxNode - { - return SeparatedList(nodes); - } + internal static StatementSyntax EmbeddedStatement(this IfStatementSyntax ifStatement) + { + StatementSyntax statement = ifStatement.Statement; - /// - /// Creates a separated list of syntax nodes from a sequence of nodes and tokens. - /// - /// - /// - public static SeparatedSyntaxList ToSeparatedSyntaxList(this IEnumerable nodesAndTokens) where TNode : SyntaxNode - { - return SeparatedList(nodesAndTokens); - } + return (statement?.Kind() == SyntaxKind.Block) ? null : statement; + } - /// - /// Creates a list of syntax tokens from a sequence of tokens. - /// - /// - public static SyntaxTokenList ToSyntaxTokenList(this IEnumerable tokens) - { - return TokenList(tokens); - } - #endregion IEnumerable + /// + /// Returns that enables to enumerate if-else cascade. + /// + /// + public static IfStatementCascade AsCascade(this IfStatementSyntax ifStatement) + { + if (ifStatement is null) + throw new ArgumentNullException(nameof(ifStatement)); - #region IndexerDeclarationSyntax - internal static TextSpan HeaderSpan(this IndexerDeclarationSyntax indexerDeclaration) - { - int start; + return new IfStatementCascade(ifStatement); + } - SyntaxList attributeLists = indexerDeclaration.AttributeLists; + /// + /// Returns that summarizes information about if-else cascade. + /// + /// + public static IfStatementCascadeInfo GetCascadeInfo(this IfStatementSyntax ifStatement) + { + if (ifStatement is null) + throw new ArgumentNullException(nameof(ifStatement)); - if (attributeLists.Any()) + return new IfStatementCascadeInfo(ifStatement); + } + #endregion IfStatementSyntax + + #region IEnumerable + /// + /// Creates a list of syntax nodes from a sequence of nodes. + /// + /// + /// + public static SyntaxList ToSyntaxList(this IEnumerable nodes) where TNode : SyntaxNode { - SyntaxTokenList modifiers = indexerDeclaration.Modifiers; + return List(nodes); + } - start = (modifiers.Any()) - ? modifiers[0].SpanStart - : indexerDeclaration.Type.SpanStart; + /// + /// Creates a separated list of syntax nodes from a sequence of nodes. + /// + /// + /// + public static SeparatedSyntaxList ToSeparatedSyntaxList(this IEnumerable nodes) where TNode : SyntaxNode + { + return SeparatedList(nodes); } - else + + /// + /// Creates a separated list of syntax nodes from a sequence of nodes and tokens. + /// + /// + /// + public static SeparatedSyntaxList ToSeparatedSyntaxList(this IEnumerable nodesAndTokens) where TNode : SyntaxNode { - start = indexerDeclaration.SpanStart; + return SeparatedList(nodesAndTokens); } - return TextSpan.FromBounds( - start, - indexerDeclaration.ParameterList?.Span.End - ?? indexerDeclaration.ThisKeyword.Span.End); - } + /// + /// Creates a list of syntax tokens from a sequence of tokens. + /// + /// + public static SyntaxTokenList ToSyntaxTokenList(this IEnumerable tokens) + { + return TokenList(tokens); + } + #endregion IEnumerable - /// - /// Returns a get accessor that is contained in the specified indexer declaration. - /// - /// - public static AccessorDeclarationSyntax Getter(this IndexerDeclarationSyntax indexerDeclaration) - { - if (indexerDeclaration == null) - throw new ArgumentNullException(nameof(indexerDeclaration)); + #region IndexerDeclarationSyntax + internal static TextSpan HeaderSpan(this IndexerDeclarationSyntax indexerDeclaration) + { + int start; - return indexerDeclaration - .AccessorList? - .Getter(); - } + SyntaxList attributeLists = indexerDeclaration.AttributeLists; - /// - /// Returns a set accessor that is contained in the specified indexer declaration. - /// - /// - public static AccessorDeclarationSyntax Setter(this IndexerDeclarationSyntax indexerDeclaration) - { - if (indexerDeclaration == null) - throw new ArgumentNullException(nameof(indexerDeclaration)); + if (attributeLists.Any()) + { + SyntaxTokenList modifiers = indexerDeclaration.Modifiers; - return indexerDeclaration - .AccessorList? - .Setter(); - } - #endregion IndexerDeclarationSyntax + start = (modifiers.Any()) + ? modifiers[0].SpanStart + : indexerDeclaration.Type.SpanStart; + } + else + { + start = indexerDeclaration.SpanStart; + } - #region InterfaceDeclarationSyntax - /// - /// The absolute span of the braces, not including it leading and trailing trivia. - /// - /// - public static TextSpan BracesSpan(this InterfaceDeclarationSyntax interfaceDeclaration) - { - if (interfaceDeclaration == null) - throw new ArgumentNullException(nameof(interfaceDeclaration)); + return TextSpan.FromBounds( + start, + indexerDeclaration.ParameterList?.Span.End + ?? indexerDeclaration.ThisKeyword.Span.End); + } - return TextSpan.FromBounds( - interfaceDeclaration.OpenBraceToken.SpanStart, - interfaceDeclaration.CloseBraceToken.Span.End); - } + /// + /// Returns a get accessor that is contained in the specified indexer declaration. + /// + /// + public static AccessorDeclarationSyntax Getter(this IndexerDeclarationSyntax indexerDeclaration) + { + if (indexerDeclaration is null) + throw new ArgumentNullException(nameof(indexerDeclaration)); - /// - /// Creates a new with the members updated. - /// - /// - /// - public static InterfaceDeclarationSyntax WithMembers( - this InterfaceDeclarationSyntax interfaceDeclaration, - MemberDeclarationSyntax member) - { - if (interfaceDeclaration == null) - throw new ArgumentNullException(nameof(interfaceDeclaration)); + return indexerDeclaration + .AccessorList? + .Getter(); + } - return interfaceDeclaration.WithMembers(SingletonList(member)); - } + /// + /// Returns a set accessor that is contained in the specified indexer declaration. + /// + /// + public static AccessorDeclarationSyntax Setter(this IndexerDeclarationSyntax indexerDeclaration) + { + if (indexerDeclaration is null) + throw new ArgumentNullException(nameof(indexerDeclaration)); - /// - /// Creates a new with the members updated. - /// - /// - /// - public static InterfaceDeclarationSyntax WithMembers( - this InterfaceDeclarationSyntax interfaceDeclaration, - IEnumerable members) - { - if (interfaceDeclaration == null) - throw new ArgumentNullException(nameof(interfaceDeclaration)); + return indexerDeclaration + .AccessorList? + .Setter(); + } + #endregion IndexerDeclarationSyntax + + #region InterfaceDeclarationSyntax + /// + /// The absolute span of the braces, not including it leading and trailing trivia. + /// + /// + public static TextSpan BracesSpan(this InterfaceDeclarationSyntax interfaceDeclaration) + { + if (interfaceDeclaration is null) + throw new ArgumentNullException(nameof(interfaceDeclaration)); - return interfaceDeclaration.WithMembers(List(members)); - } - #endregion InterfaceDeclarationSyntax + return TextSpan.FromBounds( + interfaceDeclaration.OpenBraceToken.SpanStart, + interfaceDeclaration.CloseBraceToken.Span.End); + } - #region InterpolatedStringExpressionSyntax - /// - /// Returns true if the specified interpolated string is a verbatim. - /// - /// - public static bool IsVerbatim(this InterpolatedStringExpressionSyntax interpolatedString) - { - return interpolatedString?.StringStartToken.ValueText.Contains("@") == true; - } - #endregion InterpolatedStringExpressionSyntax + /// + /// Creates a new with the members updated. + /// + /// + /// + public static InterfaceDeclarationSyntax WithMembers( + this InterfaceDeclarationSyntax interfaceDeclaration, + MemberDeclarationSyntax member) + { + if (interfaceDeclaration is null) + throw new ArgumentNullException(nameof(interfaceDeclaration)); - #region InvocationExpressionSyntax - internal static ExpressionSyntax WalkDownMethodChain( - this InvocationExpressionSyntax invocationExpression, - bool walkInvocation = true, - bool walkElementAccess = true) - { - ExpressionSyntax expression = invocationExpression; - ExpressionSyntax current = invocationExpression.Expression; + return interfaceDeclaration.WithMembers(SingletonList(member)); + } - while (current.Kind() == SyntaxKind.SimpleMemberAccessExpression) + /// + /// Creates a new with the members updated. + /// + /// + /// + public static InterfaceDeclarationSyntax WithMembers( + this InterfaceDeclarationSyntax interfaceDeclaration, + IEnumerable members) { - var memberAccessExpression = (MemberAccessExpressionSyntax)current; + if (interfaceDeclaration is null) + throw new ArgumentNullException(nameof(interfaceDeclaration)); - current = memberAccessExpression.Expression; + return interfaceDeclaration.WithMembers(List(members)); + } + #endregion InterfaceDeclarationSyntax + + #region InterpolatedStringExpressionSyntax + /// + /// Returns true if the specified interpolated string is a verbatim. + /// + /// + public static bool IsVerbatim(this InterpolatedStringExpressionSyntax interpolatedString) + { + return interpolatedString?.StringStartToken.ValueText.Contains("@") == true; + } + #endregion InterpolatedStringExpressionSyntax - SyntaxKind kind = current.Kind(); + #region InvocationExpressionSyntax + internal static ExpressionSyntax WalkDownMethodChain( + this InvocationExpressionSyntax invocationExpression, + bool walkInvocation = true, + bool walkElementAccess = true) + { + ExpressionSyntax expression = invocationExpression; + ExpressionSyntax current = invocationExpression.Expression; - if (kind == SyntaxKind.InvocationExpression) + while (current.Kind() == SyntaxKind.SimpleMemberAccessExpression) { - if (walkInvocation) - { - invocationExpression = (InvocationExpressionSyntax)current; - expression = invocationExpression; - current = invocationExpression.Expression; - } - else + var memberAccessExpression = (MemberAccessExpressionSyntax)current; + + current = memberAccessExpression.Expression; + + SyntaxKind kind = current.Kind(); + + if (kind == SyntaxKind.InvocationExpression) { - break; + if (walkInvocation) + { + invocationExpression = (InvocationExpressionSyntax)current; + expression = invocationExpression; + current = invocationExpression.Expression; + } + else + { + break; + } } - } - else if (kind == SyntaxKind.ElementAccessExpression) - { - if (walkElementAccess) + else if (kind == SyntaxKind.ElementAccessExpression) { - var elementAccess = (ElementAccessExpressionSyntax)current; - expression = elementAccess; - current = elementAccess.Expression; + if (walkElementAccess) + { + var elementAccess = (ElementAccessExpressionSyntax)current; + expression = elementAccess; + current = elementAccess.Expression; + } + else + { + break; + } } else { break; } } - else - { - break; - } - } - - return expression; - } - #endregion InvocationExpressionSyntax - - #region LiteralExpressionSyntax - /// - /// Returns true if the specified literal expression is a hexadecimal numeric literal expression. - /// - /// - public static bool IsHexNumericLiteral(this LiteralExpressionSyntax literalExpression) - { - return literalExpression.IsKind(SyntaxKind.NumericLiteralExpression) - && literalExpression.Token.Text.StartsWith("0x", StringComparison.OrdinalIgnoreCase); - } - #endregion LiteralExpressionSyntax - - #region LocalFunctionStatementSyntax - /// - /// Returns local function body or an expression body if the body is null. - /// - /// - public static CSharpSyntaxNode BodyOrExpressionBody(this LocalFunctionStatementSyntax localFunctionStatement) - { - if (localFunctionStatement == null) - throw new ArgumentNullException(nameof(localFunctionStatement)); - return localFunctionStatement.Body ?? (CSharpSyntaxNode)localFunctionStatement.ExpressionBody; - } - - /// - /// Returns true if the specified local function' return type is . - /// - /// - public static bool ReturnsVoid(this LocalFunctionStatementSyntax localFunctionStatement) - { - return localFunctionStatement?.ReturnType?.IsVoid() == true; - } - - /// - /// Returns true if the specified local function contains yield statement. Nested local functions are excluded. - /// - /// - public static bool ContainsYield(this LocalFunctionStatementSyntax localFunctionStatement) - { - if (localFunctionStatement == null) - throw new ArgumentNullException(nameof(localFunctionStatement)); - - return localFunctionStatement.Body?.ContainsYield() == true; - } - - internal static TextSpan HeaderSpan(this LocalFunctionStatementSyntax localFunction) - { - return TextSpan.FromBounds( - localFunction.SpanStart, - localFunction.ConstraintClauses.LastOrDefault()?.Span.End - ?? localFunction.ParameterList?.Span.End - ?? localFunction.Identifier.Span.End); - } - #endregion LocalFunctionStatementSyntax - - #region LockStatementSyntax - internal static StatementSyntax EmbeddedStatement(this LockStatementSyntax lockStatement) - { - StatementSyntax statement = lockStatement.Statement; - - return (statement?.Kind() == SyntaxKind.Block) ? null : statement; - } - #endregion LockStatementSyntax - - #region MemberDeclarationSyntax - /// - /// Returns single-line documentation comment that is part of the specified declaration. - /// - /// - public static SyntaxTrivia GetSingleLineDocumentationCommentTrivia(this MemberDeclarationSyntax member) - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - foreach (SyntaxTrivia trivia in member.GetLeadingTrivia()) - { - if (trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)) - return trivia; + return expression; } - - return default; - } - - /// - /// Returns documentation comment that is part of the specified declaration. - /// - /// - public static SyntaxTrivia GetDocumentationCommentTrivia(this MemberDeclarationSyntax member) - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - foreach (SyntaxTrivia trivia in member.GetLeadingTrivia()) + #endregion InvocationExpressionSyntax + + #region LiteralExpressionSyntax + /// + /// Returns true if the specified literal expression is a hexadecimal numeric literal expression. + /// + /// + public static bool IsHexNumericLiteral(this LiteralExpressionSyntax literalExpression) { - if (trivia.IsDocumentationCommentTrivia()) - return trivia; + return literalExpression.IsKind(SyntaxKind.NumericLiteralExpression) + && literalExpression.Token.Text.StartsWith("0x", StringComparison.OrdinalIgnoreCase); } + #endregion LiteralExpressionSyntax + + #region LocalFunctionStatementSyntax + /// + /// Returns local function body or an expression body if the body is null. + /// + /// + public static CSharpSyntaxNode BodyOrExpressionBody(this LocalFunctionStatementSyntax localFunctionStatement) + { + if (localFunctionStatement is null) + throw new ArgumentNullException(nameof(localFunctionStatement)); - return default; - } - - /// - /// Returns single-line documentation comment syntax that is part of the specified declaration. - /// - /// - public static DocumentationCommentTriviaSyntax GetSingleLineDocumentationComment(this MemberDeclarationSyntax member) - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - SyntaxNode structure = member.GetSingleLineDocumentationCommentTrivia().GetStructure(); - - if (structure.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)) - return (DocumentationCommentTriviaSyntax)structure; - - return null; - } - - /// - /// Returns documentation comment syntax that is part of the specified declaration. - /// - /// - public static DocumentationCommentTriviaSyntax GetDocumentationComment(this MemberDeclarationSyntax member) - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - SyntaxTrivia trivia = member.GetDocumentationCommentTrivia(); + return localFunctionStatement.Body ?? (CSharpSyntaxNode)localFunctionStatement.ExpressionBody; + } - if (trivia.IsDocumentationCommentTrivia() - && trivia.GetStructure() is DocumentationCommentTriviaSyntax comment - && SyntaxFacts.IsDocumentationCommentTrivia(comment.Kind())) + /// + /// Returns true if the specified local function' return type is . + /// + /// + public static bool ReturnsVoid(this LocalFunctionStatementSyntax localFunctionStatement) { - return comment; + return localFunctionStatement?.ReturnType?.IsVoid() == true; } - return null; - } - - /// - /// Returns true if the specified declaration has a single-line documentation comment. - /// - /// - public static bool HasSingleLineDocumentationComment(this MemberDeclarationSyntax member) - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - return member - .GetLeadingTrivia() - .Any(f => f.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)); - } - - /// - /// Returns true if the specified declaration has a documentation comment. - /// - /// - public static bool HasDocumentationComment(this MemberDeclarationSyntax member) - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - return member - .GetLeadingTrivia() - .Any(f => IsDocumentationCommentTrivia(f)); - } - - internal static TMember WithNewSingleLineDocumentationComment( - this TMember member, - DocumentationCommentGeneratorSettings settings = null) where TMember : MemberDeclarationSyntax - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - DocumentationCommentInserter inserter = DocumentationCommentInserter.Create(member); - - settings ??= DocumentationCommentGeneratorSettings.Default; - - settings = settings.WithIndentation(inserter.Indent); - - SyntaxTriviaList comment = DocumentationCommentGenerator.Generate(member, settings); - - SyntaxTriviaList newLeadingTrivia = inserter.InsertRange(comment); - - return member.WithLeadingTrivia(newLeadingTrivia); - } - - internal static TMember WithBaseOrNewSingleLineDocumentationComment( - this TMember member, - SemanticModel semanticModel, - DocumentationCommentGeneratorSettings settings = null, - CancellationToken cancellationToken = default) where TMember : MemberDeclarationSyntax - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - if (DocumentationCommentGenerator.CanGenerateFromBase(member.Kind())) + /// + /// Returns true if the specified local function contains yield statement. Nested local functions are excluded. + /// + /// + public static bool ContainsYield(this LocalFunctionStatementSyntax localFunctionStatement) { - DocumentationCommentData data = DocumentationCommentGenerator.GenerateFromBase(member, semanticModel, cancellationToken); + if (localFunctionStatement is null) + throw new ArgumentNullException(nameof(localFunctionStatement)); - if (data.Success) - { - SyntaxTrivia comment = DocumentationCommentTriviaFactory.Parse(data.RawXml, semanticModel, member.SpanStart); - - return member.WithDocumentationComment(comment, indent: true); - } + return localFunctionStatement.Body?.ContainsYield() == true; } - return WithNewSingleLineDocumentationComment(member, settings); - } - - internal static TMember WithDocumentationComment( - this TMember member, - SyntaxTrivia comment, - bool indent = false) where TMember : MemberDeclarationSyntax - { - if (member == null) - throw new ArgumentNullException(nameof(member)); - - DocumentationCommentInserter inserter = DocumentationCommentInserter.Create(member); - - SyntaxTriviaList newLeadingTrivia = inserter.Insert(comment, indent: indent); - - return member.WithLeadingTrivia(newLeadingTrivia); - } - - /// - /// Returns true if the specified method contains yield statement. Nested local functions are excluded. - /// - /// - public static bool ContainsYield(this MethodDeclarationSyntax methodDeclaration) - { - if (methodDeclaration == null) - throw new ArgumentNullException(nameof(methodDeclaration)); - - return methodDeclaration.Body?.ContainsYield() == true; - } - #endregion MemberDeclarationSyntax - - #region MethodDeclarationSyntax - /// - /// Returns true if the specified method return type is . - /// - /// - public static bool ReturnsVoid(this MethodDeclarationSyntax methodDeclaration) - { - return methodDeclaration?.ReturnType?.IsVoid() == true; - } - - internal static TextSpan HeaderSpan(this MethodDeclarationSyntax methodDeclaration) - { - int start; - - SyntaxList attributeLists = methodDeclaration.AttributeLists; + internal static TextSpan HeaderSpan(this LocalFunctionStatementSyntax localFunction) + { + return TextSpan.FromBounds( + localFunction.SpanStart, + localFunction.ConstraintClauses.LastOrDefault()?.Span.End + ?? localFunction.ParameterList?.Span.End + ?? localFunction.Identifier.Span.End); + } + #endregion LocalFunctionStatementSyntax - if (attributeLists.Any()) + #region LockStatementSyntax + internal static StatementSyntax EmbeddedStatement(this LockStatementSyntax lockStatement) { - SyntaxTokenList modifiers = methodDeclaration.Modifiers; + StatementSyntax statement = lockStatement.Statement; - start = (modifiers.Any()) - ? modifiers[0].SpanStart - : methodDeclaration.ReturnType.SpanStart; + return (statement?.Kind() == SyntaxKind.Block) ? null : statement; } - else + #endregion LockStatementSyntax + + #region MemberDeclarationSyntax + /// + /// Returns single-line documentation comment that is part of the specified declaration. + /// + /// + public static SyntaxTrivia GetSingleLineDocumentationCommentTrivia(this MemberDeclarationSyntax member) { - start = methodDeclaration.SpanStart; - } + if (member is null) + throw new ArgumentNullException(nameof(member)); - return TextSpan.FromBounds( - start, - methodDeclaration.ConstraintClauses.LastOrDefault()?.Span.End - ?? methodDeclaration.ParameterList?.Span.End - ?? methodDeclaration.Identifier.Span.End); - } - - /// - /// Returns method body or an expression body if the body is null. - /// - /// - public static CSharpSyntaxNode BodyOrExpressionBody(this MethodDeclarationSyntax methodDeclaration) - { - if (methodDeclaration == null) - throw new ArgumentNullException(nameof(methodDeclaration)); + foreach (SyntaxTrivia trivia in member.GetLeadingTrivia()) + { + if (trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)) + return trivia; + } - return methodDeclaration.Body ?? (CSharpSyntaxNode)methodDeclaration.ExpressionBody; - } - #endregion MethodDeclarationSyntax + return default; + } - #region NamespaceDeclarationSyntax - /// - /// Creates a new with the members updated. - /// - /// - /// - public static NamespaceDeclarationSyntax WithMembers( - this NamespaceDeclarationSyntax namespaceDeclaration, - MemberDeclarationSyntax member) - { - if (namespaceDeclaration == null) - throw new ArgumentNullException(nameof(namespaceDeclaration)); + /// + /// Returns documentation comment that is part of the specified declaration. + /// + /// + public static SyntaxTrivia GetDocumentationCommentTrivia(this MemberDeclarationSyntax member) + { + if (member is null) + throw new ArgumentNullException(nameof(member)); - return namespaceDeclaration.WithMembers(SingletonList(member)); - } + foreach (SyntaxTrivia trivia in member.GetLeadingTrivia()) + { + if (trivia.IsDocumentationCommentTrivia()) + return trivia; + } - /// - /// Creates a new with the members updated. - /// - /// - /// - public static NamespaceDeclarationSyntax WithMembers( - this NamespaceDeclarationSyntax namespaceDeclaration, - IEnumerable members) - { - if (namespaceDeclaration == null) - throw new ArgumentNullException(nameof(namespaceDeclaration)); + return default; + } - return namespaceDeclaration.WithMembers(List(members)); - } + /// + /// Returns single-line documentation comment syntax that is part of the specified declaration. + /// + /// + public static DocumentationCommentTriviaSyntax GetSingleLineDocumentationComment(this MemberDeclarationSyntax member) + { + if (member is null) + throw new ArgumentNullException(nameof(member)); - /// - /// The absolute span of the braces, not including leading and trailing trivia. - /// - /// - public static TextSpan BracesSpan(this NamespaceDeclarationSyntax namespaceDeclaration) - { - if (namespaceDeclaration == null) - throw new ArgumentNullException(nameof(namespaceDeclaration)); + SyntaxNode structure = member.GetSingleLineDocumentationCommentTrivia().GetStructure(); - return TextSpan.FromBounds( - namespaceDeclaration.OpenBraceToken.SpanStart, - namespaceDeclaration.CloseBraceToken.Span.End); - } - #endregion NamespaceDeclarationSyntax + if (structure.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)) + return (DocumentationCommentTriviaSyntax)structure; - #region OperatorDeclarationSyntax - /// - /// Returns operator body or an expression body if the body is null. - /// - /// - public static CSharpSyntaxNode BodyOrExpressionBody(this OperatorDeclarationSyntax operatorDeclaration) - { - if (operatorDeclaration == null) - throw new ArgumentNullException(nameof(operatorDeclaration)); + return null; + } - return operatorDeclaration.Body ?? (CSharpSyntaxNode)operatorDeclaration.ExpressionBody; - } + /// + /// Returns documentation comment syntax that is part of the specified declaration. + /// + /// + public static DocumentationCommentTriviaSyntax GetDocumentationComment(this MemberDeclarationSyntax member) + { + if (member is null) + throw new ArgumentNullException(nameof(member)); - internal static TextSpan HeaderSpan(this OperatorDeclarationSyntax operatorDeclaration) - { - int start; + SyntaxTrivia trivia = member.GetDocumentationCommentTrivia(); + + if (trivia.IsDocumentationCommentTrivia() + && trivia.GetStructure() is DocumentationCommentTriviaSyntax comment + && SyntaxFacts.IsDocumentationCommentTrivia(comment.Kind())) + { + return comment; + } - SyntaxList attributeLists = operatorDeclaration.AttributeLists; + return null; + } - if (attributeLists.Any()) + /// + /// Returns true if the specified declaration has a single-line documentation comment. + /// + /// + public static bool HasSingleLineDocumentationComment(this MemberDeclarationSyntax member) { - SyntaxTokenList modifiers = operatorDeclaration.Modifiers; + if (member is null) + throw new ArgumentNullException(nameof(member)); - start = (modifiers.Any()) - ? modifiers[0].SpanStart - : operatorDeclaration.ReturnType.SpanStart; + return member + .GetLeadingTrivia() + .Any(f => f.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)); } - else + + /// + /// Returns true if the specified declaration has a documentation comment. + /// + /// + public static bool HasDocumentationComment(this MemberDeclarationSyntax member) { - start = operatorDeclaration.SpanStart; + if (member is null) + throw new ArgumentNullException(nameof(member)); + + return member + .GetLeadingTrivia() + .Any(f => IsDocumentationCommentTrivia(f)); } - return TextSpan.FromBounds( - start, - operatorDeclaration.ParameterList?.Span.End - ?? operatorDeclaration.OperatorToken.Span.End); - } - #endregion OperatorDeclarationSyntax + internal static TMember WithNewSingleLineDocumentationComment( + this TMember member, + DocumentationCommentGeneratorSettings settings = null) where TMember : MemberDeclarationSyntax + { + if (member is null) + throw new ArgumentNullException(nameof(member)); - #region ParameterSyntax - /// - /// Returns true if the specified parameter has "params" modifier. - /// - /// - public static bool IsParams(this ParameterSyntax parameter) - { - return parameter?.Modifiers.Contains(SyntaxKind.ParamsKeyword) == true; - } - #endregion ParameterSyntax + DocumentationCommentInserter inserter = DocumentationCommentInserter.Create(member); - #region PropertyDeclarationSyntax - internal static TextSpan HeaderSpan(this PropertyDeclarationSyntax propertyDeclaration) - { - int start; + settings ??= DocumentationCommentGeneratorSettings.Default; - SyntaxList attributeLists = propertyDeclaration.AttributeLists; + settings = settings.WithIndentation(inserter.Indent); - if (attributeLists.Any()) - { - SyntaxTokenList modifiers = propertyDeclaration.Modifiers; + SyntaxTriviaList comment = DocumentationCommentGenerator.Generate(member, settings); - start = (modifiers.Any()) - ? modifiers[0].SpanStart - : propertyDeclaration.Type.SpanStart; + SyntaxTriviaList newLeadingTrivia = inserter.InsertRange(comment); + + return member.WithLeadingTrivia(newLeadingTrivia); } - else + + internal static TMember WithBaseOrNewSingleLineDocumentationComment( + this TMember member, + SemanticModel semanticModel, + DocumentationCommentGeneratorSettings settings = null, + CancellationToken cancellationToken = default) where TMember : MemberDeclarationSyntax { - start = propertyDeclaration.SpanStart; - } + if (member is null) + throw new ArgumentNullException(nameof(member)); - return TextSpan.FromBounds( - start, - propertyDeclaration.Identifier.Span.End); - } + if (DocumentationCommentGenerator.CanGenerateFromBase(member.Kind())) + { + DocumentationCommentData data = DocumentationCommentGenerator.GenerateFromBase(member, semanticModel, cancellationToken); - /// - /// Returns property get accessor, if any. - /// - /// - public static AccessorDeclarationSyntax Getter(this PropertyDeclarationSyntax propertyDeclaration) - { - if (propertyDeclaration == null) - throw new ArgumentNullException(nameof(propertyDeclaration)); + if (data.Success) + { + SyntaxTrivia comment = DocumentationCommentTriviaFactory.Parse(data.RawXml, semanticModel, member.SpanStart); - return propertyDeclaration.AccessorList?.Getter(); - } + return member.WithDocumentationComment(comment, indent: true); + } + } - /// - /// Returns property set accessor, if any. - /// - /// - public static AccessorDeclarationSyntax Setter(this PropertyDeclarationSyntax propertyDeclaration) - { - if (propertyDeclaration == null) - throw new ArgumentNullException(nameof(propertyDeclaration)); + return WithNewSingleLineDocumentationComment(member, settings); + } - return propertyDeclaration.AccessorList?.Setter(); - } + internal static TMember WithDocumentationComment( + this TMember member, + SyntaxTrivia comment, + bool indent = false) where TMember : MemberDeclarationSyntax + { + if (member is null) + throw new ArgumentNullException(nameof(member)); - internal static PropertyDeclarationSyntax ReplaceAccessor( - this PropertyDeclarationSyntax propertyDeclaration, - AccessorDeclarationSyntax accessor, - AccessorDeclarationSyntax newAccessor) - { - return propertyDeclaration.WithAccessorList( - propertyDeclaration.AccessorList.WithAccessors( - propertyDeclaration.AccessorList.Accessors.Replace(accessor, newAccessor))); - } - #endregion PropertyDeclarationSyntax + DocumentationCommentInserter inserter = DocumentationCommentInserter.Create(member); - #region RecordDeclarationSyntax - /// - /// Creates a new with the members updated. - /// - /// - /// - public static RecordDeclarationSyntax WithMembers( - this RecordDeclarationSyntax recordDeclaration, - MemberDeclarationSyntax member) - { - if (recordDeclaration == null) - throw new ArgumentNullException(nameof(recordDeclaration)); + SyntaxTriviaList newLeadingTrivia = inserter.Insert(comment, indent: indent); - return recordDeclaration.WithMembers(SingletonList(member)); - } + return member.WithLeadingTrivia(newLeadingTrivia); + } - /// - /// Creates a new with the members updated. - /// - /// - /// - public static RecordDeclarationSyntax WithMembers( - this RecordDeclarationSyntax recordDeclaration, - IEnumerable members) - { - if (recordDeclaration == null) - throw new ArgumentNullException(nameof(recordDeclaration)); + /// + /// Returns true if the specified method contains yield statement. Nested local functions are excluded. + /// + /// + public static bool ContainsYield(this MethodDeclarationSyntax methodDeclaration) + { + if (methodDeclaration is null) + throw new ArgumentNullException(nameof(methodDeclaration)); - return recordDeclaration.WithMembers(List(members)); - } + return methodDeclaration.Body?.ContainsYield() == true; + } + #endregion MemberDeclarationSyntax + + #region MethodDeclarationSyntax + /// + /// Returns true if the specified method return type is . + /// + /// + public static bool ReturnsVoid(this MethodDeclarationSyntax methodDeclaration) + { + return methodDeclaration?.ReturnType?.IsVoid() == true; + } - /// - /// The absolute span of the braces, not including its leading and trailing trivia. - /// - /// - public static TextSpan BracesSpan(this RecordDeclarationSyntax recordDeclaration) - { - if (recordDeclaration == null) - throw new ArgumentNullException(nameof(recordDeclaration)); + internal static TextSpan HeaderSpan(this MethodDeclarationSyntax methodDeclaration) + { + int start; - return TextSpan.FromBounds( - recordDeclaration.OpenBraceToken.SpanStart, - recordDeclaration.CloseBraceToken.Span.End); - } - #endregion RecordDeclarationSyntax + SyntaxList attributeLists = methodDeclaration.AttributeLists; - #region RegionDirectiveTriviaSyntax - /// - /// Returns endregion directive that is related to the specified region directive. Returns null if no matching endregion directive is found. - /// - /// - public static EndRegionDirectiveTriviaSyntax GetEndRegionDirective(this RegionDirectiveTriviaSyntax regionDirective) - { - if (regionDirective == null) - throw new ArgumentNullException(nameof(regionDirective)); + if (attributeLists.Any()) + { + SyntaxTokenList modifiers = methodDeclaration.Modifiers; - RegionInfo region = SyntaxInfo.RegionInfo(regionDirective); + start = (modifiers.Any()) + ? modifiers[0].SpanStart + : methodDeclaration.ReturnType.SpanStart; + } + else + { + start = methodDeclaration.SpanStart; + } - return (region.Success) ? region.EndDirective : null; - } + return TextSpan.FromBounds( + start, + methodDeclaration.ConstraintClauses.LastOrDefault()?.Span.End + ?? methodDeclaration.ParameterList?.Span.End + ?? methodDeclaration.Identifier.Span.End); + } - /// - /// Gets preprocessing message for the specified region directive if such message exists. - /// - /// - public static SyntaxTrivia GetPreprocessingMessageTrivia(this RegionDirectiveTriviaSyntax regionDirective) - { - if (regionDirective == null) - throw new ArgumentNullException(nameof(regionDirective)); + /// + /// Returns method body or an expression body if the body is null. + /// + /// + public static CSharpSyntaxNode BodyOrExpressionBody(this MethodDeclarationSyntax methodDeclaration) + { + if (methodDeclaration is null) + throw new ArgumentNullException(nameof(methodDeclaration)); - SyntaxToken endOfDirective = regionDirective.EndOfDirectiveToken; + return methodDeclaration.Body ?? (CSharpSyntaxNode)methodDeclaration.ExpressionBody; + } + #endregion MethodDeclarationSyntax + + #region NamespaceDeclarationSyntax + /// + /// Creates a new with the members updated. + /// + /// + /// + public static NamespaceDeclarationSyntax WithMembers( + this NamespaceDeclarationSyntax namespaceDeclaration, + MemberDeclarationSyntax member) + { + if (namespaceDeclaration is null) + throw new ArgumentNullException(nameof(namespaceDeclaration)); - SyntaxTriviaList leading = endOfDirective.LeadingTrivia; + return namespaceDeclaration.WithMembers(SingletonList(member)); + } - if (leading.Count == 1) + /// + /// Creates a new with the members updated. + /// + /// + /// + public static NamespaceDeclarationSyntax WithMembers( + this NamespaceDeclarationSyntax namespaceDeclaration, + IEnumerable members) { - SyntaxTrivia trivia = leading[0]; + if (namespaceDeclaration is null) + throw new ArgumentNullException(nameof(namespaceDeclaration)); - if (trivia.IsKind(SyntaxKind.PreprocessingMessageTrivia)) - return trivia; + return namespaceDeclaration.WithMembers(List(members)); } - return default; - } - - /// - /// Returns true the specified region directive has preprocessing message trivia. - /// - /// - internal static bool HasPreprocessingMessageTrivia(this RegionDirectiveTriviaSyntax regionDirective) - { - return GetPreprocessingMessageTrivia(regionDirective).IsKind(SyntaxKind.PreprocessingMessageTrivia); - } - #endregion RegionDirectiveTriviaSyntax + /// + /// The absolute span of the braces, not including leading and trailing trivia. + /// + /// + public static TextSpan BracesSpan(this NamespaceDeclarationSyntax namespaceDeclaration) + { + if (namespaceDeclaration is null) + throw new ArgumentNullException(nameof(namespaceDeclaration)); - #region SeparatedSyntaxList - /// - /// Searches for a node of the specified kind and returns the zero-based index of the last occurrence within the entire . - /// - /// - /// - /// - public static int LastIndexOf(this SeparatedSyntaxList list, SyntaxKind kind) where TNode : SyntaxNode - { - return list.LastIndexOf(f => f.IsKind(kind)); - } + return TextSpan.FromBounds( + namespaceDeclaration.OpenBraceToken.SpanStart, + namespaceDeclaration.CloseBraceToken.Span.End); + } + #endregion NamespaceDeclarationSyntax + + #region OperatorDeclarationSyntax + /// + /// Returns operator body or an expression body if the body is null. + /// + /// + public static CSharpSyntaxNode BodyOrExpressionBody(this OperatorDeclarationSyntax operatorDeclaration) + { + if (operatorDeclaration is null) + throw new ArgumentNullException(nameof(operatorDeclaration)); - /// - /// Searches for a node of the specified kind and returns the zero-based index of the first occurrence within the entire . - /// - /// - /// - /// - public static bool Contains(this SeparatedSyntaxList list, SyntaxKind kind) where TNode : SyntaxNode - { - return list.IndexOf(kind) != -1; - } + return operatorDeclaration.Body ?? (CSharpSyntaxNode)operatorDeclaration.ExpressionBody; + } - /// - /// Searches for a node of the specified kind and returns the first occurrence within the entire . - /// - /// - /// - /// - public static TNode Find(this SeparatedSyntaxList list, SyntaxKind kind) where TNode : SyntaxNode - { - int index = list.IndexOf(kind); + internal static TextSpan HeaderSpan(this OperatorDeclarationSyntax operatorDeclaration) + { + int start; - if (index != -1) - return list[index]; + SyntaxList attributeLists = operatorDeclaration.AttributeLists; - return default; - } + if (attributeLists.Any()) + { + SyntaxTokenList modifiers = operatorDeclaration.Modifiers; - internal static bool IsSingleLine( - this SeparatedSyntaxList list, - bool includeExteriorTrivia = true, - bool trim = true, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - TextSpan span = GetSpan(list, includeExteriorTrivia, trim); + start = (modifiers.Any()) + ? modifiers[0].SpanStart + : operatorDeclaration.ReturnType.SpanStart; + } + else + { + start = operatorDeclaration.SpanStart; + } - if (span.IsEmpty) - return false; + return TextSpan.FromBounds( + start, + operatorDeclaration.ParameterList?.Span.End + ?? operatorDeclaration.OperatorToken.Span.End); + } + #endregion OperatorDeclarationSyntax + + #region ParameterSyntax + /// + /// Returns true if the specified parameter has "params" modifier. + /// + /// + public static bool IsParams(this ParameterSyntax parameter) + { + return parameter?.Modifiers.Contains(SyntaxKind.ParamsKeyword) == true; + } + #endregion ParameterSyntax - SyntaxTree tree = list[0].SyntaxTree; + #region PropertyDeclarationSyntax + internal static TextSpan HeaderSpan(this PropertyDeclarationSyntax propertyDeclaration) + { + int start; - if (tree == null) - return false; + SyntaxList attributeLists = propertyDeclaration.AttributeLists; - return span.IsSingleLine(tree, cancellationToken); - } + if (attributeLists.Any()) + { + SyntaxTokenList modifiers = propertyDeclaration.Modifiers; - internal static bool IsMultiLine( - this SeparatedSyntaxList list, - bool includeExteriorTrivia = true, - bool trim = true, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - TextSpan span = GetSpan(list, includeExteriorTrivia, trim); + start = (modifiers.Any()) + ? modifiers[0].SpanStart + : propertyDeclaration.Type.SpanStart; + } + else + { + start = propertyDeclaration.SpanStart; + } - if (span.IsEmpty) - return false; + return TextSpan.FromBounds( + start, + propertyDeclaration.Identifier.Span.End); + } - SyntaxTree tree = list[0].SyntaxTree; + /// + /// Returns property get accessor, if any. + /// + /// + public static AccessorDeclarationSyntax Getter(this PropertyDeclarationSyntax propertyDeclaration) + { + if (propertyDeclaration is null) + throw new ArgumentNullException(nameof(propertyDeclaration)); - if (tree == null) - return false; + return propertyDeclaration.AccessorList?.Getter(); + } - return span.IsMultiLine(tree, cancellationToken); - } + /// + /// Returns property set accessor, if any. + /// + /// + public static AccessorDeclarationSyntax Setter(this PropertyDeclarationSyntax propertyDeclaration) + { + if (propertyDeclaration is null) + throw new ArgumentNullException(nameof(propertyDeclaration)); - internal static TextSpan GetSpan( - this SeparatedSyntaxList list, - bool includeExteriorTrivia = true, - bool trim = true) where TNode : SyntaxNode - { - if (!list.Any()) - return default; + return propertyDeclaration.AccessorList?.Setter(); + } - return TextSpan.FromBounds( - GetStartIndex(list[0], includeExteriorTrivia, trim), - GetEndIndex(list.Last(), includeExteriorTrivia, trim)); - } + internal static PropertyDeclarationSyntax ReplaceAccessor( + this PropertyDeclarationSyntax propertyDeclaration, + AccessorDeclarationSyntax accessor, + AccessorDeclarationSyntax newAccessor) + { + return propertyDeclaration.WithAccessorList( + propertyDeclaration.AccessorList.WithAccessors( + propertyDeclaration.AccessorList.Accessors.Replace(accessor, newAccessor))); + } + #endregion PropertyDeclarationSyntax + + #region RecordDeclarationSyntax + /// + /// Creates a new with the members updated. + /// + /// + /// + public static RecordDeclarationSyntax WithMembers( + this RecordDeclarationSyntax recordDeclaration, + MemberDeclarationSyntax member) + { + if (recordDeclaration is null) + throw new ArgumentNullException(nameof(recordDeclaration)); - /// - /// Creates a new list with the elements in the specified range replaced with new node. - /// - /// - /// - /// - /// - /// - public static SeparatedSyntaxList ReplaceRange( - this SeparatedSyntaxList list, - int index, - int count, - TNode newNode) where TNode : SyntaxNode - { - if (newNode == null) - throw new ArgumentNullException(nameof(newNode)); + return recordDeclaration.WithMembers(SingletonList(member)); + } - return ReplaceRange(list, index, count, new TNode[] { newNode }); - } + /// + /// Creates a new with the members updated. + /// + /// + /// + public static RecordDeclarationSyntax WithMembers( + this RecordDeclarationSyntax recordDeclaration, + IEnumerable members) + { + if (recordDeclaration is null) + throw new ArgumentNullException(nameof(recordDeclaration)); - /// - /// Creates a new list with the elements in the specified range replaced with new nodes. - /// - /// - /// - /// - /// - /// - public static SeparatedSyntaxList ReplaceRange( - this SeparatedSyntaxList list, - int index, - int count, - IEnumerable newNodes) where TNode : SyntaxNode - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), index, ""); + return recordDeclaration.WithMembers(List(members)); + } - if (count < 0 - || index + count > list.Count) + /// + /// The absolute span of the braces, not including its leading and trailing trivia. + /// + /// + public static TextSpan BracesSpan(this RecordDeclarationSyntax recordDeclaration) { - throw new ArgumentOutOfRangeException(nameof(count), count, ""); + if (recordDeclaration is null) + throw new ArgumentNullException(nameof(recordDeclaration)); + + return TextSpan.FromBounds( + recordDeclaration.OpenBraceToken.SpanStart, + recordDeclaration.CloseBraceToken.Span.End); } + #endregion RecordDeclarationSyntax + + #region RegionDirectiveTriviaSyntax + /// + /// Returns endregion directive that is related to the specified region directive. Returns null if no matching endregion directive is found. + /// + /// + public static EndRegionDirectiveTriviaSyntax GetEndRegionDirective(this RegionDirectiveTriviaSyntax regionDirective) + { + if (regionDirective is null) + throw new ArgumentNullException(nameof(regionDirective)); - if (newNodes == null) - throw new ArgumentNullException(nameof(newNodes)); + RegionInfo region = SyntaxInfo.RegionInfo(regionDirective); - return SeparatedList(ReplaceRange()); + return (region.Success) ? region.EndDirective : null; + } - IEnumerable ReplaceRange() + /// + /// Gets preprocessing message for the specified region directive if such message exists. + /// + /// + public static SyntaxTrivia GetPreprocessingMessageTrivia(this RegionDirectiveTriviaSyntax regionDirective) { - SeparatedSyntaxList.Enumerator en = list.GetEnumerator(); - - int i = 0; + if (regionDirective is null) + throw new ArgumentNullException(nameof(regionDirective)); - while (i < index - && en.MoveNext()) - { - yield return en.Current; - i++; - } + SyntaxToken endOfDirective = regionDirective.EndOfDirectiveToken; - int endIndex = index + count; + SyntaxTriviaList leading = endOfDirective.LeadingTrivia; - while (i < endIndex - && en.MoveNext()) + if (leading.Count == 1) { - i++; - } + SyntaxTrivia trivia = leading[0]; - if ((newNodes as ICollection)?.Count != 0) - { - foreach (TNode newNode in newNodes) - yield return newNode; + if (trivia.IsKind(SyntaxKind.PreprocessingMessageTrivia)) + return trivia; } - while (en.MoveNext()) - yield return en.Current; + return default; } - } - /// - /// Creates a new list with elements in the specified range removed. - /// - /// - /// - /// An index of the first element to remove. - /// A number of elements to remove. - public static SeparatedSyntaxList RemoveRange( - this SeparatedSyntaxList list, - int index, - int count) where TNode : SyntaxNode - { - return ReplaceRange(list, index, count, Empty.ReadOnlyList()); - } + /// + /// Returns true the specified region directive has preprocessing message trivia. + /// + /// + internal static bool HasPreprocessingMessageTrivia(this RegionDirectiveTriviaSyntax regionDirective) + { + return GetPreprocessingMessageTrivia(regionDirective).IsKind(SyntaxKind.PreprocessingMessageTrivia); + } + #endregion RegionDirectiveTriviaSyntax + + #region SeparatedSyntaxList + /// + /// Searches for a node of the specified kind and returns the zero-based index of the last occurrence within the entire . + /// + /// + /// + /// + public static int LastIndexOf(this SeparatedSyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + return list.LastIndexOf(f => f.IsKind(kind)); + } - /// - /// Removes all leading whitespace from the leading trivia of the first node in a list - /// and all trailing whitespace from the trailing trivia of the last node in a list and returns a new list with the new trivia. - /// and is considered to be a whitespace. - /// - /// - /// - public static SeparatedSyntaxList TrimTrivia(this SeparatedSyntaxList list) where TNode : SyntaxNode - { - int count = list.Count; + /// + /// Searches for a node of the specified kind and returns the zero-based index of the first occurrence within the entire . + /// + /// + /// + /// + public static bool Contains(this SeparatedSyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + return list.IndexOf(kind) != -1; + } + + /// + /// Searches for a node of the specified kind and returns the first occurrence within the entire . + /// + /// + /// + /// + public static TNode Find(this SeparatedSyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + int index = list.IndexOf(kind); - if (count == 0) - return list; + if (index != -1) + return list[index]; - int separatorCount = list.SeparatorCount; + return default; + } - if (count == 1) + internal static bool IsSingleLine( + this SeparatedSyntaxList list, + bool includeExteriorTrivia = true, + bool trim = true, + CancellationToken cancellationToken = default) where TNode : SyntaxNode { - if (separatorCount == 0) - { - return list.ReplaceAt(0, list[0].TrimTrivia()); - } - else - { - list = list.ReplaceAt(0, list[0].TrimLeadingTrivia()); + TextSpan span = GetSpan(list, includeExteriorTrivia, trim); + + if (span.IsEmpty) + return false; - SyntaxToken separator = list.GetSeparator(0); + SyntaxTree tree = list[0].SyntaxTree; - return list.ReplaceSeparator(separator, separator.TrimTrailingTrivia()); - } + if (tree is null) + return false; + + return span.IsSingleLine(tree, cancellationToken); } - else + + internal static bool IsMultiLine( + this SeparatedSyntaxList list, + bool includeExteriorTrivia = true, + bool trim = true, + CancellationToken cancellationToken = default) where TNode : SyntaxNode { - list = list.ReplaceAt(0, list[0].TrimLeadingTrivia()); + TextSpan span = GetSpan(list, includeExteriorTrivia, trim); - if (separatorCount == count - 1) - { - return list.ReplaceAt(count - 1, list[count - 1].TrimTrailingTrivia()); - } - else - { - SyntaxToken separator = list.GetSeparator(separatorCount - 1); + if (span.IsEmpty) + return false; - return list.ReplaceSeparator(separator, separator.TrimTrailingTrivia()); - } + SyntaxTree tree = list[0].SyntaxTree; + + if (tree is null) + return false; + + return span.IsMultiLine(tree, cancellationToken); } - } - internal static int IndexOf(this SeparatedSyntaxList parameters, string name) - { - for (int i = 0; i < parameters.Count; i++) + internal static TextSpan GetSpan( + this SeparatedSyntaxList list, + bool includeExteriorTrivia = true, + bool trim = true) where TNode : SyntaxNode { - if (string.Equals(parameters[i].Identifier.ValueText, name, StringComparison.Ordinal)) - return i; - } + if (!list.Any()) + return default; - return -1; - } + return TextSpan.FromBounds( + GetStartIndex(list[0], includeExteriorTrivia, trim), + GetEndIndex(list.Last(), includeExteriorTrivia, trim)); + } - internal static int IndexOf(this SeparatedSyntaxList typeParameters, string name) - { - for (int i = 0; i < typeParameters.Count; i++) + /// + /// Creates a new list with the elements in the specified range replaced with new node. + /// + /// + /// + /// + /// + /// + public static SeparatedSyntaxList ReplaceRange( + this SeparatedSyntaxList list, + int index, + int count, + TNode newNode) where TNode : SyntaxNode { - if (string.Equals(typeParameters[i].Identifier.ValueText, name, StringComparison.Ordinal)) - return i; + if (newNode is null) + throw new ArgumentNullException(nameof(newNode)); + + return ReplaceRange(list, index, count, new TNode[] { newNode }); } - return -1; - } - #endregion SeparatedSyntaxList + /// + /// Creates a new list with the elements in the specified range replaced with new nodes. + /// + /// + /// + /// + /// + /// + public static SeparatedSyntaxList ReplaceRange( + this SeparatedSyntaxList list, + int index, + int count, + IEnumerable newNodes) where TNode : SyntaxNode + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, ""); - #region StatementSyntax - /// - /// Gets the previous statement of the specified statement. - /// If the specified statement is not contained in the list, or if there is no previous statement, then this method returns null. - /// - /// - public static StatementSyntax PreviousStatement(this StatementSyntax statement) - { - if (statement == null) - throw new ArgumentNullException(nameof(statement)); + if (count < 0 + || index + count > list.Count) + { + throw new ArgumentOutOfRangeException(nameof(count), count, ""); + } - SyntaxList statements = SyntaxInfo.StatementListInfo(statement).Statements; + if (newNodes is null) + throw new ArgumentNullException(nameof(newNodes)); - if (statements.Any()) - { - int index = statements.IndexOf(statement); + return SeparatedList(ReplaceRange()); - if (index > 0) - return statements[index - 1]; - } + IEnumerable ReplaceRange() + { + SeparatedSyntaxList.Enumerator en = list.GetEnumerator(); - return null; - } + int i = 0; - /// - /// Gets the next statement of the specified statement. - /// If the specified statement is not contained in the list, or if there is no next statement, then this method returns null. - /// - /// - public static StatementSyntax NextStatement(this StatementSyntax statement) - { - if (statement == null) - throw new ArgumentNullException(nameof(statement)); + while (i < index + && en.MoveNext()) + { + yield return en.Current; + i++; + } - SyntaxList statements = SyntaxInfo.StatementListInfo(statement).Statements; + int endIndex = index + count; - if (statements.Any()) - { - int index = statements.IndexOf(statement); + while (i < endIndex + && en.MoveNext()) + { + i++; + } - if (index < statements.Count - 1) - return statements[index + 1]; + if ((newNodes as ICollection)?.Count != 0) + { + foreach (TNode newNode in newNodes) + yield return newNode; + } + + while (en.MoveNext()) + yield return en.Current; + } } - return null; - } + /// + /// Creates a new list with elements in the specified range removed. + /// + /// + /// + /// An index of the first element to remove. + /// A number of elements to remove. + public static SeparatedSyntaxList RemoveRange( + this SeparatedSyntaxList list, + int index, + int count) where TNode : SyntaxNode + { + return ReplaceRange(list, index, count, Empty.ReadOnlyList()); + } - /// - /// Gets a list the specified statement is contained in. - /// This method succeeds if the statement is in a block's statements or a switch section's statements. - /// - /// - /// - /// True if the statement is contained in the list; otherwise, false. - public static bool TryGetContainingList(this StatementSyntax statement, out SyntaxList statements) - { - statements = SyntaxInfo.StatementListInfo(statement).Statements; + /// + /// Removes all leading whitespace from the leading trivia of the first node in a list + /// and all trailing whitespace from the trailing trivia of the last node in a list and returns a new list with the new trivia. + /// and is considered to be a whitespace. + /// + /// + /// + public static SeparatedSyntaxList TrimTrivia(this SeparatedSyntaxList list) where TNode : SyntaxNode + { + int count = list.Count; - return statements.Any(); - } + if (count == 0) + return list; - internal static StatementSyntax SingleNonBlockStatementOrDefault(this StatementSyntax statement, bool recursive = false) - { - return (statement.Kind() == SyntaxKind.Block) - ? SingleNonBlockStatementOrDefault((BlockSyntax)statement, recursive) - : statement; - } + int separatorCount = list.SeparatorCount; - /// - /// Returns true if the specified statement is an embedded statement. - /// - /// - /// Block can be considered as embedded statement - /// If statement that is a child of an else statement can be considered as an embedded statement. - /// Using statement that is a child of an using statement can be considered as en embedded statement. - public static bool IsEmbedded( - this StatementSyntax statement, - bool canBeBlock = false, - bool canBeIfInsideElse = true, - bool canBeUsingInsideUsing = true) - { - if (statement == null) - throw new ArgumentNullException(nameof(statement)); + if (count == 1) + { + if (separatorCount == 0) + { + return list.ReplaceAt(0, list[0].TrimTrivia()); + } + else + { + list = list.ReplaceAt(0, list[0].TrimLeadingTrivia()); - SyntaxKind kind = statement.Kind(); + SyntaxToken separator = list.GetSeparator(0); - if (!canBeBlock - && kind == SyntaxKind.Block) - { - return false; - } + return list.ReplaceSeparator(separator, separator.TrimTrailingTrivia()); + } + } + else + { + list = list.ReplaceAt(0, list[0].TrimLeadingTrivia()); - if (!CSharpFacts.CanBeEmbeddedStatement(kind)) - return false; + if (separatorCount == count - 1) + { + return list.ReplaceAt(count - 1, list[count - 1].TrimTrailingTrivia()); + } + else + { + SyntaxToken separator = list.GetSeparator(separatorCount - 1); + + return list.ReplaceSeparator(separator, separator.TrimTrailingTrivia()); + } + } + } - SyntaxNode parent = statement.Parent; + internal static int IndexOf(this SeparatedSyntaxList parameters, string name) + { + for (int i = 0; i < parameters.Count; i++) + { + if (string.Equals(parameters[i].Identifier.ValueText, name, StringComparison.Ordinal)) + return i; + } - if (parent == null) - return false; + return -1; + } - SyntaxKind parentKind = parent.Kind(); + internal static int IndexOf(this SeparatedSyntaxList typeParameters, string name) + { + for (int i = 0; i < typeParameters.Count; i++) + { + if (string.Equals(typeParameters[i].Identifier.ValueText, name, StringComparison.Ordinal)) + return i; + } - return CSharpFacts.CanHaveEmbeddedStatement(parentKind) - && (canBeIfInsideElse - || kind != SyntaxKind.IfStatement - || parentKind != SyntaxKind.ElseClause) - && (canBeUsingInsideUsing - || kind != SyntaxKind.UsingStatement - || parentKind != SyntaxKind.UsingStatement); - } - #endregion StatementSyntax + return -1; + } + #endregion SeparatedSyntaxList + + #region StatementSyntax + /// + /// Gets the previous statement of the specified statement. + /// If the specified statement is not contained in the list, or if there is no previous statement, then this method returns null. + /// + /// + public static StatementSyntax PreviousStatement(this StatementSyntax statement) + { + if (statement is null) + throw new ArgumentNullException(nameof(statement)); - #region StructDeclarationSyntax - /// - /// Creates a new with the members updated. - /// - /// - /// - public static StructDeclarationSyntax WithMembers( - this StructDeclarationSyntax structDeclaration, - MemberDeclarationSyntax member) - { - if (structDeclaration == null) - throw new ArgumentNullException(nameof(structDeclaration)); + SyntaxList statements = SyntaxInfo.StatementListInfo(statement).Statements; - return structDeclaration.WithMembers(SingletonList(member)); - } + if (statements.Any()) + { + int index = statements.IndexOf(statement); - /// - /// Creates a new with the members updated. - /// - /// - /// - public static StructDeclarationSyntax WithMembers( - this StructDeclarationSyntax structDeclaration, - IEnumerable members) - { - if (structDeclaration == null) - throw new ArgumentNullException(nameof(structDeclaration)); + if (index > 0) + return statements[index - 1]; + } - return structDeclaration.WithMembers(List(members)); - } + return null; + } - /// - /// The absolute span of the braces, not including its leading and trailing trivia. - /// - /// - public static TextSpan BracesSpan(this StructDeclarationSyntax structDeclaration) - { - if (structDeclaration == null) - throw new ArgumentNullException(nameof(structDeclaration)); + /// + /// Gets the next statement of the specified statement. + /// If the specified statement is not contained in the list, or if there is no next statement, then this method returns null. + /// + /// + public static StatementSyntax NextStatement(this StatementSyntax statement) + { + if (statement is null) + throw new ArgumentNullException(nameof(statement)); - return TextSpan.FromBounds( - structDeclaration.OpenBraceToken.SpanStart, - structDeclaration.CloseBraceToken.Span.End); - } - #endregion StructDeclarationSyntax + SyntaxList statements = SyntaxInfo.StatementListInfo(statement).Statements; - #region SwitchSectionSyntax - /// - /// Returns true if the specified switch section contains default switch label. - /// - /// - public static bool ContainsDefaultLabel(this SwitchSectionSyntax switchSection) - { - return switchSection?.Labels.Any(f => f.IsKind(SyntaxKind.DefaultSwitchLabel)) == true; - } + if (statements.Any()) + { + int index = statements.IndexOf(statement); - internal static SyntaxList GetStatements(this SwitchSectionSyntax switchSection) - { - SyntaxList statements = switchSection.Statements; + if (index < statements.Count - 1) + return statements[index + 1]; + } - if (statements.SingleOrDefault(shouldThrow: false) is BlockSyntax block) - { - return block.Statements; + return null; } - return statements; - } - #endregion SwitchSectionSyntax + /// + /// Gets a list the specified statement is contained in. + /// This method succeeds if the statement is in a block's statements or a switch section's statements. + /// + /// + /// + /// True if the statement is contained in the list; otherwise, false. + public static bool TryGetContainingList(this StatementSyntax statement, out SyntaxList statements) + { + statements = SyntaxInfo.StatementListInfo(statement).Statements; - #region SwitchStatementSyntax - /// - /// Returns a section that contains default label, or null if the specified switch statement does not contains section with default label. - /// - /// - public static SwitchSectionSyntax DefaultSection(this SwitchStatementSyntax switchStatement) - { - if (switchStatement == null) - throw new ArgumentNullException(nameof(switchStatement)); + return statements.Any(); + } - foreach (SwitchSectionSyntax section in switchStatement.Sections) + internal static StatementSyntax SingleNonBlockStatementOrDefault(this StatementSyntax statement, bool recursive = false) { - if (section.Labels.Any(SyntaxKind.DefaultSwitchLabel)) - return section; + return (statement.Kind() == SyntaxKind.Block) + ? SingleNonBlockStatementOrDefault((BlockSyntax)statement, recursive) + : statement; } - return null; - } - #endregion SwitchStatementSyntax - - #region SyntaxList - /// - /// Searches for a node of the specified kind and returns the zero-based index of the last occurrence within the entire . - /// - /// - /// - /// - public static int LastIndexOf(this SyntaxList list, SyntaxKind kind) where TNode : SyntaxNode - { - return list.LastIndexOf(f => f.IsKind(kind)); - } + /// + /// Returns true if the specified statement is an embedded statement. + /// + /// + /// Block can be considered as embedded statement + /// If statement that is a child of an else statement can be considered as an embedded statement. + /// Using statement that is a child of an using statement can be considered as en embedded statement. + public static bool IsEmbedded( + this StatementSyntax statement, + bool canBeBlock = false, + bool canBeIfInsideElse = true, + bool canBeUsingInsideUsing = true) + { + if (statement is null) + throw new ArgumentNullException(nameof(statement)); - /// - /// Returns true if a node of the specified kind is in the . - /// - /// - /// - /// - public static bool Contains(this SyntaxList list, SyntaxKind kind) where TNode : SyntaxNode - { - return list.IndexOf(kind) != -1; - } + SyntaxKind kind = statement.Kind(); - /// - /// Searches for a node of the specified kind and returns the first occurrence within the entire . - /// - /// - /// - /// - public static TNode Find(this SyntaxList list, SyntaxKind kind) where TNode : SyntaxNode - { - int index = list.IndexOf(kind); + if (!canBeBlock + && kind == SyntaxKind.Block) + { + return false; + } - if (index != -1) - return list[index]; + if (!CSharpFacts.CanBeEmbeddedStatement(kind)) + return false; - return default; - } + SyntaxNode parent = statement.Parent; - internal static bool IsSingleLine( - this SyntaxList list, - bool includeExteriorTrivia = true, - bool trim = true, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - TextSpan span = GetSpan(list, includeExteriorTrivia, trim); + if (parent is null) + return false; - if (span.IsEmpty) - return false; + SyntaxKind parentKind = parent.Kind(); - SyntaxTree tree = list[0].SyntaxTree; + return CSharpFacts.CanHaveEmbeddedStatement(parentKind) + && (canBeIfInsideElse + || kind != SyntaxKind.IfStatement + || parentKind != SyntaxKind.ElseClause) + && (canBeUsingInsideUsing + || kind != SyntaxKind.UsingStatement + || parentKind != SyntaxKind.UsingStatement); + } + #endregion StatementSyntax + + #region StructDeclarationSyntax + /// + /// Creates a new with the members updated. + /// + /// + /// + public static StructDeclarationSyntax WithMembers( + this StructDeclarationSyntax structDeclaration, + MemberDeclarationSyntax member) + { + if (structDeclaration is null) + throw new ArgumentNullException(nameof(structDeclaration)); - if (tree == null) - return false; + return structDeclaration.WithMembers(SingletonList(member)); + } - return span.IsSingleLine(tree, cancellationToken); - } + /// + /// Creates a new with the members updated. + /// + /// + /// + public static StructDeclarationSyntax WithMembers( + this StructDeclarationSyntax structDeclaration, + IEnumerable members) + { + if (structDeclaration is null) + throw new ArgumentNullException(nameof(structDeclaration)); - internal static bool IsMultiLine( - this SyntaxList list, - bool includeExteriorTrivia = true, - bool trim = true, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - TextSpan span = GetSpan(list, includeExteriorTrivia, trim); + return structDeclaration.WithMembers(List(members)); + } - if (span.IsEmpty) - return false; + /// + /// The absolute span of the braces, not including its leading and trailing trivia. + /// + /// + public static TextSpan BracesSpan(this StructDeclarationSyntax structDeclaration) + { + if (structDeclaration is null) + throw new ArgumentNullException(nameof(structDeclaration)); - SyntaxTree tree = list[0].SyntaxTree; + return TextSpan.FromBounds( + structDeclaration.OpenBraceToken.SpanStart, + structDeclaration.CloseBraceToken.Span.End); + } + #endregion StructDeclarationSyntax + + #region SwitchSectionSyntax + /// + /// Returns true if the specified switch section contains default switch label. + /// + /// + public static bool ContainsDefaultLabel(this SwitchSectionSyntax switchSection) + { + return switchSection?.Labels.Any(f => f.IsKind(SyntaxKind.DefaultSwitchLabel)) == true; + } - if (tree == null) - return false; + internal static SyntaxList GetStatements(this SwitchSectionSyntax switchSection) + { + SyntaxList statements = switchSection.Statements; - return span.IsMultiLine(tree, cancellationToken); - } + if (statements.SingleOrDefault(shouldThrow: false) is BlockSyntax block) + { + return block.Statements; + } - internal static TextSpan GetSpan( - this SyntaxList list, - bool includeExteriorTrivia = true, - bool trim = true) where TNode : SyntaxNode - { - if (!list.Any()) - return default; + return statements; + } + #endregion SwitchSectionSyntax + + #region SwitchStatementSyntax + /// + /// Returns a section that contains default label, or null if the specified switch statement does not contains section with default label. + /// + /// + public static SwitchSectionSyntax DefaultSection(this SwitchStatementSyntax switchStatement) + { + if (switchStatement is null) + throw new ArgumentNullException(nameof(switchStatement)); - return TextSpan.FromBounds( - GetStartIndex(list[0], includeExteriorTrivia, trim), - GetEndIndex(list.Last(), includeExteriorTrivia, trim)); - } + foreach (SwitchSectionSyntax section in switchStatement.Sections) + { + if (section.Labels.Any(SyntaxKind.DefaultSwitchLabel)) + return section; + } - internal static StatementSyntax SingleOrDefault(this SyntaxList statements, bool ignoreLocalFunctions, bool shouldThrow) - { - return (ignoreLocalFunctions) - ? statements.SingleOrDefault(statement => statement.Kind() != SyntaxKind.LocalFunctionStatement, shouldThrow: shouldThrow) - : statements.SingleOrDefault(shouldThrow: shouldThrow); - } + return null; + } + #endregion SwitchStatementSyntax + + #region SyntaxList + /// + /// Searches for a node of the specified kind and returns the zero-based index of the last occurrence within the entire . + /// + /// + /// + /// + public static int LastIndexOf(this SyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + return list.LastIndexOf(f => f.IsKind(kind)); + } - /// - /// Returns true if the specified statement is a last statement in the list. - /// - /// - /// - /// Ignore local function statements at the end of the list. - public static bool IsLast( - this SyntaxList statements, - StatementSyntax statement, - bool ignoreLocalFunctions) - { - if (!ignoreLocalFunctions) - return statements.IsLast(statement); + /// + /// Returns true if a node of the specified kind is in the . + /// + /// + /// + /// + public static bool Contains(this SyntaxList list, SyntaxKind kind) where TNode : SyntaxNode + { + return list.IndexOf(kind) != -1; + } - for (int i = statements.Count - 1; i >= 0; i--) + /// + /// Searches for a node of the specified kind and returns the first occurrence within the entire . + /// + /// + /// + /// + public static TNode Find(this SyntaxList list, SyntaxKind kind) where TNode : SyntaxNode { - StatementSyntax s = statements[i]; + int index = list.IndexOf(kind); - if (!s.IsKind(SyntaxKind.LocalFunctionStatement)) - return s == statement; - } + if (index != -1) + return list[index]; - return false; - } + return default; + } - /// - /// Creates a new list with the specified node added or inserted. - /// - /// - /// - /// Insert statement before local function statements at the end of the list. - public static SyntaxList Add( - this SyntaxList statements, - StatementSyntax statement, - bool ignoreLocalFunctions) - { - if (statement == null) - throw new ArgumentNullException(nameof(statement)); + internal static bool IsSingleLine( + this SyntaxList list, + bool includeExteriorTrivia = true, + bool trim = true, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + TextSpan span = GetSpan(list, includeExteriorTrivia, trim); - if (!ignoreLocalFunctions) - return statements.Add(statement); + if (span.IsEmpty) + return false; - int count = statements.Count; + SyntaxTree tree = list[0].SyntaxTree; - int index = count; + if (tree is null) + return false; - for (int i = count - 1; i >= 0; i--) - { - if (statements[i].IsKind(SyntaxKind.LocalFunctionStatement)) - index--; + return span.IsSingleLine(tree, cancellationToken); } - return statements.Insert(index, statement); - } + internal static bool IsMultiLine( + this SyntaxList list, + bool includeExteriorTrivia = true, + bool trim = true, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + TextSpan span = GetSpan(list, includeExteriorTrivia, trim); - /// - /// Creates a new list with the elements in the specified range replaced with new node. - /// - /// - /// - /// - /// - /// - public static SyntaxList ReplaceRange( - this SyntaxList list, - int index, - int count, - TNode newNode) where TNode : SyntaxNode - { - if (newNode == null) - throw new ArgumentNullException(nameof(newNode)); + if (span.IsEmpty) + return false; - return ReplaceRange(list, index, count, new TNode[] { newNode }); - } + SyntaxTree tree = list[0].SyntaxTree; - /// - /// Creates a new list with the elements in the specified range replaced with new nodes. - /// - /// - /// - /// - /// - /// - public static SyntaxList ReplaceRange( - this SyntaxList list, - int index, - int count, - IEnumerable newNodes) where TNode : SyntaxNode - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), index, ""); + if (tree is null) + return false; - if (count < 0 - || index + count > list.Count) - { - throw new ArgumentOutOfRangeException(nameof(count), count, ""); + return span.IsMultiLine(tree, cancellationToken); } - if (newNodes == null) - throw new ArgumentNullException(nameof(newNodes)); + internal static TextSpan GetSpan( + this SyntaxList list, + bool includeExteriorTrivia = true, + bool trim = true) where TNode : SyntaxNode + { + if (!list.Any()) + return default; - return List(ReplaceRange()); + return TextSpan.FromBounds( + GetStartIndex(list[0], includeExteriorTrivia, trim), + GetEndIndex(list.Last(), includeExteriorTrivia, trim)); + } - IEnumerable ReplaceRange() + internal static StatementSyntax SingleOrDefault(this SyntaxList statements, bool ignoreLocalFunctions, bool shouldThrow) { - SyntaxList.Enumerator en = list.GetEnumerator(); + return (ignoreLocalFunctions) + ? statements.SingleOrDefault(statement => statement.Kind() != SyntaxKind.LocalFunctionStatement, shouldThrow: shouldThrow) + : statements.SingleOrDefault(shouldThrow: shouldThrow); + } - int i = 0; + /// + /// Returns true if the specified statement is a last statement in the list. + /// + /// + /// + /// Ignore local function statements at the end of the list. + public static bool IsLast( + this SyntaxList statements, + StatementSyntax statement, + bool ignoreLocalFunctions) + { + if (!ignoreLocalFunctions) + return statements.IsLast(statement); - while (i < index - && en.MoveNext()) + for (int i = statements.Count - 1; i >= 0; i--) { - yield return en.Current; - i++; + StatementSyntax s = statements[i]; + + if (!s.IsKind(SyntaxKind.LocalFunctionStatement)) + return s == statement; } - int endIndex = index + count; + return false; + } - while (i < endIndex - && en.MoveNext()) - { - i++; - } + /// + /// Creates a new list with the specified node added or inserted. + /// + /// + /// + /// Insert statement before local function statements at the end of the list. + public static SyntaxList Add( + this SyntaxList statements, + StatementSyntax statement, + bool ignoreLocalFunctions) + { + if (statement is null) + throw new ArgumentNullException(nameof(statement)); - if ((newNodes as ICollection)?.Count != 0) + if (!ignoreLocalFunctions) + return statements.Add(statement); + + int count = statements.Count; + + int index = count; + + for (int i = count - 1; i >= 0; i--) { - foreach (TNode newNode in newNodes) - yield return newNode; + if (statements[i].IsKind(SyntaxKind.LocalFunctionStatement)) + index--; } - while (en.MoveNext()) - yield return en.Current; + return statements.Insert(index, statement); } - } - - /// - /// Creates a new list with elements in the specified range removed. - /// - /// - /// - /// An index of the first element to remove. - /// A number of elements to remove. - public static SyntaxList RemoveRange( - this SyntaxList list, - int index, - int count) where TNode : SyntaxNode - { - return ReplaceRange(list, index, count, Empty.ReadOnlyList()); - } - internal static StatementSyntax LastOrDefault(this SyntaxList statements, bool ignoreLocalFunction) - { - if (!ignoreLocalFunction) - return statements.LastOrDefault(); + /// + /// Creates a new list with the elements in the specified range replaced with new node. + /// + /// + /// + /// + /// + /// + public static SyntaxList ReplaceRange( + this SyntaxList list, + int index, + int count, + TNode newNode) where TNode : SyntaxNode + { + if (newNode is null) + throw new ArgumentNullException(nameof(newNode)); - int i = statements.Count - 1; + return ReplaceRange(list, index, count, new TNode[] { newNode }); + } - while (i >= 0) + /// + /// Creates a new list with the elements in the specified range replaced with new nodes. + /// + /// + /// + /// + /// + /// + public static SyntaxList ReplaceRange( + this SyntaxList list, + int index, + int count, + IEnumerable newNodes) where TNode : SyntaxNode { - StatementSyntax statement = statements[i]; + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, ""); - if (statement.Kind() != SyntaxKind.LocalFunctionStatement) - return statement; + if (count < 0 + || index + count > list.Count) + { + throw new ArgumentOutOfRangeException(nameof(count), count, ""); + } - i--; - } + if (newNodes is null) + throw new ArgumentNullException(nameof(newNodes)); - return null; - } + return List(ReplaceRange()); - /// - /// Removes all leading whitespace from the leading trivia of the first node in a list - /// and all trailing whitespace from the trailing trivia of the last node in a list and returns a new list with the new trivia. - /// and is considered to be a whitespace. - /// - /// - /// - public static SyntaxList TrimTrivia(this SyntaxList list) where TNode : SyntaxNode - { - int count = list.Count; + IEnumerable ReplaceRange() + { + SyntaxList.Enumerator en = list.GetEnumerator(); - if (count == 0) - return list; + int i = 0; - if (count == 1) - return list.ReplaceAt(0, list[0].TrimTrivia()); + while (i < index + && en.MoveNext()) + { + yield return en.Current; + i++; + } - return list - .ReplaceAt(0, list[0].TrimLeadingTrivia()) - .ReplaceAt(count - 1, list[count - 1].TrimTrailingTrivia()); - } - #endregion SyntaxList + int endIndex = index + count; - #region SyntaxNode - internal static IEnumerable DescendantPreprocessorDirectives(this SyntaxNode node, Func predicate = null) - { - return DescendantPreprocessorDirectives(node, node.FullSpan, predicate); - } + while (i < endIndex + && en.MoveNext()) + { + i++; + } - internal static IEnumerable DescendantPreprocessorDirectives(this SyntaxNode node, TextSpan span, Func predicate = null) - { - foreach (SyntaxTrivia trivia in node.DescendantTrivia(span: span, descendIntoTrivia: true)) - { - if (trivia.IsDirective - && trivia.HasStructure - && (trivia.GetStructure() is DirectiveTriviaSyntax directive)) - { - if (predicate == null - || predicate(directive)) + if ((newNodes as ICollection)?.Count != 0) { - yield return directive; + foreach (TNode newNode in newNodes) + yield return newNode; } + + while (en.MoveNext()) + yield return en.Current; } } - } - /// - /// Returns true if a node is a descendant of a node with the specified kind. - /// - /// - /// - /// - public static bool IsDescendantOf(this SyntaxNode node, SyntaxKind kind, bool ascendOutOfTrivia = true) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + /// + /// Creates a new list with elements in the specified range removed. + /// + /// + /// + /// An index of the first element to remove. + /// A number of elements to remove. + public static SyntaxList RemoveRange( + this SyntaxList list, + int index, + int count) where TNode : SyntaxNode + { + return ReplaceRange(list, index, count, Empty.ReadOnlyList()); + } - return node.Ancestors(ascendOutOfTrivia).Any(f => f.IsKind(kind)); - } + internal static StatementSyntax LastOrDefault(this SyntaxList statements, bool ignoreLocalFunction) + { + if (!ignoreLocalFunction) + return statements.LastOrDefault(); - /// - /// Returns true if a node's kind is one of the specified kinds. - /// - /// - /// - /// - public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2) - { - if (node == null) - return false; + int i = statements.Count - 1; - SyntaxKind kind = node.Kind(); + while (i >= 0) + { + StatementSyntax statement = statements[i]; - return kind == kind1 - || kind == kind2; - } + if (statement.Kind() != SyntaxKind.LocalFunctionStatement) + return statement; - /// - /// Returns true if a node's kind is one of the specified kinds. - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) - { - if (node == null) - return false; + i--; + } - SyntaxKind kind = node.Kind(); + return null; + } - return kind == kind1 - || kind == kind2 - || kind == kind3; - } + /// + /// Removes all leading whitespace from the leading trivia of the first node in a list + /// and all trailing whitespace from the trailing trivia of the last node in a list and returns a new list with the new trivia. + /// and is considered to be a whitespace. + /// + /// + /// + public static SyntaxList TrimTrivia(this SyntaxList list) where TNode : SyntaxNode + { + int count = list.Count; - /// - /// Returns true if a node's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) - { - if (node == null) - return false; + if (count == 0) + return list; - SyntaxKind kind = node.Kind(); + if (count == 1) + return list.ReplaceAt(0, list[0].TrimTrivia()); - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4; - } + return list + .ReplaceAt(0, list[0].TrimLeadingTrivia()) + .ReplaceAt(count - 1, list[count - 1].TrimTrailingTrivia()); + } + #endregion SyntaxList - /// - /// Returns true if a node's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) - { - if (node == null) - return false; + #region SyntaxNode + internal static IEnumerable DescendantPreprocessorDirectives(this SyntaxNode node, Func predicate = null) + { + return DescendantPreprocessorDirectives(node, node.FullSpan, predicate); + } - SyntaxKind kind = node.Kind(); + internal static IEnumerable DescendantPreprocessorDirectives(this SyntaxNode node, TextSpan span, Func predicate = null) + { + foreach (SyntaxTrivia trivia in node.DescendantTrivia(span: span, descendIntoTrivia: true)) + { + if (trivia.IsDirective + && trivia.HasStructure + && (trivia.GetStructure() is DirectiveTriviaSyntax directive)) + { + if (predicate is null + || predicate(directive)) + { + yield return directive; + } + } + } + } - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4 - || kind == kind5; - } + /// + /// Returns true if a node is a descendant of a node with the specified kind. + /// + /// + /// + /// + public static bool IsDescendantOf(this SyntaxNode node, SyntaxKind kind, bool ascendOutOfTrivia = true) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - /// - /// Returns true if a node's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) - { - if (node == null) - return false; + return node.Ancestors(ascendOutOfTrivia).Any(f => f.IsKind(kind)); + } - SyntaxKind kind = node.Kind(); + /// + /// Returns true if a node's kind is one of the specified kinds. + /// + /// + /// + /// + public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2) + { + if (node is null) + return false; - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4 - || kind == kind5 - || kind == kind6; - } + SyntaxKind kind = node.Kind(); - /// - /// Returns true if a node parent's kind is the specified kind. - /// - /// - /// - public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind) - { - return node?.Parent.IsKind(kind) == true; - } + return kind == kind1 + || kind == kind2; + } - /// - /// Returns true if a node parent's kind is one of the specified kinds. - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2) - { - return IsKind(node?.Parent, kind1, kind2); - } + /// + /// Returns true if a node's kind is one of the specified kinds. + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) + { + if (node is null) + return false; - /// - /// Returns true if a node parent's kind is one of the specified kinds. - /// - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) - { - return IsKind(node?.Parent, kind1, kind2, kind3); - } + SyntaxKind kind = node.Kind(); - /// - /// Returns true if a node parent's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) - { - return IsKind(node?.Parent, kind1, kind2, kind3, kind4); - } + return kind == kind1 + || kind == kind2 + || kind == kind3; + } - /// - /// Returns true if a node parent's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) - { - return IsKind(node?.Parent, kind1, kind2, kind3, kind4, kind5); - } + /// + /// Returns true if a node's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) + { + if (node is null) + return false; - /// - /// Returns true if a node parent's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) - { - return IsKind(node?.Parent, kind1, kind2, kind3, kind4, kind5, kind6); - } + SyntaxKind kind = node.Kind(); + + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4; + } + + /// + /// Returns true if a node's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) + { + if (node is null) + return false; - internal static bool IsSingleLine( - this SyntaxNode node, - bool includeExteriorTrivia = true, - bool trim = true, - CancellationToken cancellationToken = default) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + SyntaxKind kind = node.Kind(); - SyntaxTree syntaxTree = node.SyntaxTree; + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4 + || kind == kind5; + } - if (syntaxTree != null) + /// + /// Returns true if a node's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) { - TextSpan span = GetSpan(node, includeExteriorTrivia, trim); + if (node is null) + return false; - return syntaxTree.IsSingleLineSpan(span, cancellationToken); + SyntaxKind kind = node.Kind(); + + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4 + || kind == kind5 + || kind == kind6; } - else + + /// + /// Returns true if a node parent's kind is the specified kind. + /// + /// + /// + public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind) { - return false; + return node?.Parent.IsKind(kind) == true; } - } - internal static bool IsMultiLine( - this SyntaxNode node, - bool includeExteriorTrivia = true, - bool trim = true, - CancellationToken cancellationToken = default) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + /// + /// Returns true if a node parent's kind is one of the specified kinds. + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2) + { + return IsKind(node?.Parent, kind1, kind2); + } - SyntaxTree syntaxTree = node.SyntaxTree; + /// + /// Returns true if a node parent's kind is one of the specified kinds. + /// + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) + { + return IsKind(node?.Parent, kind1, kind2, kind3); + } - if (syntaxTree != null) + /// + /// Returns true if a node parent's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) { - TextSpan span = GetSpan(node, includeExteriorTrivia, trim); + return IsKind(node?.Parent, kind1, kind2, kind3, kind4); + } - return syntaxTree.IsMultiLineSpan(span, cancellationToken); + /// + /// Returns true if a node parent's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) + { + return IsKind(node?.Parent, kind1, kind2, kind3, kind4, kind5); } - else + + /// + /// Returns true if a node parent's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) { - return false; + return IsKind(node?.Parent, kind1, kind2, kind3, kind4, kind5, kind6); } - } - internal static TextSpan GetSpan( - this SyntaxNode node, - bool includeExteriorTrivia = true, - bool trim = true) - { - return TextSpan.FromBounds( - GetStartIndex(node, includeExteriorTrivia, trim), - GetEndIndex(node, includeExteriorTrivia, trim)); - } + internal static bool IsSingleLine( + this SyntaxNode node, + bool includeExteriorTrivia = true, + bool trim = true, + CancellationToken cancellationToken = default) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - private static int GetStartIndex(SyntaxNode node, bool includeExteriorTrivia, bool trim) - { - if (!includeExteriorTrivia) - return node.SpanStart; + SyntaxTree syntaxTree = node.SyntaxTree; + + if (syntaxTree is not null) + { + TextSpan span = GetSpan(node, includeExteriorTrivia, trim); - int start = node.FullSpan.Start; + return syntaxTree.IsSingleLineSpan(span, cancellationToken); + } + else + { + return false; + } + } - if (trim) + internal static bool IsMultiLine( + this SyntaxNode node, + bool includeExteriorTrivia = true, + bool trim = true, + CancellationToken cancellationToken = default) { - SyntaxTriviaList leading = node.GetLeadingTrivia(); + if (node is null) + throw new ArgumentNullException(nameof(node)); - for (int i = 0; i < leading.Count; i++) + SyntaxTree syntaxTree = node.SyntaxTree; + + if (syntaxTree is not null) { - if (!leading[i].IsWhitespaceOrEndOfLineTrivia()) - break; + TextSpan span = GetSpan(node, includeExteriorTrivia, trim); - start = leading[i].Span.End; + return syntaxTree.IsMultiLineSpan(span, cancellationToken); + } + else + { + return false; } } - return start; - } - - private static int GetEndIndex(SyntaxNode node, bool includeExteriorTrivia, bool trim) - { - if (!includeExteriorTrivia) - return node.Span.End; - - int end = node.FullSpan.End; + internal static TextSpan GetSpan( + this SyntaxNode node, + bool includeExteriorTrivia = true, + bool trim = true) + { + return TextSpan.FromBounds( + GetStartIndex(node, includeExteriorTrivia, trim), + GetEndIndex(node, includeExteriorTrivia, trim)); + } - if (trim) + private static int GetStartIndex(SyntaxNode node, bool includeExteriorTrivia, bool trim) { - SyntaxTriviaList trailing = node.GetTrailingTrivia(); + if (!includeExteriorTrivia) + return node.SpanStart; - for (int i = trailing.Count - 1; i >= 0; i--) + int start = node.FullSpan.Start; + + if (trim) { - if (!trailing[i].IsWhitespaceOrEndOfLineTrivia()) - break; + SyntaxTriviaList leading = node.GetLeadingTrivia(); - end = trailing[i].SpanStart; + for (int i = 0; i < leading.Count; i++) + { + if (!leading[i].IsWhitespaceOrEndOfLineTrivia()) + break; + + start = leading[i].Span.End; + } } + + return start; } - return end; - } + private static int GetEndIndex(SyntaxNode node, bool includeExteriorTrivia, bool trim) + { + if (!includeExteriorTrivia) + return node.Span.End; - /// - /// Removes all leading whitespace from the leading trivia and returns a new node with the new leading trivia. - /// and is considered to be a whitespace. - /// Returns the same node if there is nothing to trim. - /// - /// - /// - public static TNode TrimLeadingTrivia(this TNode node) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + int end = node.FullSpan.End; - SyntaxTriviaList trivia = node.GetLeadingTrivia(); + if (trim) + { + SyntaxTriviaList trailing = node.GetTrailingTrivia(); - int count = trivia.Count; + for (int i = trailing.Count - 1; i >= 0; i--) + { + if (!trailing[i].IsWhitespaceOrEndOfLineTrivia()) + break; - if (count > 0) - { - SyntaxTriviaList newTrivia = trivia.TrimStart(); + end = trailing[i].SpanStart; + } + } - if (trivia.Count != newTrivia.Count) - return node.WithLeadingTrivia(newTrivia); + return end; } - return node; - } + /// + /// Removes all leading whitespace from the leading trivia and returns a new node with the new leading trivia. + /// and is considered to be a whitespace. + /// Returns the same node if there is nothing to trim. + /// + /// + /// + public static TNode TrimLeadingTrivia(this TNode node) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - /// - /// Removes all trailing whitespace from the trailing trivia and returns a new node with the new trailing trivia. - /// and is considered to be a whitespace. - /// Returns the same node if there is nothing to trim. - /// - /// - /// - public static TNode TrimTrailingTrivia(this TNode node) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + SyntaxTriviaList trivia = node.GetLeadingTrivia(); - SyntaxTriviaList trivia = node.GetTrailingTrivia(); + int count = trivia.Count; - int count = trivia.Count; + if (count > 0) + { + SyntaxTriviaList newTrivia = trivia.TrimStart(); - if (count > 0) - { - SyntaxTriviaList newTrivia = trivia.TrimEnd(); + if (trivia.Count != newTrivia.Count) + return node.WithLeadingTrivia(newTrivia); + } - if (trivia.Count != newTrivia.Count) - return node.WithTrailingTrivia(newTrivia); + return node; } - return node; - } + /// + /// Removes all trailing whitespace from the trailing trivia and returns a new node with the new trailing trivia. + /// and is considered to be a whitespace. + /// Returns the same node if there is nothing to trim. + /// + /// + /// + public static TNode TrimTrailingTrivia(this TNode node) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - /// - /// Removes all leading whitespace from the leading trivia and all trailing whitespace from the trailing trivia and returns a new node with the new trivia. - /// and is considered to be a whitespace. - /// Returns the same node if there is nothing to trim. - /// - /// - /// - public static TNode TrimTrivia(this TNode node) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + SyntaxTriviaList trivia = node.GetTrailingTrivia(); - return node - .TrimLeadingTrivia() - .TrimTrailingTrivia(); - } + int count = trivia.Count; - internal static TextSpan TrimmedSpan(this SyntaxNode node) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + if (count > 0) + { + SyntaxTriviaList newTrivia = trivia.TrimEnd(); - return TextSpan.FromBounds( - GetStartIndex(node, includeExteriorTrivia: true, trim: true), - GetEndIndex(node, includeExteriorTrivia: true, trim: true)); - } + if (trivia.Count != newTrivia.Count) + return node.WithTrailingTrivia(newTrivia); + } - /// - /// Gets the first ancestor of the specified kind. - /// - /// - /// - /// - public static SyntaxNode FirstAncestor( - this SyntaxNode node, - SyntaxKind kind, - bool ascendOutOfTrivia = true) - { - return FirstAncestor(node, f => f.IsKind(kind), ascendOutOfTrivia); - } + return node; + } - /// - /// Gets the first ancestor of the specified kinds. - /// - /// - /// - /// - /// - public static SyntaxNode FirstAncestor( - this SyntaxNode node, - SyntaxKind kind1, - SyntaxKind kind2, - bool ascendOutOfTrivia = true) - { - return FirstAncestor(node, f => f.IsKind(kind1, kind2), ascendOutOfTrivia); - } + /// + /// Removes all leading whitespace from the leading trivia and all trailing whitespace from the trailing trivia and returns a new node with the new trivia. + /// and is considered to be a whitespace. + /// Returns the same node if there is nothing to trim. + /// + /// + /// + public static TNode TrimTrivia(this TNode node) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - /// - /// Gets the first ancestor of the specified kinds. - /// - /// - /// - /// - /// - /// - public static SyntaxNode FirstAncestor( - this SyntaxNode node, - SyntaxKind kind1, - SyntaxKind kind2, - SyntaxKind kind3, - bool ascendOutOfTrivia = true) - { - return FirstAncestor(node, f => f.IsKind(kind1, kind2, kind3), ascendOutOfTrivia); - } + return node + .TrimLeadingTrivia() + .TrimTrailingTrivia(); + } - /// - /// Gets the first ancestor that matches the predicate. - /// - /// - /// - /// - public static SyntaxNode FirstAncestor(this SyntaxNode node, Func predicate, bool ascendOutOfTrivia = true) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + internal static TextSpan TrimmedSpan(this SyntaxNode node) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - if (predicate == null) - throw new ArgumentNullException(nameof(predicate)); + return TextSpan.FromBounds( + GetStartIndex(node, includeExteriorTrivia: true, trim: true), + GetEndIndex(node, includeExteriorTrivia: true, trim: true)); + } - SyntaxNode parent = node.GetParent(ascendOutOfTrivia); + /// + /// Gets the first ancestor of the specified kind. + /// + /// + /// + /// + public static SyntaxNode FirstAncestor( + this SyntaxNode node, + SyntaxKind kind, + bool ascendOutOfTrivia = true) + { + return FirstAncestor(node, f => f.IsKind(kind), ascendOutOfTrivia); + } - if (parent != null) + /// + /// Gets the first ancestor of the specified kinds. + /// + /// + /// + /// + /// + public static SyntaxNode FirstAncestor( + this SyntaxNode node, + SyntaxKind kind1, + SyntaxKind kind2, + bool ascendOutOfTrivia = true) { - return FirstAncestorOrSelf(parent, predicate, ascendOutOfTrivia); + return FirstAncestor(node, f => f.IsKind(kind1, kind2), ascendOutOfTrivia); } - else + + /// + /// Gets the first ancestor of the specified kinds. + /// + /// + /// + /// + /// + /// + public static SyntaxNode FirstAncestor( + this SyntaxNode node, + SyntaxKind kind1, + SyntaxKind kind2, + SyntaxKind kind3, + bool ascendOutOfTrivia = true) { - return null; + return FirstAncestor(node, f => f.IsKind(kind1, kind2, kind3), ascendOutOfTrivia); } - } - /// - /// Gets the first ancestor of the specified kind. - /// - /// - /// - /// - public static SyntaxNode FirstAncestorOrSelf( - this SyntaxNode node, - SyntaxKind kind, - bool ascendOutOfTrivia = true) - { - return FirstAncestorOrSelf(node, f => f.IsKind(kind), ascendOutOfTrivia); - } + /// + /// Gets the first ancestor that matches the predicate. + /// + /// + /// + /// + public static SyntaxNode FirstAncestor(this SyntaxNode node, Func predicate, bool ascendOutOfTrivia = true) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - /// - /// Gets the first ancestor of the specified kinds. - /// - /// - /// - /// - /// - public static SyntaxNode FirstAncestorOrSelf( - this SyntaxNode node, - SyntaxKind kind1, - SyntaxKind kind2, - bool ascendOutOfTrivia = true) - { - return FirstAncestorOrSelf(node, f => f.IsKind(kind1, kind2), ascendOutOfTrivia); - } + if (predicate is null) + throw new ArgumentNullException(nameof(predicate)); - /// - /// Gets the first ancestor of the specified kinds. - /// - /// - /// - /// - /// - /// - public static SyntaxNode FirstAncestorOrSelf( - this SyntaxNode node, - SyntaxKind kind1, - SyntaxKind kind2, - SyntaxKind kind3, - bool ascendOutOfTrivia = true) - { - return FirstAncestorOrSelf(node, f => f.IsKind(kind1, kind2, kind3), ascendOutOfTrivia); - } + SyntaxNode parent = node.GetParent(ascendOutOfTrivia); - /// - /// Gets the first ancestor that matches the predicate. - /// - /// - /// - /// - public static SyntaxNode FirstAncestorOrSelf(this SyntaxNode node, Func predicate, bool ascendOutOfTrivia = true) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + if (parent is not null) + { + return FirstAncestorOrSelf(parent, predicate, ascendOutOfTrivia); + } + else + { + return null; + } + } - if (predicate == null) - throw new ArgumentNullException(nameof(predicate)); + /// + /// Gets the first ancestor of the specified kind. + /// + /// + /// + /// + public static SyntaxNode FirstAncestorOrSelf( + this SyntaxNode node, + SyntaxKind kind, + bool ascendOutOfTrivia = true) + { + return FirstAncestorOrSelf(node, f => f.IsKind(kind), ascendOutOfTrivia); + } - while (node != null) + /// + /// Gets the first ancestor of the specified kinds. + /// + /// + /// + /// + /// + public static SyntaxNode FirstAncestorOrSelf( + this SyntaxNode node, + SyntaxKind kind1, + SyntaxKind kind2, + bool ascendOutOfTrivia = true) { - if (predicate(node)) - return node; + return FirstAncestorOrSelf(node, f => f.IsKind(kind1, kind2), ascendOutOfTrivia); + } - node = node.GetParent(ascendOutOfTrivia); + /// + /// Gets the first ancestor of the specified kinds. + /// + /// + /// + /// + /// + /// + public static SyntaxNode FirstAncestorOrSelf( + this SyntaxNode node, + SyntaxKind kind1, + SyntaxKind kind2, + SyntaxKind kind3, + bool ascendOutOfTrivia = true) + { + return FirstAncestorOrSelf(node, f => f.IsKind(kind1, kind2, kind3), ascendOutOfTrivia); } - return null; - } + /// + /// Gets the first ancestor that matches the predicate. + /// + /// + /// + /// + public static SyntaxNode FirstAncestorOrSelf(this SyntaxNode node, Func predicate, bool ascendOutOfTrivia = true) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - internal static TRoot RemoveNode(this TRoot root, SyntaxNode node) where TRoot : SyntaxNode - { - return SyntaxRefactorings.RemoveNode(root, node); - } + if (predicate is null) + throw new ArgumentNullException(nameof(predicate)); - internal static TNode RemoveStatement(this TNode node, StatementSyntax statement) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + while (node is not null) + { + if (predicate(node)) + return node; - if (statement == null) - throw new ArgumentNullException(nameof(statement)); + node = node.GetParent(ascendOutOfTrivia); + } - return node.RemoveNode(statement); - } + return null; + } - internal static TNode RemoveModifier(this TNode node, SyntaxKind modifierKind) where TNode : SyntaxNode - { - return ModifierList.Remove(node, modifierKind); - } + internal static TRoot RemoveNode(this TRoot root, SyntaxNode node) where TRoot : SyntaxNode + { + return SyntaxRefactorings.RemoveNode(root, node); + } - internal static TNode RemoveModifiers(this TNode node, SyntaxKind modifierKind1, SyntaxKind modifierKind2) where TNode : SyntaxNode - { - return node - .RemoveModifier(modifierKind1) - .RemoveModifier(modifierKind2); - } + internal static TNode RemoveStatement(this TNode node, StatementSyntax statement) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - internal static TNode RemoveModifier(this TNode node, SyntaxToken modifier) where TNode : SyntaxNode - { - return ModifierList.Remove(node, modifier); - } + if (statement is null) + throw new ArgumentNullException(nameof(statement)); - internal static TNode InsertModifier(this TNode node, SyntaxKind modifierKind, IComparer comparer = null) where TNode : SyntaxNode - { - return ModifierList.Insert(node, modifierKind, comparer); - } + return node.RemoveNode(statement); + } - /// - /// Creates a new node with the trivia removed. - /// - /// - /// - /// - public static TNode RemoveTrivia(this TNode node, TextSpan? span = null) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + internal static TNode RemoveModifier(this TNode node, SyntaxKind modifierKind) where TNode : SyntaxNode + { + return ModifierList.Remove(node, modifierKind); + } - return SyntaxRefactorings.RemoveTrivia(node, span); - } + internal static TNode RemoveModifiers(this TNode node, SyntaxKind modifierKind1, SyntaxKind modifierKind2) where TNode : SyntaxNode + { + return node + .RemoveModifier(modifierKind1) + .RemoveModifier(modifierKind2); + } - /// - /// Creates a new node with the whitespace removed. - /// - /// - /// - /// - public static TNode RemoveWhitespace(this TNode node, TextSpan? span = null) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + internal static TNode RemoveModifier(this TNode node, SyntaxToken modifier) where TNode : SyntaxNode + { + return ModifierList.Remove(node, modifier); + } - return SyntaxRefactorings.RemoveWhitespace(node, span); - } + internal static TNode InsertModifier(this TNode node, SyntaxKind modifierKind, IComparer comparer = null) where TNode : SyntaxNode + { + return ModifierList.Insert(node, modifierKind, comparer); + } - /// - /// Creates a new node with the whitespace replaced. - /// - /// - /// - /// - /// - public static TNode ReplaceWhitespace(this TNode node, SyntaxTrivia replacement, TextSpan? span = null) where TNode : SyntaxNode - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + /// + /// Creates a new node with the trivia removed. + /// + /// + /// + /// + public static TNode RemoveTrivia(this TNode node, TextSpan? span = null) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - var replacer = new WhitespaceReplacer(replacement, span); + return SyntaxRefactorings.RemoveTrivia(node, span); + } - return (TNode)replacer.Visit(node); - } + /// + /// Creates a new node with the whitespace removed. + /// + /// + /// + /// + public static TNode RemoveWhitespace(this TNode node, TextSpan? span = null) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - internal static bool IsPartOfDocumentationComment(this SyntaxNode node) - { - while (node != null) + return SyntaxRefactorings.RemoveWhitespace(node, span); + } + + /// + /// Creates a new node with the whitespace replaced. + /// + /// + /// + /// + /// + public static TNode ReplaceWhitespace(this TNode node, SyntaxTrivia replacement, TextSpan? span = null) where TNode : SyntaxNode + { + if (node is null) + throw new ArgumentNullException(nameof(node)); + + var replacer = new WhitespaceReplacer(replacement, span); + + return (TNode)replacer.Visit(node); + } + + internal static bool IsPartOfDocumentationComment(this SyntaxNode node) { - if (node.IsStructuredTrivia - && SyntaxFacts.IsDocumentationCommentTrivia(node.Kind())) + while (node is not null) { - return true; + if (node.IsStructuredTrivia + && SyntaxFacts.IsDocumentationCommentTrivia(node.Kind())) + { + return true; + } + + node = node.Parent; } - node = node.Parent; + return false; } - return false; - } - - /// - /// Determines if the specified node is contained in an expression tree. - /// - /// - /// - /// - public static bool IsInExpressionTree( - this SyntaxNode node, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - for (SyntaxNode current = node; current != null; current = current.Parent) + /// + /// Determines if the specified node is contained in an expression tree. + /// + /// + /// + /// + public static bool IsInExpressionTree( + this SyntaxNode node, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) { - switch (current.Kind()) + for (SyntaxNode current = node; current is not null; current = current.Parent) { - case SyntaxKind.SimpleLambdaExpression: - case SyntaxKind.ParenthesizedLambdaExpression: - { - if (semanticModel - .GetTypeInfo(current, cancellationToken) - .ConvertedType? - .OriginalDefinition - .HasMetadataName(MetadataNames.System_Linq_Expressions_Expression_T) == true) + switch (current.Kind()) + { + case SyntaxKind.SimpleLambdaExpression: + case SyntaxKind.ParenthesizedLambdaExpression: { - return true; + if (semanticModel + .GetTypeInfo(current, cancellationToken) + .ConvertedType? + .OriginalDefinition + .HasMetadataName(MetadataNames.System_Linq_Expressions_Expression_T) == true) + { + return true; + } + + break; } + case SyntaxKind.AscendingOrdering: + case SyntaxKind.DescendingOrdering: + case SyntaxKind.GroupClause: + case SyntaxKind.SelectClause: + { + SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(current, cancellationToken); - break; - } - case SyntaxKind.AscendingOrdering: - case SyntaxKind.DescendingOrdering: - case SyntaxKind.GroupClause: - case SyntaxKind.SelectClause: - { - SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(current, cancellationToken); + if (IsMethodThatAcceptsExpressionAsFirstParameter(symbolInfo)) + return true; - if (IsMethodThatAcceptsExpressionAsFirstParameter(symbolInfo)) - return true; + 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); - 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; + } - if (IsMethodThatAcceptsExpressionAsFirstParameter(clauseInfo.CastInfo) - || IsMethodThatAcceptsExpressionAsFirstParameter(clauseInfo.OperationInfo)) + break; + } + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.ArrowExpressionClause: + case SyntaxKind.Block: + case SyntaxKind.BreakStatement: + case SyntaxKind.CatchClause: + case SyntaxKind.CatchFilterClause: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ConstructorDeclaration: + case SyntaxKind.ContinueStatement: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.DelegateDeclaration: + case SyntaxKind.DestructorDeclaration: + case SyntaxKind.DoStatement: + case SyntaxKind.EmptyStatement: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.ExpressionStatement: + case SyntaxKind.FieldDeclaration: + case SyntaxKind.FixedStatement: + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + case SyntaxKind.ForStatement: + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.GlobalStatement: + case SyntaxKind.GotoCaseStatement: + case SyntaxKind.GotoDefaultStatement: + case SyntaxKind.GotoStatement: + case SyntaxKind.CheckedStatement: + case SyntaxKind.IfStatement: + case SyntaxKind.IncompleteMember: + case SyntaxKind.IndexerDeclaration: + case SyntaxKind.InitAccessorDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.LabeledStatement: + case SyntaxKind.LocalDeclarationStatement: + case SyntaxKind.LocalFunctionStatement: + case SyntaxKind.LockStatement: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.ReturnStatement: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.StructDeclaration: + case SyntaxKind.RecordStructDeclaration: + case SyntaxKind.SwitchStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.TryStatement: + case SyntaxKind.UncheckedStatement: + case SyntaxKind.UnknownAccessorDeclaration: + case SyntaxKind.UnsafeStatement: + case SyntaxKind.UsingStatement: + case SyntaxKind.WhileStatement: + case SyntaxKind.YieldBreakStatement: + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.IfDirectiveTrivia: + case SyntaxKind.ElifDirectiveTrivia: + case SyntaxKind.WhenClause: { - return true; + return false; } - - break; - } - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.ArrowExpressionClause: - case SyntaxKind.Block: - case SyntaxKind.BreakStatement: - case SyntaxKind.CatchClause: - case SyntaxKind.CatchFilterClause: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.ConstructorDeclaration: - case SyntaxKind.ContinueStatement: - case SyntaxKind.ConversionOperatorDeclaration: - case SyntaxKind.DelegateDeclaration: - case SyntaxKind.DestructorDeclaration: - case SyntaxKind.DoStatement: - case SyntaxKind.EmptyStatement: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.EventDeclaration: - case SyntaxKind.EventFieldDeclaration: - case SyntaxKind.ExpressionStatement: - case SyntaxKind.FieldDeclaration: - case SyntaxKind.FixedStatement: - case SyntaxKind.ForEachStatement: - case SyntaxKind.ForEachVariableStatement: - case SyntaxKind.ForStatement: - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.GlobalStatement: - case SyntaxKind.GotoCaseStatement: - case SyntaxKind.GotoDefaultStatement: - case SyntaxKind.GotoStatement: - case SyntaxKind.CheckedStatement: - case SyntaxKind.IfStatement: - case SyntaxKind.IncompleteMember: - case SyntaxKind.IndexerDeclaration: - case SyntaxKind.InitAccessorDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.LabeledStatement: - case SyntaxKind.LocalDeclarationStatement: - case SyntaxKind.LocalFunctionStatement: - case SyntaxKind.LockStatement: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.OperatorDeclaration: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.ReturnStatement: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.StructDeclaration: - case SyntaxKind.RecordStructDeclaration: - case SyntaxKind.SwitchStatement: - case SyntaxKind.ThrowStatement: - case SyntaxKind.TryStatement: - case SyntaxKind.UncheckedStatement: - case SyntaxKind.UnknownAccessorDeclaration: - case SyntaxKind.UnsafeStatement: - case SyntaxKind.UsingStatement: - case SyntaxKind.WhileStatement: - case SyntaxKind.YieldBreakStatement: - case SyntaxKind.YieldReturnStatement: - case SyntaxKind.IfDirectiveTrivia: - case SyntaxKind.ElifDirectiveTrivia: - case SyntaxKind.WhenClause: - { - return false; - } #if DEBUG - case SyntaxKind.Argument: - case SyntaxKind.ArgumentList: - case SyntaxKind.BracketedArgumentList: - case SyntaxKind.ArrayRankSpecifier: - case SyntaxKind.EqualsValueClause: - case SyntaxKind.Interpolation: - case SyntaxKind.SwitchExpressionArm: - case SyntaxKind.VariableDeclaration: - case SyntaxKind.VariableDeclarator: - case SyntaxKind.QueryBody: - case SyntaxKind.AnonymousObjectMemberDeclarator: - { - break; - } - default: - { - SyntaxDebug.Assert(current is ExpressionSyntax, current); - break; - } + case SyntaxKind.Argument: + case SyntaxKind.ArgumentList: + case SyntaxKind.BracketedArgumentList: + case SyntaxKind.ArrayRankSpecifier: + case SyntaxKind.EqualsValueClause: + case SyntaxKind.Interpolation: + case SyntaxKind.SwitchExpressionArm: + case SyntaxKind.VariableDeclaration: + case SyntaxKind.VariableDeclarator: + case SyntaxKind.QueryBody: + case SyntaxKind.AnonymousObjectMemberDeclarator: + { + break; + } + default: + { + SyntaxDebug.Assert(current is ExpressionSyntax, current); + break; + } #endif + } } - } - return false; + return false; - static bool IsMethodThatAcceptsExpressionAsFirstParameter(SymbolInfo info) - { - ISymbol symbol = info.Symbol; + static bool IsMethodThatAcceptsExpressionAsFirstParameter(SymbolInfo info) + { + ISymbol symbol = info.Symbol; + + if (symbol is not null) + return IsMethodThatAcceptsExpressionAsFirstParameter2(symbol); + + foreach (ISymbol candidateSymbol in info.CandidateSymbols) + { + if (IsMethodThatAcceptsExpressionAsFirstParameter2(candidateSymbol)) + return true; + } - if (symbol != null) - return IsMethodThatAcceptsExpressionAsFirstParameter2(symbol); + return false; + } - foreach (ISymbol candidateSymbol in info.CandidateSymbols) + static bool IsMethodThatAcceptsExpressionAsFirstParameter2(ISymbol symbol) { - if (IsMethodThatAcceptsExpressionAsFirstParameter2(candidateSymbol)) - return true; + return symbol is IMethodSymbol methodSymbol + && methodSymbol + .Parameters + .FirstOrDefault()? + .Type? + .OriginalDefinition + .HasMetadataName(MetadataNames.System_Linq_Expressions_Expression_T) == true; } - - return false; } - static bool IsMethodThatAcceptsExpressionAsFirstParameter2(ISymbol symbol) + /// + /// Returns true if the specified node contains #if directive but it does not contain related #endif directive. + /// + /// + public static bool ContainsUnbalancedIfElseDirectives(this SyntaxNode node) { - return symbol is IMethodSymbol methodSymbol - && methodSymbol - .Parameters - .FirstOrDefault()? - .Type? - .OriginalDefinition - .HasMetadataName(MetadataNames.System_Linq_Expressions_Expression_T) == true; + return ContainsUnbalancedIfElseDirectives(node, node.FullSpan); } - } - - /// - /// Returns true if the specified node contains #if directive but it does not contain related #endif directive. - /// - /// - public static bool ContainsUnbalancedIfElseDirectives(this SyntaxNode node) - { - return ContainsUnbalancedIfElseDirectives(node, node.FullSpan); - } - - /// - /// Returns true if the specified node contains #if directive but it does not contain related #endif directive. - /// - /// - /// - public static bool ContainsUnbalancedIfElseDirectives(this SyntaxNode node, TextSpan span) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); - - if (!node.FullSpan.Contains(span)) - throw new ArgumentOutOfRangeException(nameof(span)); - if (node.ContainsDirectives) + /// + /// Returns true if the specified node contains #if directive but it does not contain related #endif directive. + /// + /// + /// + public static bool ContainsUnbalancedIfElseDirectives(this SyntaxNode node, TextSpan span) { - DirectiveTriviaSyntax first = node.GetFirstDirective(span, f => CSharpFacts.IsIfElseDirective(f.Kind())); + if (node is null) + throw new ArgumentNullException(nameof(node)); - if (first != null) + if (!node.FullSpan.Contains(span)) + throw new ArgumentOutOfRangeException(nameof(span)); + + if (node.ContainsDirectives) { - if (!first.IsKind(SyntaxKind.IfDirectiveTrivia)) - return true; + DirectiveTriviaSyntax first = node.GetFirstDirective(span, f => CSharpFacts.IsIfElseDirective(f.Kind())); - DirectiveTriviaSyntax last = node.GetLastDirective(span, f => CSharpFacts.IsIfElseDirective(f.Kind())); + if (first is not null) + { + if (!first.IsKind(SyntaxKind.IfDirectiveTrivia)) + return true; - if (last == first) - return true; + DirectiveTriviaSyntax last = node.GetLastDirective(span, f => CSharpFacts.IsIfElseDirective(f.Kind())); - if (!last.IsKind(SyntaxKind.EndIfDirectiveTrivia)) - return true; + if (last == first) + return true; - DirectiveTriviaSyntax d = first; + if (!last.IsKind(SyntaxKind.EndIfDirectiveTrivia)) + return true; - do - { - d = d.GetNextRelatedDirective(); + DirectiveTriviaSyntax d = first; - if (d == null) - return true; + do + { + d = d.GetNextRelatedDirective(); - if (!d.FullSpan.OverlapsWith(span)) - return true; + if (d is null) + return true; + + if (!d.FullSpan.OverlapsWith(span)) + return true; + } + while (d != last); } - while (d != last); } - } - return false; - } - - /// - /// Gets the first directive of the tree rooted by this node. - /// - /// - /// - /// - public static DirectiveTriviaSyntax GetFirstDirective(this SyntaxNode node, TextSpan span, Func predicate = null) - { - DirectiveTriviaSyntax directive = node.GetFirstDirective(predicate); - - if (directive == null) - return null; + return false; + } - while (!directive.FullSpan.OverlapsWith(span)) + /// + /// Gets the first directive of the tree rooted by this node. + /// + /// + /// + /// + public static DirectiveTriviaSyntax GetFirstDirective(this SyntaxNode node, TextSpan span, Func predicate = null) { - directive = directive.GetNextDirective(predicate); + DirectiveTriviaSyntax directive = node.GetFirstDirective(predicate); - if (directive == null) + if (directive is null) return null; - if (!node.FullSpan.Contains(directive.FullSpan)) - return null; - } + while (!directive.FullSpan.OverlapsWith(span)) + { + directive = directive.GetNextDirective(predicate); - return directive; - } + if (directive is null) + return null; - internal static DirectiveTriviaSyntax GetLastDirective(this SyntaxNode node, TextSpan span, Func predicate = null) - { - DirectiveTriviaSyntax directive = node.GetLastDirective(predicate); + if (!node.FullSpan.Contains(directive.FullSpan)) + return null; + } - if (directive == null) - return null; + return directive; + } - while (!directive.FullSpan.OverlapsWith(span)) + internal static DirectiveTriviaSyntax GetLastDirective(this SyntaxNode node, TextSpan span, Func predicate = null) { - directive = directive.GetPreviousDirective(predicate); - - if (directive == null) - return null; + DirectiveTriviaSyntax directive = node.GetLastDirective(predicate); - if (!node.FullSpan.Contains(directive.FullSpan)) + if (directive is null) return null; - } - return directive; - } - #endregion SyntaxNode - - #region SyntaxToken - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2) - { - SyntaxKind kind = token.Kind(); + while (!directive.FullSpan.OverlapsWith(span)) + { + directive = directive.GetPreviousDirective(predicate); - return kind == kind1 - || kind == kind2; - } + if (directive is null) + return null; - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) - { - SyntaxKind kind = token.Kind(); + if (!node.FullSpan.Contains(directive.FullSpan)) + return null; + } - return kind == kind1 - || kind == kind2 - || kind == kind3; - } + return directive; + } + #endregion SyntaxNode + + #region SyntaxToken + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2) + { + SyntaxKind kind = token.Kind(); - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) - { - SyntaxKind kind = token.Kind(); + return kind == kind1 + || kind == kind2; + } - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4; - } + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) + { + SyntaxKind kind = token.Kind(); - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) - { - SyntaxKind kind = token.Kind(); + return kind == kind1 + || kind == kind2 + || kind == kind3; + } - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4 - || kind == kind5; - } + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) + { + SyntaxKind kind = token.Kind(); - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) - { - SyntaxKind kind = token.Kind(); - - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4 - || kind == kind5 - || kind == kind6; - } + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4; + } - /// - /// Removes all leading whitespace from the leading trivia and returns a new token with the new leading trivia. - /// and is considered to be a whitespace. - /// Returns the same token if there is nothing to trim. - /// - /// - public static SyntaxToken TrimLeadingTrivia(this SyntaxToken token) - { - SyntaxTriviaList trivia = token.LeadingTrivia; + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) + { + SyntaxKind kind = token.Kind(); - int count = trivia.Count; + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4 + || kind == kind5; + } - if (count > 0) + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) { - SyntaxTriviaList newTrivia = trivia.TrimStart(); - - if (trivia.Count != newTrivia.Count) - return token.WithLeadingTrivia(newTrivia); + SyntaxKind kind = token.Kind(); + + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4 + || kind == kind5 + || kind == kind6; } - return token; - } + /// + /// Removes all leading whitespace from the leading trivia and returns a new token with the new leading trivia. + /// and is considered to be a whitespace. + /// Returns the same token if there is nothing to trim. + /// + /// + public static SyntaxToken TrimLeadingTrivia(this SyntaxToken token) + { + SyntaxTriviaList trivia = token.LeadingTrivia; - /// - /// Removes all trailing whitespace from the trailing trivia and returns a new token with the new trailing trivia. - /// and is considered to be a whitespace. - /// Returns the same token if there is nothing to trim. - /// - /// - public static SyntaxToken TrimTrailingTrivia(this SyntaxToken token) - { - SyntaxTriviaList trivia = token.TrailingTrivia; + int count = trivia.Count; - int count = trivia.Count; + if (count > 0) + { + SyntaxTriviaList newTrivia = trivia.TrimStart(); - if (count > 0) - { - SyntaxTriviaList newTrivia = trivia.TrimEnd(); + if (trivia.Count != newTrivia.Count) + return token.WithLeadingTrivia(newTrivia); + } - if (trivia.Count != newTrivia.Count) - return token.WithTrailingTrivia(newTrivia); + return token; } - return token; - } - - /// - /// Removes all leading whitespace from the leading trivia and all trailing whitespace from the trailing trivia and returns a new token with the new trivia. - /// and is considered to be a whitespace. - /// Returns the same token if there is nothing to trim. - /// - /// - public static SyntaxToken TrimTrivia(this SyntaxToken token) - { - return token - .TrimLeadingTrivia() - .TrimTrailingTrivia(); - } - - /// - /// Returns true if a token of the specified kind is in the . - /// - /// - /// - public static bool Contains(this SyntaxTokenList tokenList, SyntaxKind kind) - { - return tokenList.IndexOf(kind) != -1; - } + /// + /// Removes all trailing whitespace from the trailing trivia and returns a new token with the new trailing trivia. + /// and is considered to be a whitespace. + /// Returns the same token if there is nothing to trim. + /// + /// + public static SyntaxToken TrimTrailingTrivia(this SyntaxToken token) + { + SyntaxTriviaList trivia = token.TrailingTrivia; - /// - /// Returns true if a token of the specified kinds is in the . - /// - /// - /// - /// - public static bool ContainsAny(this SyntaxTokenList tokenList, SyntaxKind kind1, SyntaxKind kind2) - { - return ContainsAny(tokenList, (int)kind1, (int)kind2); - } + int count = trivia.Count; - /// - /// Returns true if a token of the specified kinds is in the . - /// - /// - /// - /// - /// - public static bool ContainsAny(this SyntaxTokenList tokenList, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) - { - return ContainsAny(tokenList, (int)kind1, (int)kind2, (int)kind3); - } + if (count > 0) + { + SyntaxTriviaList newTrivia = trivia.TrimEnd(); - /// - /// Returns true if a token of the specified kinds is in the . - /// - /// - /// - /// - /// - /// - public static bool ContainsAny(this SyntaxTokenList tokenList, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) - { - return ContainsAny(tokenList, (int)kind1, (int)kind2, (int)kind3, (int)kind4); - } + if (trivia.Count != newTrivia.Count) + return token.WithTrailingTrivia(newTrivia); + } - /// - /// Returns true if a token of the specified kinds is in the . - /// - /// - /// - /// - /// - /// - /// - public static bool ContainsAny(this SyntaxTokenList tokenList, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) - { - return ContainsAny(tokenList, (int)kind1, (int)kind2, (int)kind3, (int)kind4, (int)kind5); - } + return token; + } - internal static bool ContainsAny(this SyntaxTokenList tokenList, int rawKind1, int rawKind2) - { - foreach (SyntaxToken token in tokenList) + /// + /// Removes all leading whitespace from the leading trivia and all trailing whitespace from the trailing trivia and returns a new token with the new trivia. + /// and is considered to be a whitespace. + /// Returns the same token if there is nothing to trim. + /// + /// + public static SyntaxToken TrimTrivia(this SyntaxToken token) { - int rawKind = token.RawKind; - - if (rawKind == rawKind1 - || rawKind == rawKind2) - { - return true; - } + return token + .TrimLeadingTrivia() + .TrimTrailingTrivia(); } - return false; - } + /// + /// Returns true if a token of the specified kind is in the . + /// + /// + /// + public static bool Contains(this SyntaxTokenList tokenList, SyntaxKind kind) + { + return tokenList.IndexOf(kind) != -1; + } - internal static bool ContainsAny(this SyntaxTokenList tokenList, int rawKind1, int rawKind2, int rawKind3) - { - foreach (SyntaxToken token in tokenList) + /// + /// Returns true if a token of the specified kinds is in the . + /// + /// + /// + /// + public static bool ContainsAny(this SyntaxTokenList tokenList, SyntaxKind kind1, SyntaxKind kind2) { - int rawKind = token.RawKind; + return ContainsAny(tokenList, (int)kind1, (int)kind2); + } - if (rawKind == rawKind1 - || rawKind == rawKind2 - || rawKind == rawKind3) - { - return true; - } + /// + /// Returns true if a token of the specified kinds is in the . + /// + /// + /// + /// + /// + public static bool ContainsAny(this SyntaxTokenList tokenList, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) + { + return ContainsAny(tokenList, (int)kind1, (int)kind2, (int)kind3); } - return false; - } + /// + /// Returns true if a token of the specified kinds is in the . + /// + /// + /// + /// + /// + /// + public static bool ContainsAny(this SyntaxTokenList tokenList, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) + { + return ContainsAny(tokenList, (int)kind1, (int)kind2, (int)kind3, (int)kind4); + } - internal static bool ContainsAny(this SyntaxTokenList tokenList, int rawKind1, int rawKind2, int rawKind3, int rawKind4) - { - foreach (SyntaxToken token in tokenList) + /// + /// Returns true if a token of the specified kinds is in the . + /// + /// + /// + /// + /// + /// + /// + public static bool ContainsAny(this SyntaxTokenList tokenList, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) { - int rawKind = token.RawKind; + return ContainsAny(tokenList, (int)kind1, (int)kind2, (int)kind3, (int)kind4, (int)kind5); + } - if (rawKind == rawKind1 - || rawKind == rawKind2 - || rawKind == rawKind3 - || rawKind == rawKind4) + internal static bool ContainsAny(this SyntaxTokenList tokenList, int rawKind1, int rawKind2) + { + foreach (SyntaxToken token in tokenList) { - return true; + int rawKind = token.RawKind; + + if (rawKind == rawKind1 + || rawKind == rawKind2) + { + return true; + } } - } - return false; - } + return false; + } - internal static bool ContainsAny(this SyntaxTokenList tokenList, int rawKind1, int rawKind2, int rawKind3, int rawKind4, int rawKind5) - { - foreach (SyntaxToken token in tokenList) + internal static bool ContainsAny(this SyntaxTokenList tokenList, int rawKind1, int rawKind2, int rawKind3) { - int rawKind = token.RawKind; - - if (rawKind == rawKind1 - || rawKind == rawKind2 - || rawKind == rawKind3 - || rawKind == rawKind4 - || rawKind == rawKind5) + foreach (SyntaxToken token in tokenList) { - return true; + int rawKind = token.RawKind; + + if (rawKind == rawKind1 + || rawKind == rawKind2 + || rawKind == rawKind3) + { + return true; + } } - } - return false; - } + return false; + } - /// - /// Returns true if a token parent's kind is the specified kind. - /// - /// - /// - public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind) - { - return token.Parent.IsKind(kind); - } + internal static bool ContainsAny(this SyntaxTokenList tokenList, int rawKind1, int rawKind2, int rawKind3, int rawKind4) + { + foreach (SyntaxToken token in tokenList) + { + int rawKind = token.RawKind; - /// - /// Returns true if a token parent's kind is one of the specified kinds. - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2) - { - return IsKind(token.Parent, kind1, kind2); - } + if (rawKind == rawKind1 + || rawKind == rawKind2 + || rawKind == rawKind3 + || rawKind == rawKind4) + { + return true; + } + } - /// - /// Returns true if a token parent's kind is one of the specified kinds. - /// - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) - { - return IsKind(token.Parent, kind1, kind2, kind3); - } + return false; + } - /// - /// Returns true if a token parent's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) - { - return IsKind(token.Parent, kind1, kind2, kind3, kind4); - } + internal static bool ContainsAny(this SyntaxTokenList tokenList, int rawKind1, int rawKind2, int rawKind3, int rawKind4, int rawKind5) + { + foreach (SyntaxToken token in tokenList) + { + int rawKind = token.RawKind; - /// - /// Returns true if a token parent's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) - { - return IsKind(token.Parent, kind1, kind2, kind3, kind4, kind5); - } + if (rawKind == rawKind1 + || rawKind == rawKind2 + || rawKind == rawKind3 + || rawKind == rawKind4 + || rawKind == rawKind5) + { + return true; + } + } - /// - /// Returns true if a token parent's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - /// - public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) - { - return IsKind(token.Parent, kind1, kind2, kind3, kind4, kind5, kind6); - } - #endregion SyntaxToken + return false; + } - #region SyntaxTokenList - /// - /// Searches for a token of the specified kind and returns the first occurrence within the entire . - /// - /// - /// - public static SyntaxToken Find(this SyntaxTokenList tokenList, SyntaxKind kind) - { - foreach (SyntaxToken token in tokenList) + /// + /// Returns true if a token parent's kind is the specified kind. + /// + /// + /// + public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind) { - if (token.IsKind(kind)) - return token; + return token.Parent.IsKind(kind); } - return default; - } - - internal static SyntaxTokenList Replace(this SyntaxTokenList tokens, SyntaxKind kind, SyntaxKind newKind) - { - int i = 0; - foreach (SyntaxToken token in tokens) + /// + /// Returns true if a token parent's kind is one of the specified kinds. + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2) { - if (token.IsKind(kind)) - return tokens.ReplaceAt(i, Token(newKind).WithTriviaFrom(token)); - - i++; + return IsKind(token.Parent, kind1, kind2); } - return tokens; - } - - /// - /// Creates a new list with tokens in the specified range removed. - /// - /// - /// An index of the first element to remove. - /// A number of elements to remove. - public static SyntaxTokenList RemoveRange( - this SyntaxTokenList list, - int index, - int count) - { - return ReplaceRange(list, index, count, Empty.ReadOnlyList()); - } + /// + /// Returns true if a token parent's kind is one of the specified kinds. + /// + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) + { + return IsKind(token.Parent, kind1, kind2, kind3); + } - /// - /// Creates a new list with the tokens in the specified range replaced with new tokens. - /// - /// - /// - /// - /// - public static SyntaxTokenList ReplaceRange( - this SyntaxTokenList list, - int index, - int count, - IEnumerable newTokens) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), index, ""); + /// + /// Returns true if a token parent's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) + { + return IsKind(token.Parent, kind1, kind2, kind3, kind4); + } - if (count < 0 - || index + count > list.Count) + /// + /// Returns true if a token parent's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) { - throw new ArgumentOutOfRangeException(nameof(count), count, ""); + return IsKind(token.Parent, kind1, kind2, kind3, kind4, kind5); } - if (newTokens == null) - throw new ArgumentNullException(nameof(newTokens)); + /// + /// Returns true if a token parent's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + /// + public static bool IsParentKind(this SyntaxToken token, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) + { + return IsKind(token.Parent, kind1, kind2, kind3, kind4, kind5, kind6); + } + #endregion SyntaxToken + + #region SyntaxTokenList + /// + /// Searches for a token of the specified kind and returns the first occurrence within the entire . + /// + /// + /// + public static SyntaxToken Find(this SyntaxTokenList tokenList, SyntaxKind kind) + { + foreach (SyntaxToken token in tokenList) + { + if (token.IsKind(kind)) + return token; + } - return TokenList(ReplaceRange()); + return default; + } - IEnumerable ReplaceRange() + internal static SyntaxTokenList Replace(this SyntaxTokenList tokens, SyntaxKind kind, SyntaxKind newKind) { - SyntaxTokenList.Enumerator en = list.GetEnumerator(); - int i = 0; - - while (i < index - && en.MoveNext()) + foreach (SyntaxToken token in tokens) { - yield return en.Current; + if (token.IsKind(kind)) + return tokens.ReplaceAt(i, Token(newKind).WithTriviaFrom(token)); + i++; } - int endIndex = index + count; + return tokens; + } - while (i < endIndex - && en.MoveNext()) - { - i++; - } + /// + /// Creates a new list with tokens in the specified range removed. + /// + /// + /// An index of the first element to remove. + /// A number of elements to remove. + public static SyntaxTokenList RemoveRange( + this SyntaxTokenList list, + int index, + int count) + { + return ReplaceRange(list, index, count, Empty.ReadOnlyList()); + } - if ((newTokens as ICollection)?.Count != 0) + /// + /// Creates a new list with the tokens in the specified range replaced with new tokens. + /// + /// + /// + /// + /// + public static SyntaxTokenList ReplaceRange( + this SyntaxTokenList list, + int index, + int count, + IEnumerable newTokens) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, ""); + + if (count < 0 + || index + count > list.Count) { - foreach (SyntaxToken token in newTokens) - yield return token; + throw new ArgumentOutOfRangeException(nameof(count), count, ""); } - while (en.MoveNext()) - yield return en.Current; - } - } - #endregion SyntaxTokenList + if (newTokens is null) + throw new ArgumentNullException(nameof(newTokens)); - #region SyntaxTrivia - /// - /// Returns true if a trivia's kind is one of the specified kinds. - /// - /// - /// - /// - public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2) - { - SyntaxKind kind = trivia.Kind(); + return TokenList(ReplaceRange()); - return kind == kind1 - || kind == kind2; - } + IEnumerable ReplaceRange() + { + SyntaxTokenList.Enumerator en = list.GetEnumerator(); - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) - { - SyntaxKind kind = trivia.Kind(); + int i = 0; - return kind == kind1 - || kind == kind2 - || kind == kind3; - } + while (i < index + && en.MoveNext()) + { + yield return en.Current; + i++; + } + + int endIndex = index + count; - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) - { - SyntaxKind kind = trivia.Kind(); + while (i < endIndex + && en.MoveNext()) + { + i++; + } - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4; - } + if ((newTokens as ICollection)?.Count != 0) + { + foreach (SyntaxToken token in newTokens) + yield return token; + } - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) - { - SyntaxKind kind = trivia.Kind(); + while (en.MoveNext()) + yield return en.Current; + } + } + #endregion SyntaxTokenList + + #region SyntaxTrivia + /// + /// Returns true if a trivia's kind is one of the specified kinds. + /// + /// + /// + /// + public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2) + { + SyntaxKind kind = trivia.Kind(); - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4 - || kind == kind5; - } + return kind == kind1 + || kind == kind2; + } - /// - /// Returns true if a token's kind is one of the specified kinds. - /// - /// - /// - /// - /// - /// - /// - /// - public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) - { - SyntaxKind kind = trivia.Kind(); - - return kind == kind1 - || kind == kind2 - || kind == kind3 - || kind == kind4 - || kind == kind5 - || kind == kind6; - } + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) + { + SyntaxKind kind = trivia.Kind(); - /// - /// Returns true if the trivia is . - /// - /// - public static bool IsWhitespaceTrivia(this SyntaxTrivia trivia) - { - return trivia.IsKind(SyntaxKind.WhitespaceTrivia); - } + return kind == kind1 + || kind == kind2 + || kind == kind3; + } - /// - /// Returns true if the trivia is . - /// - /// - public static bool IsEndOfLineTrivia(this SyntaxTrivia trivia) - { - return trivia.IsKind(SyntaxKind.EndOfLineTrivia); - } + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) + { + SyntaxKind kind = trivia.Kind(); - /// - /// Returns true if the trivia is either or . - /// - /// - public static bool IsWhitespaceOrEndOfLineTrivia(this SyntaxTrivia trivia) - { - return trivia.IsKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia); - } + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4; + } - /// - /// Returns true if the trivia is a documentation comment trivia. - /// - /// - internal static bool IsDocumentationCommentTrivia(this SyntaxTrivia trivia) - { - return SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind()); - } + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) + { + SyntaxKind kind = trivia.Kind(); - internal static bool IsElasticMarker(this SyntaxTrivia trivia) - { - return trivia.IsWhitespaceTrivia() - && trivia.Span.IsEmpty - && trivia.HasAnnotation(SyntaxAnnotation.ElasticAnnotation); - } - #endregion SyntaxTrivia + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4 + || kind == kind5; + } - #region SyntaxTriviaList - /// - /// Searches for a trivia of the specified kind and returns the zero-based index of the last occurrence within the entire . - /// - /// - /// - public static int LastIndexOf(this SyntaxTriviaList triviaList, SyntaxKind kind) - { - for (int i = triviaList.Count - 1; i >= 0; i--) + /// + /// Returns true if a token's kind is one of the specified kinds. + /// + /// + /// + /// + /// + /// + /// + /// + public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) { - if (triviaList[i].IsKind(kind)) - return i; + SyntaxKind kind = trivia.Kind(); + + return kind == kind1 + || kind == kind2 + || kind == kind3 + || kind == kind4 + || kind == kind5 + || kind == kind6; } - return -1; - } + /// + /// Returns true if the trivia is . + /// + /// + public static bool IsWhitespaceTrivia(this SyntaxTrivia trivia) + { + return trivia.IsKind(SyntaxKind.WhitespaceTrivia); + } - /// - /// Returns true if a trivia of the specified kind is in the . - /// - /// - /// - public static bool Contains(this SyntaxTriviaList triviaList, SyntaxKind kind) - { - return triviaList.IndexOf(kind) != -1; - } + /// + /// Returns true if the trivia is . + /// + /// + public static bool IsEndOfLineTrivia(this SyntaxTrivia trivia) + { + return trivia.IsKind(SyntaxKind.EndOfLineTrivia); + } - /// - /// Searches for a trivia of the specified kind and returns the first occurrence within the entire . - /// - /// - /// - public static SyntaxTrivia Find(this SyntaxTriviaList triviaList, SyntaxKind kind) - { - foreach (SyntaxTrivia trivia in triviaList) + /// + /// Returns true if the trivia is either or . + /// + /// + public static bool IsWhitespaceOrEndOfLineTrivia(this SyntaxTrivia trivia) { - if (trivia.IsKind(kind)) - return trivia; + return trivia.IsKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia); } - return default; - } + /// + /// Returns true if the trivia is a documentation comment trivia. + /// + /// + internal static bool IsDocumentationCommentTrivia(this SyntaxTrivia trivia) + { + return SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind()); + } - /// - /// Returns true if the list of either empty or contains only whitespace ( or ). - /// - /// - public static bool IsEmptyOrWhitespace(this SyntaxTriviaList triviaList) - { - foreach (SyntaxTrivia trivia in triviaList) + internal static bool IsElasticMarker(this SyntaxTrivia trivia) { - if (!trivia.IsWhitespaceOrEndOfLineTrivia()) - return false; + return trivia.IsWhitespaceTrivia() + && trivia.Span.IsEmpty + && trivia.HasAnnotation(SyntaxAnnotation.ElasticAnnotation); } + #endregion SyntaxTrivia + + #region SyntaxTriviaList + /// + /// Searches for a trivia of the specified kind and returns the zero-based index of the last occurrence within the entire . + /// + /// + /// + public static int LastIndexOf(this SyntaxTriviaList triviaList, SyntaxKind kind) + { + for (int i = triviaList.Count - 1; i >= 0; i--) + { + if (triviaList[i].IsKind(kind)) + return i; + } - return true; - } + return -1; + } - internal static bool IsEmptyOrSingleWhitespaceTrivia(this SyntaxTriviaList triviaList) - { - return !triviaList.Any() - || (triviaList.Count == 1 && triviaList[0].IsWhitespaceTrivia()); - } + /// + /// Returns true if a trivia of the specified kind is in the . + /// + /// + /// + public static bool Contains(this SyntaxTriviaList triviaList, SyntaxKind kind) + { + return triviaList.IndexOf(kind) != -1; + } - internal static SyntaxTriviaList EmptyIfWhitespace(this SyntaxTriviaList triviaList) - { - return (triviaList.IsEmptyOrWhitespace()) ? default : triviaList; - } + /// + /// Searches for a trivia of the specified kind and returns the first occurrence within the entire . + /// + /// + /// + public static SyntaxTrivia Find(this SyntaxTriviaList triviaList, SyntaxKind kind) + { + foreach (SyntaxTrivia trivia in triviaList) + { + if (trivia.IsKind(kind)) + return trivia; + } - internal static bool IsSingleElasticMarker(this SyntaxTriviaList triviaList) - { - return triviaList.Count == 1 - && triviaList[0].IsElasticMarker(); - } + return default; + } - /// - /// Creates a new list with trivia in the specified range removed. - /// - /// - /// An index of the first element to remove. - /// A number of elements to remove. - public static SyntaxTriviaList RemoveRange( - this SyntaxTriviaList list, - int index, - int count) - { - return ReplaceRange(list, index, count, Empty.ReadOnlyList()); - } + /// + /// Returns true if the list of either empty or contains only whitespace ( or ). + /// + /// + public static bool IsEmptyOrWhitespace(this SyntaxTriviaList triviaList) + { + foreach (SyntaxTrivia trivia in triviaList) + { + if (!trivia.IsWhitespaceOrEndOfLineTrivia()) + return false; + } - /// - /// Creates a new list with the trivia in the specified range replaced with new trivia. - /// - /// - /// - /// - /// - public static SyntaxTriviaList ReplaceRange( - this SyntaxTriviaList list, - int index, - int count, - IEnumerable newTrivia) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index), index, ""); + return true; + } - if (count < 0 - || index + count > list.Count) + internal static bool IsEmptyOrSingleWhitespaceTrivia(this SyntaxTriviaList triviaList) { - throw new ArgumentOutOfRangeException(nameof(count), count, ""); + return !triviaList.Any() + || (triviaList.Count == 1 && triviaList[0].IsWhitespaceTrivia()); } - if (newTrivia == null) - throw new ArgumentNullException(nameof(newTrivia)); + internal static SyntaxTriviaList EmptyIfWhitespace(this SyntaxTriviaList triviaList) + { + return (triviaList.IsEmptyOrWhitespace()) ? default : triviaList; + } - return TriviaList(ReplaceRange()); + internal static bool IsSingleElasticMarker(this SyntaxTriviaList triviaList) + { + return triviaList.Count == 1 + && triviaList[0].IsElasticMarker(); + } - IEnumerable ReplaceRange() + /// + /// Creates a new list with trivia in the specified range removed. + /// + /// + /// An index of the first element to remove. + /// A number of elements to remove. + public static SyntaxTriviaList RemoveRange( + this SyntaxTriviaList list, + int index, + int count) { - SyntaxTriviaList.Enumerator en = list.GetEnumerator(); + return ReplaceRange(list, index, count, Empty.ReadOnlyList()); + } - int i = 0; + /// + /// Creates a new list with the trivia in the specified range replaced with new trivia. + /// + /// + /// + /// + /// + public static SyntaxTriviaList ReplaceRange( + this SyntaxTriviaList list, + int index, + int count, + IEnumerable newTrivia) + { + if (index < 0) + throw new ArgumentOutOfRangeException(nameof(index), index, ""); - while (i < index - && en.MoveNext()) + if (count < 0 + || index + count > list.Count) { - yield return en.Current; - i++; + throw new ArgumentOutOfRangeException(nameof(count), count, ""); } - int endIndex = index + count; + if (newTrivia is null) + throw new ArgumentNullException(nameof(newTrivia)); - while (i < endIndex - && en.MoveNext()) - { - i++; - } + return TriviaList(ReplaceRange()); - if ((newTrivia as ICollection)?.Count != 0) + IEnumerable ReplaceRange() { - foreach (SyntaxTrivia trivia in newTrivia) - yield return trivia; - } + SyntaxTriviaList.Enumerator en = list.GetEnumerator(); - while (en.MoveNext()) - yield return en.Current; - } - } + int i = 0; - internal static SyntaxTriviaList TrimStart(this SyntaxTriviaList trivia) - { - SyntaxTriviaList.Enumerator en = trivia.GetEnumerator(); + while (i < index + && en.MoveNext()) + { + yield return en.Current; + i++; + } - if (en.MoveNext()) - { - if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) - return trivia; + int endIndex = index + count; - for (int count = 1; en.MoveNext(); count++) - { - if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) - return trivia.RemoveRange(0, count); - } - } + while (i < endIndex + && en.MoveNext()) + { + i++; + } - return SyntaxTriviaList.Empty; - } + if ((newTrivia as ICollection)?.Count != 0) + { + foreach (SyntaxTrivia trivia in newTrivia) + yield return trivia; + } - internal static SyntaxTriviaList TrimEnd(this SyntaxTriviaList trivia) - { - SyntaxTriviaList.Reversed.Enumerator en = trivia.Reverse().GetEnumerator(); + while (en.MoveNext()) + yield return en.Current; + } + } - if (en.MoveNext()) + internal static SyntaxTriviaList TrimStart(this SyntaxTriviaList trivia) { - if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) - return trivia; + SyntaxTriviaList.Enumerator en = trivia.GetEnumerator(); - for (int count = 1; en.MoveNext(); count++) + if (en.MoveNext()) { if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) - return trivia.RemoveRange(trivia.Count - count, count); + return trivia; + + for (int count = 1; en.MoveNext(); count++) + { + if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) + return trivia.RemoveRange(0, count); + } } + + return SyntaxTriviaList.Empty; } - return SyntaxTriviaList.Empty; - } - #endregion SyntaxTriviaList + internal static SyntaxTriviaList TrimEnd(this SyntaxTriviaList trivia) + { + SyntaxTriviaList.Reversed.Enumerator en = trivia.Reverse().GetEnumerator(); - #region TypeDeclarationSyntax - internal static TypeDeclarationSyntax WithMembers(this TypeDeclarationSyntax typeDeclaration, SyntaxList newMembers) - { - if (typeDeclaration == null) - throw new ArgumentNullException(nameof(typeDeclaration)); - - switch (typeDeclaration.Kind()) - { - case SyntaxKind.ClassDeclaration: - return ((ClassDeclarationSyntax)typeDeclaration).WithMembers(newMembers); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return ((RecordDeclarationSyntax)typeDeclaration).WithMembers(newMembers); - case SyntaxKind.StructDeclaration: - return ((StructDeclarationSyntax)typeDeclaration).WithMembers(newMembers); - case SyntaxKind.InterfaceDeclaration: - return ((InterfaceDeclarationSyntax)typeDeclaration).WithMembers(newMembers); - default: + if (en.MoveNext()) + { + if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) + return trivia; + + for (int count = 1; en.MoveNext(); count++) { - SyntaxDebug.Fail(typeDeclaration); - return typeDeclaration; + if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) + return trivia.RemoveRange(trivia.Count - count, count); } + } + + return SyntaxTriviaList.Empty; } - } - #endregion TypeDeclarationSyntax + #endregion SyntaxTriviaList - #region TypeSyntax - /// - /// Returns true if the type is . - /// - /// - public static bool IsVoid(this TypeSyntax type) - { - return type.IsKind(SyntaxKind.PredefinedType) - && ((PredefinedTypeSyntax)type).Keyword.IsKind(SyntaxKind.VoidKeyword); - } - #endregion TypeSyntax + #region TypeDeclarationSyntax + internal static TypeDeclarationSyntax WithMembers(this TypeDeclarationSyntax typeDeclaration, SyntaxList newMembers) + { + if (typeDeclaration is null) + throw new ArgumentNullException(nameof(typeDeclaration)); - #region UsingDirectiveSyntax - internal static IdentifierNameSyntax GetRootNamespace(this UsingDirectiveSyntax usingDirective) - { - if (usingDirective.Name is IdentifierNameSyntax identifierName) - return identifierName; + switch (typeDeclaration.Kind()) + { + case SyntaxKind.ClassDeclaration: + return ((ClassDeclarationSyntax)typeDeclaration).WithMembers(newMembers); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((RecordDeclarationSyntax)typeDeclaration).WithMembers(newMembers); + case SyntaxKind.StructDeclaration: + return ((StructDeclarationSyntax)typeDeclaration).WithMembers(newMembers); + case SyntaxKind.InterfaceDeclaration: + return ((InterfaceDeclarationSyntax)typeDeclaration).WithMembers(newMembers); + default: + { + SyntaxDebug.Fail(typeDeclaration); + return typeDeclaration; + } + } + } + #endregion TypeDeclarationSyntax + + #region TypeSyntax + /// + /// Returns true if the type is . + /// + /// + public static bool IsVoid(this TypeSyntax type) + { + return type.IsKind(SyntaxKind.PredefinedType) + && ((PredefinedTypeSyntax)type).Keyword.IsKind(SyntaxKind.VoidKeyword); + } + #endregion TypeSyntax - if (usingDirective.Name is QualifiedNameSyntax qualifiedName) + #region UsingDirectiveSyntax + internal static IdentifierNameSyntax GetRootNamespace(this UsingDirectiveSyntax usingDirective) { - NameSyntax left; + if (usingDirective.Name is IdentifierNameSyntax identifierName) + return identifierName; - do + if (usingDirective.Name is QualifiedNameSyntax qualifiedName) { - left = qualifiedName.Left; + NameSyntax left; + + do + { + left = qualifiedName.Left; - if (left is IdentifierNameSyntax identifierName2) - return identifierName2; + if (left is IdentifierNameSyntax identifierName2) + return identifierName2; - qualifiedName = left as QualifiedNameSyntax; + qualifiedName = left as QualifiedNameSyntax; + } + while (qualifiedName is not null); + + SyntaxDebug.Fail(left); + } + else + { + SyntaxDebug.Fail(usingDirective.Name); } - while (qualifiedName != null); - SyntaxDebug.Fail(left); + return null; } - else + #endregion UsingDirectiveSyntax + + #region UsingStatementSyntax + /// + /// Returns using statement's declaration or an expression if the declaration is null. + /// + /// + public static CSharpSyntaxNode DeclarationOrExpression(this UsingStatementSyntax usingStatement) { - SyntaxDebug.Fail(usingDirective.Name); + if (usingStatement is null) + throw new ArgumentNullException(nameof(usingStatement)); + + return usingStatement.Declaration ?? (CSharpSyntaxNode)usingStatement.Expression; } - return null; - } - #endregion UsingDirectiveSyntax + internal static StatementSyntax EmbeddedStatement(this UsingStatementSyntax usingStatement, bool allowUsingStatement = true) + { + StatementSyntax statement = usingStatement.Statement; - #region UsingStatementSyntax - /// - /// Returns using statement's declaration or an expression if the declaration is null. - /// - /// - public static CSharpSyntaxNode DeclarationOrExpression(this UsingStatementSyntax usingStatement) - { - if (usingStatement == null) - throw new ArgumentNullException(nameof(usingStatement)); + if (statement is null) + return null; - return usingStatement.Declaration ?? (CSharpSyntaxNode)usingStatement.Expression; - } + SyntaxKind kind = statement.Kind(); - internal static StatementSyntax EmbeddedStatement(this UsingStatementSyntax usingStatement, bool allowUsingStatement = true) - { - StatementSyntax statement = usingStatement.Statement; + if (kind == SyntaxKind.Block) + return null; - if (statement == null) - return null; + if (!allowUsingStatement + && kind == SyntaxKind.UsingStatement) + { + return null; + } - SyntaxKind kind = statement.Kind(); + return statement; + } + #endregion UsingStatementSyntax - if (kind == SyntaxKind.Block) - return null; + #region WhileStatementSyntax + internal static StatementSyntax EmbeddedStatement(this WhileStatementSyntax whileStatement) + { + StatementSyntax statement = whileStatement.Statement; - if (!allowUsingStatement - && kind == SyntaxKind.UsingStatement) + return (statement?.Kind() == SyntaxKind.Block) ? null : statement; + } + #endregion WhileStatementSyntax + + #region XmlElementSyntax + internal static bool HasTag(this XmlElementSyntax xmlElement, XmlTag tag) { - return null; + return GetTag(xmlElement) == tag; } - return statement; - } - #endregion UsingStatementSyntax + internal static XmlTag GetTag(this XmlElementSyntax xmlElement) + { + return XmlTagMapper.GetTagOrDefault(xmlElement.StartTag?.Name?.LocalName.ValueText); + } - #region WhileStatementSyntax - internal static StatementSyntax EmbeddedStatement(this WhileStatementSyntax whileStatement) - { - StatementSyntax statement = whileStatement.Statement; + internal static bool IsLocalName(this XmlElementSyntax xmlElement, string localName, StringComparison comparison = StringComparison.Ordinal) + { + return xmlElement.StartTag?.Name?.IsLocalName(localName, comparison) == true; + } - return (statement?.Kind() == SyntaxKind.Block) ? null : statement; - } - #endregion WhileStatementSyntax + internal static string GetAttributeValue(this XmlElementSyntax element, string attributeName) + { + XmlElementStartTagSyntax startTag = element.StartTag; - #region XmlElementSyntax - internal static bool HasTag(this XmlElementSyntax xmlElement, XmlTag tag) - { - return GetTag(xmlElement) == tag; - } + if (startTag is not null) + { + foreach (XmlAttributeSyntax attribute in startTag.Attributes) + { + if (attribute is XmlNameAttributeSyntax nameAttribute + && nameAttribute.Name?.LocalName.ValueText == attributeName) + { + IdentifierNameSyntax identifierName = nameAttribute.Identifier; - internal static XmlTag GetTag(this XmlElementSyntax xmlElement) - { - return XmlTagMapper.GetTagOrDefault(xmlElement.StartTag?.Name?.LocalName.ValueText); - } + if (identifierName is not null) + return identifierName.Identifier.ValueText; + } + } + } - internal static bool IsLocalName(this XmlElementSyntax xmlElement, string localName, StringComparison comparison = StringComparison.Ordinal) - { - return xmlElement.StartTag?.Name?.IsLocalName(localName, comparison) == true; - } + return null; + } - internal static string GetAttributeValue(this XmlElementSyntax element, string attributeName) - { - XmlElementStartTagSyntax startTag = element.StartTag; + internal static XmlElementSyntax UpdateName(this XmlElementSyntax element, string newName) + { + XmlElementStartTagSyntax startTag = element.StartTag; + XmlElementEndTagSyntax endTag = element.EndTag; + + SyntaxToken localName = Identifier(newName); - if (startTag != null) + return element + .WithStartTag(startTag.WithName(startTag.Name.WithLocalName(localName.WithTriviaFrom(startTag.Name)))) + .WithEndTag(endTag.WithName(endTag.Name.WithLocalName(localName.WithTriviaFrom(endTag.Name)))); + } + #endregion XmlElementSyntax + + #region XmlEmptyElementSyntax + internal static string GetAttributeValue(this XmlEmptyElementSyntax element, string attributeName) { - foreach (XmlAttributeSyntax attribute in startTag.Attributes) + foreach (XmlAttributeSyntax attribute in element.Attributes) { if (attribute is XmlNameAttributeSyntax nameAttribute && nameAttribute.Name?.LocalName.ValueText == attributeName) { IdentifierNameSyntax identifierName = nameAttribute.Identifier; - if (identifierName != null) + if (identifierName is not null) return identifierName.Identifier.ValueText; } } - } - - return null; - } - - internal static XmlElementSyntax UpdateName(this XmlElementSyntax element, string newName) - { - XmlElementStartTagSyntax startTag = element.StartTag; - XmlElementEndTagSyntax endTag = element.EndTag; - - SyntaxToken localName = Identifier(newName); - return element - .WithStartTag(startTag.WithName(startTag.Name.WithLocalName(localName.WithTriviaFrom(startTag.Name)))) - .WithEndTag(endTag.WithName(endTag.Name.WithLocalName(localName.WithTriviaFrom(endTag.Name)))); - } - #endregion XmlElementSyntax + return null; + } - #region XmlEmptyElementSyntax - internal static string GetAttributeValue(this XmlEmptyElementSyntax element, string attributeName) - { - foreach (XmlAttributeSyntax attribute in element.Attributes) + internal static bool HasTag(this XmlEmptyElementSyntax xmlElement, XmlTag tag) { - if (attribute is XmlNameAttributeSyntax nameAttribute - && nameAttribute.Name?.LocalName.ValueText == attributeName) - { - IdentifierNameSyntax identifierName = nameAttribute.Identifier; - - if (identifierName != null) - return identifierName.Identifier.ValueText; - } + return GetTag(xmlElement) == tag; } - return null; - } - - internal static bool HasTag(this XmlEmptyElementSyntax xmlElement, XmlTag tag) - { - return GetTag(xmlElement) == tag; - } - - internal static XmlTag GetTag(this XmlEmptyElementSyntax xmlElement) - { - return XmlTagMapper.GetTagOrDefault(xmlElement.Name?.LocalName.ValueText); - } - - internal static bool IsLocalName(this XmlEmptyElementSyntax xmlEmptyElement, string localName, StringComparison comparison = StringComparison.Ordinal) - { - return xmlEmptyElement.Name?.IsLocalName(localName, comparison) == true; - } - #endregion XmlEmptyElementSyntax + internal static XmlTag GetTag(this XmlEmptyElementSyntax xmlElement) + { + return XmlTagMapper.GetTagOrDefault(xmlElement.Name?.LocalName.ValueText); + } - #region XmlNameSyntax - internal static bool IsLocalName(this XmlNameSyntax xmlName, string localName, StringComparison comparison = StringComparison.Ordinal) - { - return string.Equals(xmlName.LocalName.ValueText, localName, comparison); - } - #endregion XmlNameSyntax + internal static bool IsLocalName(this XmlEmptyElementSyntax xmlEmptyElement, string localName, StringComparison comparison = StringComparison.Ordinal) + { + return xmlEmptyElement.Name?.IsLocalName(localName, comparison) == true; + } + #endregion XmlEmptyElementSyntax - #region YieldStatementSyntax - /// - /// Returns true if the specified statement is a yield break statement. - /// - /// - public static bool IsYieldBreak(this YieldStatementSyntax yieldStatement) - { - return yieldStatement.IsKind(SyntaxKind.YieldBreakStatement); - } + #region XmlNameSyntax + internal static bool IsLocalName(this XmlNameSyntax xmlName, string localName, StringComparison comparison = StringComparison.Ordinal) + { + return string.Equals(xmlName.LocalName.ValueText, localName, comparison); + } + #endregion XmlNameSyntax + + #region YieldStatementSyntax + /// + /// Returns true if the specified statement is a yield break statement. + /// + /// + public static bool IsYieldBreak(this YieldStatementSyntax yieldStatement) + { + return yieldStatement.IsKind(SyntaxKind.YieldBreakStatement); + } - /// - /// Returns true if the specified statement is a yield return statement. - /// - /// - public static bool IsYieldReturn(this YieldStatementSyntax yieldStatement) - { - return yieldStatement.IsKind(SyntaxKind.YieldReturnStatement); + /// + /// Returns true if the specified statement is a yield return statement. + /// + /// + public static bool IsYieldReturn(this YieldStatementSyntax yieldStatement) + { + return yieldStatement.IsKind(SyntaxKind.YieldReturnStatement); + } + #endregion YieldStatementSyntax } - #endregion YieldStatementSyntax } diff --git a/src/CSharp/CSharp/IfStatementCascade.cs b/src/CSharp/CSharp/IfStatementCascade.cs index 1d784e7851..ce0980efb4 100644 --- a/src/CSharp/CSharp/IfStatementCascade.cs +++ b/src/CSharp/CSharp/IfStatementCascade.cs @@ -7,223 +7,224 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -/// -/// Enables to enumerate if statement cascade. -/// -[DebuggerDisplay("{DebuggerDisplay,nq}")] -public readonly struct IfStatementCascade : IEquatable, IEnumerable +namespace Roslynator.CSharp { - internal IfStatementCascade(IfStatementSyntax ifStatement) - { - IfStatement = ifStatement; - } - /// - /// The if statement. + /// Enables to enumerate if statement cascade. /// - public IfStatementSyntax IfStatement { get; } - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay + [DebuggerDisplay("{DebuggerDisplay,nq}")] + public readonly struct IfStatementCascade : IEquatable, IEnumerable { - get { return IfStatement?.ToString() ?? "Uninitialized"; } - } + internal IfStatementCascade(IfStatementSyntax ifStatement) + { + IfStatement = ifStatement; + } - /// - /// Gets the enumerator for the if-else cascade. - /// - public Enumerator GetEnumerator() - { - return new Enumerator(IfStatement); - } + /// + /// The if statement. + /// + public IfStatementSyntax IfStatement { get; } - IEnumerator IEnumerable.GetEnumerator() - { - if (IfStatement != null) - return new EnumeratorImpl(IfStatement); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay + { + get { return IfStatement?.ToString() ?? "Uninitialized"; } + } - return Empty.Enumerator(); - } + /// + /// Gets the enumerator for the if-else cascade. + /// + public Enumerator GetEnumerator() + { + return new Enumerator(IfStatement); + } - IEnumerator IEnumerable.GetEnumerator() - { - if (IfStatement != null) - return new EnumeratorImpl(IfStatement); + IEnumerator IEnumerable.GetEnumerator() + { + if (IfStatement is not null) + return new EnumeratorImpl(IfStatement); - return Empty.Enumerator(); - } + return Empty.Enumerator(); + } - /// - /// Returns the string representation of the underlying syntax, not including its leading and trailing trivia. - /// - public override string ToString() - { - return IfStatement?.ToString() ?? ""; - } + IEnumerator IEnumerable.GetEnumerator() + { + if (IfStatement is not null) + return new EnumeratorImpl(IfStatement); - /// - /// Determines whether this instance and a specified object are equal. - /// - /// The object to compare with the current instance. - /// true if and this instance are the same type and represent the same value; otherwise, false. - public override bool Equals(object obj) - { - return obj is IfStatementCascade other && Equals(other); - } + return Empty.Enumerator(); + } - /// - /// Determines whether this instance is equal to another object of the same type. - /// - /// An object to compare with this object. - /// true if the current object is equal to the parameter; otherwise, false. - public bool Equals(IfStatementCascade other) - { - return EqualityComparer.Default.Equals(IfStatement, other.IfStatement); - } + /// + /// Returns the string representation of the underlying syntax, not including its leading and trailing trivia. + /// + public override string ToString() + { + return IfStatement?.ToString() ?? ""; + } - /// - /// Returns the hash code for this instance. - /// - /// A 32-bit signed integer that is the hash code for this instance. - public override int GetHashCode() - { - return EqualityComparer.Default.GetHashCode(IfStatement); - } + /// + /// Determines whether this instance and a specified object are equal. + /// + /// The object to compare with the current instance. + /// true if and this instance are the same type and represent the same value; otherwise, false. + public override bool Equals(object obj) + { + return obj is IfStatementCascade other && Equals(other); + } -#pragma warning disable CS1591 + /// + /// Determines whether this instance is equal to another object of the same type. + /// + /// An object to compare with this object. + /// true if the current object is equal to the parameter; otherwise, false. + public bool Equals(IfStatementCascade other) + { + return EqualityComparer.Default.Equals(IfStatement, other.IfStatement); + } - public static bool operator ==(in IfStatementCascade cascade1, in IfStatementCascade cascade2) - { - return cascade1.Equals(cascade2); - } + /// + /// Returns the hash code for this instance. + /// + /// A 32-bit signed integer that is the hash code for this instance. + public override int GetHashCode() + { + return EqualityComparer.Default.GetHashCode(IfStatement); + } - public static bool operator !=(in IfStatementCascade cascade1, in IfStatementCascade cascade2) - { - return !(cascade1 == cascade2); - } +#pragma warning disable CS1591 - [SuppressMessage("Usage", "RCS1223:Use DebuggerDisplay attribute for publicly visible type.")] - public struct Enumerator - { - private IfStatementOrElseClause _ifOrElse; - private int _count; + public static bool operator ==(in IfStatementCascade cascade1, in IfStatementCascade cascade2) + { + return cascade1.Equals(cascade2); + } - internal Enumerator(IfStatementSyntax ifStatement) + public static bool operator !=(in IfStatementCascade cascade1, in IfStatementCascade cascade2) { - _ifOrElse = ifStatement; - _count = -1; + return !(cascade1 == cascade2); } - public bool MoveNext() + [SuppressMessage("Usage", "RCS1223:Use DebuggerDisplay attribute for publicly visible type.")] + public struct Enumerator { - if (_count == -1) + private IfStatementOrElseClause _ifOrElse; + private int _count; + + internal Enumerator(IfStatementSyntax ifStatement) { - if (_ifOrElse != default) - { - _count++; - return true; - } + _ifOrElse = ifStatement; + _count = -1; } - else if (_ifOrElse.IsIf) - { - ElseClauseSyntax elseClause = _ifOrElse.AsIf().Else; - if (elseClause != null) + public bool MoveNext() + { + if (_count == -1) { - if (elseClause.Statement is IfStatementSyntax nextIf) + if (_ifOrElse != default) { - _ifOrElse = nextIf; + _count++; + return true; } - else + } + else if (_ifOrElse.IsIf) + { + ElseClauseSyntax elseClause = _ifOrElse.AsIf().Else; + + if (elseClause is not null) { - _ifOrElse = elseClause; + if (elseClause.Statement is IfStatementSyntax nextIf) + { + _ifOrElse = nextIf; + } + else + { + _ifOrElse = elseClause; + } + + _count++; + return true; } - - _count++; - return true; } - } - - return false; - } - public IfStatementOrElseClause Current - { - get { return (_count >= 0) ? _ifOrElse : throw new InvalidOperationException(); } - } - - public void Reset() - { - int count = _count; + return false; + } - if (count >= 0) + public IfStatementOrElseClause Current { - IfStatementSyntax ifStatement; - if (_ifOrElse.IsElse) - { - ifStatement = (IfStatementSyntax)_ifOrElse.Parent; - } - else - { - ifStatement = _ifOrElse.AsIf(); - } + get { return (_count >= 0) ? _ifOrElse : throw new InvalidOperationException(); } + } - count--; + public void Reset() + { + int count = _count; - while (count >= 0) + if (count >= 0) { - ifStatement = (IfStatementSyntax)ifStatement.Parent.Parent; + IfStatementSyntax ifStatement; + if (_ifOrElse.IsElse) + { + ifStatement = (IfStatementSyntax)_ifOrElse.Parent; + } + else + { + ifStatement = _ifOrElse.AsIf(); + } + count--; + + while (count >= 0) + { + ifStatement = (IfStatementSyntax)ifStatement.Parent.Parent; + count--; + } + + _ifOrElse = ifStatement; } + } - _ifOrElse = ifStatement; + public override bool Equals(object obj) + { + throw new NotSupportedException(); } - } - public override bool Equals(object obj) - { - throw new NotSupportedException(); + public override int GetHashCode() + { + throw new NotSupportedException(); + } } - public override int GetHashCode() + private class EnumeratorImpl : IEnumerator { - throw new NotSupportedException(); - } - } - - private class EnumeratorImpl : IEnumerator - { - private Enumerator _en; + private Enumerator _en; - internal EnumeratorImpl(IfStatementSyntax ifStatement) - { - _en = new Enumerator(ifStatement); - } + internal EnumeratorImpl(IfStatementSyntax ifStatement) + { + _en = new Enumerator(ifStatement); + } - public IfStatementOrElseClause Current - { - get { return _en.Current; } - } + public IfStatementOrElseClause Current + { + get { return _en.Current; } + } - object IEnumerator.Current - { - get { return _en.Current; } - } + object IEnumerator.Current + { + get { return _en.Current; } + } - public bool MoveNext() - { - return _en.MoveNext(); - } + public bool MoveNext() + { + return _en.MoveNext(); + } - public void Reset() - { - _en.Reset(); - } + public void Reset() + { + _en.Reset(); + } - public void Dispose() - { + public void Dispose() + { + } } } } diff --git a/src/CSharp/CSharp/IfStatementCascadeInfo.cs b/src/CSharp/CSharp/IfStatementCascadeInfo.cs index d765a8b30d..5fb77bb129 100644 --- a/src/CSharp/CSharp/IfStatementCascadeInfo.cs +++ b/src/CSharp/CSharp/IfStatementCascadeInfo.cs @@ -5,119 +5,120 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Diagnostics; -namespace Roslynator.CSharp; - -/// -/// Summarizes information about . -/// -[DebuggerDisplay("{DebuggerDisplay,nq}")] -public readonly struct IfStatementCascadeInfo : IEquatable +namespace Roslynator.CSharp { /// - /// Initializes a new instance of . + /// Summarizes information about . /// - /// - public IfStatementCascadeInfo(IfStatementSyntax ifStatement) + [DebuggerDisplay("{DebuggerDisplay,nq}")] + public readonly struct IfStatementCascadeInfo : IEquatable { - int count = 0; - IfStatementOrElseClause last = default; - - foreach (IfStatementOrElseClause ifOrElse in ifStatement.AsCascade()) + /// + /// Initializes a new instance of . + /// + /// + public IfStatementCascadeInfo(IfStatementSyntax ifStatement) { - count++; - last = ifOrElse; + int count = 0; + IfStatementOrElseClause last = default; + + foreach (IfStatementOrElseClause ifOrElse in ifStatement.AsCascade()) + { + count++; + last = ifOrElse; + } + + IfStatement = ifStatement; + Count = count; + Last = last; } - IfStatement = ifStatement; - Count = count; - Last = last; - } - - /// - /// Gets the topmost 'if' statement. - /// - public IfStatementSyntax IfStatement { get; } - - /// - /// Gets a number of 'if' statements plus optional 'else' clause at the end of a cascade. - /// - public int Count { get; } - - /// - /// Gets a last 'if' or 'else' in a cascade. - /// - public IfStatementOrElseClause Last { get; } - - /// - /// Determines whether the cascade ends with 'if' statement. - /// - public bool EndsWithIf => Last.IsIf; - - /// - /// Determines whether the cascade ends with 'else' clause. - /// - public bool EndsWithElse => Last.IsElse; - - /// - /// Determines whether the cascade consists of single 'if' statement. - /// - public bool IsSimpleIf => Count == 1; - - /// - /// Determines whether the cascade consists of single if-else. - /// - public bool IsSimpleIfElse => Count == 2; - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay - { - get { return (IfStatement != null) ? $"Count = {Count} {((EndsWithIf) ? $"EndsWithIf = {EndsWithIf}" : $"EndsWithElse = {EndsWithElse}")}" : "Uninitialized"; } - } + /// + /// Gets the topmost 'if' statement. + /// + public IfStatementSyntax IfStatement { get; } + + /// + /// Gets a number of 'if' statements plus optional 'else' clause at the end of a cascade. + /// + public int Count { get; } + + /// + /// Gets a last 'if' or 'else' in a cascade. + /// + public IfStatementOrElseClause Last { get; } + + /// + /// Determines whether the cascade ends with 'if' statement. + /// + public bool EndsWithIf => Last.IsIf; + + /// + /// Determines whether the cascade ends with 'else' clause. + /// + public bool EndsWithElse => Last.IsElse; + + /// + /// Determines whether the cascade consists of single 'if' statement. + /// + public bool IsSimpleIf => Count == 1; + + /// + /// Determines whether the cascade consists of single if-else. + /// + public bool IsSimpleIfElse => Count == 2; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay + { + get { return (IfStatement is not null) ? $"Count = {Count} {((EndsWithIf) ? $"EndsWithIf = {EndsWithIf}" : $"EndsWithElse = {EndsWithElse}")}" : "Uninitialized"; } + } - /// - /// Returns the string representation of the underlying syntax, not including its leading and trailing trivia. - /// - public override string ToString() - { - return IfStatement?.ToString() ?? ""; - } + /// + /// Returns the string representation of the underlying syntax, not including its leading and trailing trivia. + /// + public override string ToString() + { + return IfStatement?.ToString() ?? ""; + } - /// - /// Determines whether this instance and a specified object are equal. - /// - /// The object to compare with the current instance. - /// true if and this instance are the same type and represent the same value; otherwise, false. - public override bool Equals(object obj) - { - return obj is IfStatementCascadeInfo other && Equals(other); - } + /// + /// Determines whether this instance and a specified object are equal. + /// + /// The object to compare with the current instance. + /// true if and this instance are the same type and represent the same value; otherwise, false. + public override bool Equals(object obj) + { + return obj is IfStatementCascadeInfo other && Equals(other); + } - /// - /// Determines whether this instance is equal to another object of the same type. - /// - /// An object to compare with this object. - /// true if the current object is equal to the parameter; otherwise, false. - public bool Equals(IfStatementCascadeInfo other) - { - return EqualityComparer.Default.Equals(IfStatement, other.IfStatement); - } + /// + /// Determines whether this instance is equal to another object of the same type. + /// + /// An object to compare with this object. + /// true if the current object is equal to the parameter; otherwise, false. + public bool Equals(IfStatementCascadeInfo other) + { + return EqualityComparer.Default.Equals(IfStatement, other.IfStatement); + } - /// - /// Returns the hash code for this instance. - /// - /// A 32-bit signed integer that is the hash code for this instance. - public override int GetHashCode() - { - return EqualityComparer.Default.GetHashCode(IfStatement); - } + /// + /// Returns the hash code for this instance. + /// + /// A 32-bit signed integer that is the hash code for this instance. + public override int GetHashCode() + { + return EqualityComparer.Default.GetHashCode(IfStatement); + } - public static bool operator ==(in IfStatementCascadeInfo info1, in IfStatementCascadeInfo info2) - { - return info1.Equals(info2); - } + public static bool operator ==(in IfStatementCascadeInfo info1, in IfStatementCascadeInfo info2) + { + return info1.Equals(info2); + } - public static bool operator !=(in IfStatementCascadeInfo info1, in IfStatementCascadeInfo info2) - { - return !(info1 == info2); + public static bool operator !=(in IfStatementCascadeInfo info1, in IfStatementCascadeInfo info2) + { + return !(info1 == info2); + } } } diff --git a/src/CSharp/CSharp/IfStatementOrElseClause.cs b/src/CSharp/CSharp/IfStatementOrElseClause.cs index 4295638e64..e7bc03ec00 100644 --- a/src/CSharp/CSharp/IfStatementOrElseClause.cs +++ b/src/CSharp/CSharp/IfStatementOrElseClause.cs @@ -7,238 +7,239 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -namespace Roslynator.CSharp; - -/// -/// A wrapper for either an or an . -/// -[DebuggerDisplay("{DebuggerDisplay,nq}")] -public readonly struct IfStatementOrElseClause : IEquatable +namespace Roslynator.CSharp { - private readonly IfStatementSyntax _ifStatement; - private readonly ElseClauseSyntax _elseClause; - - internal IfStatementOrElseClause(SyntaxNode node) + /// + /// A wrapper for either an or an . + /// + [DebuggerDisplay("{DebuggerDisplay,nq}")] + public readonly struct IfStatementOrElseClause : IEquatable { - if (node == null) - throw new ArgumentNullException(nameof(node)); + private readonly IfStatementSyntax _ifStatement; + private readonly ElseClauseSyntax _elseClause; - SyntaxKind kind = node.Kind(); + internal IfStatementOrElseClause(SyntaxNode node) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); + + SyntaxKind kind = node.Kind(); + + if (kind == SyntaxKind.IfStatement) + { + _ifStatement = (IfStatementSyntax)node; + _elseClause = null; + } + else if (kind == SyntaxKind.ElseClause) + { + _elseClause = (ElseClauseSyntax)node; + _ifStatement = null; + } + else + { + throw new ArgumentException("Node must be either an if statement or an else clause.", nameof(node)); + } + } - if (kind == SyntaxKind.IfStatement) + public IfStatementOrElseClause(IfStatementSyntax ifStatement) { - _ifStatement = (IfStatementSyntax)node; + _ifStatement = ifStatement ?? throw new ArgumentNullException(nameof(ifStatement)); _elseClause = null; } - else if (kind == SyntaxKind.ElseClause) + + public IfStatementOrElseClause(ElseClauseSyntax elseClause) { - _elseClause = (ElseClauseSyntax)node; + _elseClause = elseClause ?? throw new ArgumentNullException(nameof(elseClause)); _ifStatement = null; } - else + + internal SyntaxNode Node { - throw new ArgumentException("Node must be either an if statement or an else clause.", nameof(node)); + get { return _ifStatement ?? (SyntaxNode)_elseClause; } } - } - - public IfStatementOrElseClause(IfStatementSyntax ifStatement) - { - _ifStatement = ifStatement ?? throw new ArgumentNullException(nameof(ifStatement)); - _elseClause = null; - } - - public IfStatementOrElseClause(ElseClauseSyntax elseClause) - { - _elseClause = elseClause ?? throw new ArgumentNullException(nameof(elseClause)); - _ifStatement = null; - } - internal SyntaxNode Node - { - get { return _ifStatement ?? (SyntaxNode)_elseClause; } - } - - /// - /// Gets an underlying node kind. - /// - public SyntaxKind Kind - { - get + /// + /// Gets an underlying node kind. + /// + public SyntaxKind Kind { - if (_ifStatement != null) - return SyntaxKind.IfStatement; + get + { + if (_ifStatement is not null) + return SyntaxKind.IfStatement; - if (_elseClause != null) - return SyntaxKind.ElseClause; + if (_elseClause is not null) + return SyntaxKind.ElseClause; - return SyntaxKind.None; + return SyntaxKind.None; + } } - } - /// - /// Determines whether this is wrapping an if statement. - /// - public bool IsIf - { - get { return Kind == SyntaxKind.IfStatement; } - } + /// + /// Determines whether this is wrapping an if statement. + /// + public bool IsIf + { + get { return Kind == SyntaxKind.IfStatement; } + } - /// - /// Determines whether this is wrapping an else clause. - /// - public bool IsElse - { - get { return Kind == SyntaxKind.ElseClause; } - } + /// + /// Determines whether this is wrapping an else clause. + /// + public bool IsElse + { + get { return Kind == SyntaxKind.ElseClause; } + } - /// - /// Gets or . - /// - public StatementSyntax Statement - { - get + /// + /// Gets or . + /// + public StatementSyntax Statement { - if (_ifStatement != null) - return _ifStatement.Statement; + get + { + if (_ifStatement is not null) + return _ifStatement.Statement; - if (_elseClause != null) - return _elseClause.Statement; + if (_elseClause is not null) + return _elseClause.Statement; - return null; + return null; + } } - } - /// - /// The node that contains the underlying node in its collection. - /// - public SyntaxNode Parent - { - get { return _ifStatement?.Parent ?? _elseClause?.Parent; } - } + /// + /// The node that contains the underlying node in its collection. + /// + public SyntaxNode Parent + { + get { return _ifStatement?.Parent ?? _elseClause?.Parent; } + } - /// - /// The absolute span of this node in characters, not including its leading and trailing trivia. - /// - public TextSpan Span - { - get + /// + /// The absolute span of this node in characters, not including its leading and trailing trivia. + /// + public TextSpan Span { - if (_ifStatement != null) - return _ifStatement.Span; + get + { + if (_ifStatement is not null) + return _ifStatement.Span; - if (_elseClause != null) - return _elseClause.Span; + if (_elseClause is not null) + return _elseClause.Span; - return default; + return default; + } } - } - /// - /// The absolute span of this node in characters, including its leading and trailing trivia. - /// - public TextSpan FullSpan - { - get + /// + /// The absolute span of this node in characters, including its leading and trailing trivia. + /// + public TextSpan FullSpan { - if (_ifStatement != null) - return _ifStatement.FullSpan; + get + { + if (_ifStatement is not null) + return _ifStatement.FullSpan; - if (_elseClause != null) - return _elseClause.FullSpan; + if (_elseClause is not null) + return _elseClause.FullSpan; - return default; + return default; + } } - } - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay - { - get { return $"{GetType().Name} {Kind} {ToString()}"; } - } + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay + { + get { return $"{GetType().Name} {Kind} {ToString()}"; } + } - /// - /// Returns the underlying if statement if this is wrapping if statement. - /// - public IfStatementSyntax AsIf() - { - return _ifStatement; - } + /// + /// Returns the underlying if statement if this is wrapping if statement. + /// + public IfStatementSyntax AsIf() + { + return _ifStatement; + } - /// - /// Returns the underlying else clause if this is wrapping else clause. - /// - public ElseClauseSyntax AsElse() - { - return _elseClause; - } + /// + /// Returns the underlying else clause if this is wrapping else clause. + /// + public ElseClauseSyntax AsElse() + { + return _elseClause; + } - /// - /// Returns the string representation of the underlying node, not including its leading and trailing trivia. - /// - public override string ToString() - { - return Node?.ToString() ?? ""; - } + /// + /// Returns the string representation of the underlying node, not including its leading and trailing trivia. + /// + public override string ToString() + { + return Node?.ToString() ?? ""; + } - /// - /// Determines whether this instance and a specified object are equal. - /// - /// The object to compare with the current instance. - /// true if and this instance are the same type and represent the same value; otherwise, false. - public override bool Equals(object obj) - { - return obj is IfStatementOrElseClause other - && Equals(other); - } + /// + /// Determines whether this instance and a specified object are equal. + /// + /// The object to compare with the current instance. + /// true if and this instance are the same type and represent the same value; otherwise, false. + public override bool Equals(object obj) + { + return obj is IfStatementOrElseClause other + && Equals(other); + } - /// - /// Determines whether this instance is equal to another object of the same type. - /// - /// An object to compare with this object. - /// true if the current object is equal to the parameter; otherwise, false. - public bool Equals(IfStatementOrElseClause other) - { - return Node == other.Node; - } + /// + /// Determines whether this instance is equal to another object of the same type. + /// + /// An object to compare with this object. + /// true if the current object is equal to the parameter; otherwise, false. + public bool Equals(IfStatementOrElseClause other) + { + return Node == other.Node; + } - /// - /// Returns the hash code for this instance. - /// - /// A 32-bit signed integer that is the hash code for this instance. - public override int GetHashCode() - { - return Node?.GetHashCode() ?? 0; - } + /// + /// Returns the hash code for this instance. + /// + /// A 32-bit signed integer that is the hash code for this instance. + public override int GetHashCode() + { + return Node?.GetHashCode() ?? 0; + } #pragma warning disable CS1591 - public static bool operator ==(in IfStatementOrElseClause left, in IfStatementOrElseClause right) - { - return left.Equals(right); - } + public static bool operator ==(in IfStatementOrElseClause left, in IfStatementOrElseClause right) + { + return left.Equals(right); + } - public static bool operator !=(in IfStatementOrElseClause left, in IfStatementOrElseClause right) - { - return !left.Equals(right); - } + public static bool operator !=(in IfStatementOrElseClause left, in IfStatementOrElseClause right) + { + return !left.Equals(right); + } - public static implicit operator IfStatementOrElseClause(IfStatementSyntax ifStatement) - { - return new IfStatementOrElseClause(ifStatement); - } + public static implicit operator IfStatementOrElseClause(IfStatementSyntax ifStatement) + { + return new IfStatementOrElseClause(ifStatement); + } - public static implicit operator IfStatementSyntax(in IfStatementOrElseClause ifOrElse) - { - return ifOrElse.AsIf(); - } + public static implicit operator IfStatementSyntax(in IfStatementOrElseClause ifOrElse) + { + return ifOrElse.AsIf(); + } - public static implicit operator IfStatementOrElseClause(ElseClauseSyntax elseClause) - { - return new IfStatementOrElseClause(elseClause); - } + public static implicit operator IfStatementOrElseClause(ElseClauseSyntax elseClause) + { + return new IfStatementOrElseClause(elseClause); + } - public static implicit operator ElseClauseSyntax(in IfStatementOrElseClause ifOrElse) - { - return ifOrElse.AsElse(); - } + public static implicit operator ElseClauseSyntax(in IfStatementOrElseClause ifOrElse) + { + return ifOrElse.AsElse(); + } #pragma warning restore CS1591 + } } diff --git a/src/CSharp/CSharp/IndentationAnalysis.cs b/src/CSharp/CSharp/IndentationAnalysis.cs index c7fb3abae5..c46e1e7b8e 100644 --- a/src/CSharp/CSharp/IndentationAnalysis.cs +++ b/src/CSharp/CSharp/IndentationAnalysis.cs @@ -6,347 +6,348 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -[DebuggerDisplay("{DebuggerDisplay,nq}")] -internal readonly struct IndentationAnalysis +namespace Roslynator.CSharp { - private readonly int? _indentSize; - private readonly SyntaxTrivia? _singleIndentation; - - private IndentationAnalysis(SyntaxTrivia indentation, int? indentSize, SyntaxTrivia? singleIndentation) + [DebuggerDisplay("{DebuggerDisplay,nq}")] + internal readonly struct IndentationAnalysis { - Indentation = indentation; - _indentSize = indentSize; - _singleIndentation = singleIndentation; - } + private readonly int? _indentSize; + private readonly SyntaxTrivia? _singleIndentation; - public SyntaxTrivia Indentation { get; } + private IndentationAnalysis(SyntaxTrivia indentation, int? indentSize, SyntaxTrivia? singleIndentation) + { + Indentation = indentation; + _indentSize = indentSize; + _singleIndentation = singleIndentation; + } - public int IndentSize => _indentSize ?? _singleIndentation?.Span.Length ?? 0; + public SyntaxTrivia Indentation { get; } - public int IndentationLength => Indentation.Span.Length; + public int IndentSize => _indentSize ?? _singleIndentation?.Span.Length ?? 0; - public int IncreasedIndentationLength => (IndentSize > 0) ? Indentation.Span.Length + IndentSize : 0; + public int IndentationLength => Indentation.Span.Length; - public bool IsDefault - { - get + public int IncreasedIndentationLength => (IndentSize > 0) ? Indentation.Span.Length + IndentSize : 0; + + public bool IsDefault { - return Indentation.IsKind(SyntaxKind.None) - && _indentSize is null - && _singleIndentation is null; + get + { + return Indentation.IsKind(SyntaxKind.None) + && _indentSize is null + && _singleIndentation is null; + } } - } - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay => $"Length = {Indentation.Span.Length} {nameof(IndentSize)} = {IndentSize}"; + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => $"Length = {Indentation.Span.Length} {nameof(IndentSize)} = {IndentSize}"; - public static IndentationAnalysis Create(SyntaxNode node, CancellationToken cancellationToken = default) - { - SyntaxTrivia indentation = SyntaxTriviaAnalysis.DetermineIndentation(node, cancellationToken); + public static IndentationAnalysis Create(SyntaxNode node, CancellationToken cancellationToken = default) + { + SyntaxTrivia indentation = SyntaxTriviaAnalysis.DetermineIndentation(node, cancellationToken); - (SyntaxTrivia trivia1, SyntaxTrivia trivia2, bool isFromCompilationUnit) = DetermineSingleIndentation(node, cancellationToken); + (SyntaxTrivia trivia1, SyntaxTrivia trivia2, bool isFromCompilationUnit) = DetermineSingleIndentation(node, cancellationToken); - if (isFromCompilationUnit) - { - return new IndentationAnalysis(indentation, trivia1.Span.Length - trivia2.Span.Length, null); + if (isFromCompilationUnit) + { + return new IndentationAnalysis(indentation, trivia1.Span.Length - trivia2.Span.Length, null); + } + else if (indentation.Span.Length > 0) + { + return (trivia1.Span.Length > 0) + ? new IndentationAnalysis(indentation, null, trivia1) + : new IndentationAnalysis(indentation, null, null); + } + else if (trivia1.Span.Length > 0) + { + return new IndentationAnalysis(indentation, null, trivia1); + } + else + { + return default; + } } - else if (indentation.Span.Length > 0) + + public string GetIncreasedIndentation() { - return (trivia1.Span.Length > 0) - ? new IndentationAnalysis(indentation, null, trivia1) - : new IndentationAnalysis(indentation, null, null); + string singleIndentation = GetSingleIndentation(); + + return Indentation.ToString() + singleIndentation; } - else if (trivia1.Span.Length > 0) + + public SyntaxTrivia GetIncreasedIndentationTrivia() { - return new IndentationAnalysis(indentation, null, trivia1); + return SyntaxFactory.Whitespace(GetIncreasedIndentation()); } - else + + public SyntaxTriviaList GetIncreasedIndentationTriviaList() { - return default; + return SyntaxFactory.TriviaList(GetIncreasedIndentationTrivia()); } - } - - public string GetIncreasedIndentation() - { - string singleIndentation = GetSingleIndentation(); - - return Indentation.ToString() + singleIndentation; - } - - public SyntaxTrivia GetIncreasedIndentationTrivia() - { - return SyntaxFactory.Whitespace(GetIncreasedIndentation()); - } - - public SyntaxTriviaList GetIncreasedIndentationTriviaList() - { - return SyntaxFactory.TriviaList(GetIncreasedIndentationTrivia()); - } - public string GetSingleIndentation() - { - if (_singleIndentation is not null) - return _singleIndentation.ToString(); + public string GetSingleIndentation() + { + if (_singleIndentation is not null) + return _singleIndentation.ToString(); - if (_indentSize == -1) - return Indentation.ToString(); + if (_indentSize == -1) + return Indentation.ToString(); - if (Indentation.Span.Length == 0) - return ""; + if (Indentation.Span.Length == 0) + return ""; - string indentation = Indentation.ToString(); + string indentation = Indentation.ToString(); - if (indentation[indentation.Length - 1] == '\t') - return "\t"; + if (indentation[indentation.Length - 1] == '\t') + return "\t"; - return new string(indentation[0], IndentSize); - } + return new string(indentation[0], IndentSize); + } - private static (SyntaxTrivia, SyntaxTrivia, bool isFromCompilationUnit) DetermineSingleIndentation(SyntaxNode node, CancellationToken cancellationToken = default) - { - do + private static (SyntaxTrivia, SyntaxTrivia, bool isFromCompilationUnit) DetermineSingleIndentation(SyntaxNode node, CancellationToken cancellationToken = default) { - switch (node) + do { - case MemberDeclarationSyntax member: - { - switch (node.Parent) + switch (node) + { + case MemberDeclarationSyntax member: { - 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; - } + switch (node.Parent) + { + 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; + } + } + + break; } - - break; - } - case AccessorDeclarationSyntax accessor: - { - switch (node.Parent) + case AccessorDeclarationSyntax accessor: { - case AccessorListSyntax accessorList: - { - (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(accessor, accessorList.CloseBraceToken); - - if (trivia1.Span.Length > 0) - return (trivia1, trivia2, true); - - break; - } - default: - { - return default; - } + switch (node.Parent) + { + case AccessorListSyntax accessorList: + { + (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(accessor, accessorList.CloseBraceToken); + + if (trivia1.Span.Length > 0) + return (trivia1, trivia2, true); + + break; + } + default: + { + return default; + } + } + + break; } - - break; - } - case BlockSyntax _: - { - break; - } - case StatementSyntax statement: - { - switch (node.Parent) + case BlockSyntax _: + { + break; + } + case StatementSyntax statement: { - 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; - } + switch (node.Parent) + { + 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; + } + } + + break; } + case CompilationUnitSyntax compilationUnit: + { + SyntaxTrivia trivia = DetermineIndentationSize(compilationUnit); + return (trivia, default, false); + } + } - break; - } - case CompilationUnitSyntax compilationUnit: - { - SyntaxTrivia trivia = DetermineIndentationSize(compilationUnit); - return (trivia, default, false); - } + node = node.Parent; } + while (node is not null); - node = node.Parent; - } - while (node != null); - - return default; + return default; - SyntaxTrivia DetermineIndentationSize(CompilationUnitSyntax compilationUnit) - { - foreach (MemberDeclarationSyntax member in compilationUnit.Members) + SyntaxTrivia DetermineIndentationSize(CompilationUnitSyntax compilationUnit) { - if (member is NamespaceDeclarationSyntax namespaceDeclaration) - { - MemberDeclarationSyntax member2 = namespaceDeclaration.Members.FirstOrDefault(); - - if (member2 != null) - return SyntaxTriviaAnalysis.DetermineIndentation(member2, cancellationToken); - } - else if (member is TypeDeclarationSyntax typeDeclaration) - { - MemberDeclarationSyntax member2 = typeDeclaration.Members.FirstOrDefault(); - - if (member2 != null) - return SyntaxTriviaAnalysis.DetermineIndentation(member2, cancellationToken); - } - else if (member is GlobalStatementSyntax globalStatement) + foreach (MemberDeclarationSyntax member in compilationUnit.Members) { - StatementSyntax statement2 = globalStatement.Statement; - - if (statement2 is SwitchStatementSyntax switchStatement) + if (member is NamespaceDeclarationSyntax namespaceDeclaration) { - SwitchSectionSyntax switchSection = switchStatement.Sections.FirstOrDefault(); + MemberDeclarationSyntax member2 = namespaceDeclaration.Members.FirstOrDefault(); - if (switchSection is not null) - return SyntaxTriviaAnalysis.DetermineIndentation(switchSection, cancellationToken); + if (member2 is not null) + return SyntaxTriviaAnalysis.DetermineIndentation(member2, cancellationToken); + } + else if (member is TypeDeclarationSyntax typeDeclaration) + { + MemberDeclarationSyntax member2 = typeDeclaration.Members.FirstOrDefault(); - break; + if (member2 is not null) + return SyntaxTriviaAnalysis.DetermineIndentation(member2, cancellationToken); } - else + else if (member is GlobalStatementSyntax globalStatement) { - StatementSyntax statement3 = GetContainedStatement(statement2); + StatementSyntax statement2 = globalStatement.Statement; + + if (statement2 is SwitchStatementSyntax switchStatement) + { + SwitchSectionSyntax switchSection = switchStatement.Sections.FirstOrDefault(); - if (statement3 is not null) + if (switchSection is not null) + return SyntaxTriviaAnalysis.DetermineIndentation(switchSection, cancellationToken); + + break; + } + else { - if (statement3 is BlockSyntax block) - statement3 = block.Statements.FirstOrDefault(); + StatementSyntax statement3 = GetContainedStatement(statement2); if (statement3 is not null) - return SyntaxTriviaAnalysis.DetermineIndentation(statement3, cancellationToken); + { + if (statement3 is BlockSyntax block) + statement3 = block.Statements.FirstOrDefault(); + + if (statement3 is not null) + return SyntaxTriviaAnalysis.DetermineIndentation(statement3, cancellationToken); + } } } } - } - - return default; - } - - (SyntaxTrivia, SyntaxTrivia) GetIndentationSize(SyntaxNodeOrToken nodeOrToken1, SyntaxNodeOrToken nodeOrToken2) - { - SyntaxTrivia indentation1 = SyntaxTriviaAnalysis.DetermineIndentation(nodeOrToken1, cancellationToken); - int length1 = indentation1.Span.Length; + return default; + } - if (length1 > 0) + (SyntaxTrivia, SyntaxTrivia) GetIndentationSize(SyntaxNodeOrToken nodeOrToken1, SyntaxNodeOrToken nodeOrToken2) { - SyntaxTrivia indentation2 = SyntaxTriviaAnalysis.DetermineIndentation(nodeOrToken2, cancellationToken); + SyntaxTrivia indentation1 = SyntaxTriviaAnalysis.DetermineIndentation(nodeOrToken1, cancellationToken); - int length2 = indentation2.Span.Length; + int length1 = indentation1.Span.Length; - if (length1 > length2) + if (length1 > 0) { - return (indentation1, indentation2); + SyntaxTrivia indentation2 = SyntaxTriviaAnalysis.DetermineIndentation(nodeOrToken2, cancellationToken); + + int length2 = indentation2.Span.Length; + + if (length1 > length2) + { + return (indentation1, indentation2); + } } - } - return default; - } + return default; + } - StatementSyntax GetContainedStatement(StatementSyntax statement) - { - switch (statement.Kind()) + StatementSyntax GetContainedStatement(StatementSyntax statement) { - case SyntaxKind.WhileStatement: - return ((WhileStatementSyntax)statement).Statement; + switch (statement.Kind()) + { + case SyntaxKind.WhileStatement: + return ((WhileStatementSyntax)statement).Statement; - case SyntaxKind.DoStatement: - return ((DoStatementSyntax)statement).Statement; + case SyntaxKind.DoStatement: + return ((DoStatementSyntax)statement).Statement; - case SyntaxKind.ForStatement: - return ((ForStatementSyntax)statement).Statement; + case SyntaxKind.ForStatement: + return ((ForStatementSyntax)statement).Statement; - case SyntaxKind.ForEachStatement: - case SyntaxKind.ForEachVariableStatement: - return ((CommonForEachStatementSyntax)statement).Statement; + case SyntaxKind.ForEachStatement: + case SyntaxKind.ForEachVariableStatement: + return ((CommonForEachStatementSyntax)statement).Statement; - case SyntaxKind.UsingStatement: - return ((UsingStatementSyntax)statement).Statement; + case SyntaxKind.UsingStatement: + return ((UsingStatementSyntax)statement).Statement; - case SyntaxKind.FixedStatement: - return ((FixedStatementSyntax)statement).Statement; + case SyntaxKind.FixedStatement: + return ((FixedStatementSyntax)statement).Statement; - case SyntaxKind.CheckedStatement: - case SyntaxKind.UncheckedStatement: - return ((CheckedStatementSyntax)statement).Block; + case SyntaxKind.CheckedStatement: + case SyntaxKind.UncheckedStatement: + return ((CheckedStatementSyntax)statement).Block; - case SyntaxKind.UnsafeStatement: - return ((UnsafeStatementSyntax)statement).Block; + case SyntaxKind.UnsafeStatement: + return ((UnsafeStatementSyntax)statement).Block; - case SyntaxKind.LockStatement: - return ((LockStatementSyntax)statement).Statement; + case SyntaxKind.LockStatement: + return ((LockStatementSyntax)statement).Statement; - case SyntaxKind.IfStatement: - return ((IfStatementSyntax)statement).Statement; + case SyntaxKind.IfStatement: + return ((IfStatementSyntax)statement).Statement; - case SyntaxKind.TryStatement: - return ((TryStatementSyntax)statement).Block; + case SyntaxKind.TryStatement: + return ((TryStatementSyntax)statement).Block; - default: - return null; + default: + return null; + } } } } diff --git a/src/CSharp/CSharp/MemberDeclarationComparer.cs b/src/CSharp/CSharp/MemberDeclarationComparer.cs index b15e540102..2f7716db42 100644 --- a/src/CSharp/CSharp/MemberDeclarationComparer.cs +++ b/src/CSharp/CSharp/MemberDeclarationComparer.cs @@ -6,149 +6,150 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal abstract class MemberDeclarationComparer : IComparer +namespace Roslynator.CSharp { - internal const int MaxRank = 19; - - internal const int ConstRank = 0; - internal const int FieldRank = 1; - - internal static MemberDeclarationComparer ByKind { get; } = new ByKindMemberDeclarationComparer(); - - internal static MemberDeclarationComparer ByKindThenByName { get; } = new ByKindThenByNameMemberDeclarationComparer(); - - public abstract int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y); - - public virtual int GetRank(MemberDeclarationSyntax member) + internal abstract class MemberDeclarationComparer : IComparer { - if (member == null) - throw new ArgumentNullException(nameof(member)); + internal const int MaxRank = 19; - SyntaxKind kind = member.Kind(); + internal const int ConstRank = 0; + internal const int FieldRank = 1; - if (kind == SyntaxKind.FieldDeclaration) - { - return (((FieldDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.ConstKeyword)) - ? ConstRank - : FieldRank; - } + internal static MemberDeclarationComparer ByKind { get; } = new ByKindMemberDeclarationComparer(); - return MemberDeclarationKindComparer.Default.GetRank(kind); - } + internal static MemberDeclarationComparer ByKindThenByName { get; } = new ByKindThenByNameMemberDeclarationComparer(); - internal static bool CanBeSortedByName(SyntaxKind kind) - { - switch (kind) - { - case SyntaxKind.FieldDeclaration: - case SyntaxKind.ConstructorDeclaration: - case SyntaxKind.DelegateDeclaration: - case SyntaxKind.EventDeclaration: - case SyntaxKind.EventFieldDeclaration: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.StructDeclaration: - case SyntaxKind.RecordStructDeclaration: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.RecordDeclaration: - case SyntaxKind.NamespaceDeclaration: - return true; - case SyntaxKind.DestructorDeclaration: - case SyntaxKind.IndexerDeclaration: - case SyntaxKind.ConversionOperatorDeclaration: - case SyntaxKind.OperatorDeclaration: - case SyntaxKind.IncompleteMember: - return false; - default: - { - Debug.Fail($"unknown member '{kind}'"); - return false; - } - } - } + public abstract int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y); - private class ByKindMemberDeclarationComparer : MemberDeclarationComparer - { - public override int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + public virtual int GetRank(MemberDeclarationSyntax member) { - if (object.ReferenceEquals(x, y)) - return 0; - - if (x == null) - return -1; - - if (y == null) - return 1; - - return GetRank(x).CompareTo(GetRank(y)); - } - } + if (member is null) + throw new ArgumentNullException(nameof(member)); - private sealed class ByKindThenByNameMemberDeclarationComparer : ByKindMemberDeclarationComparer - { - public override int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y) - { - int result = base.Compare(x, y); + SyntaxKind kind = member.Kind(); - if (result == 0) - { - return string.Compare(GetName(x), GetName(y), StringComparison.CurrentCulture); - } - else + if (kind == SyntaxKind.FieldDeclaration) { - return result; + return (((FieldDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.ConstKeyword)) + ? ConstRank + : FieldRank; } + + return MemberDeclarationKindComparer.Default.GetRank(kind); } - private static string GetName(MemberDeclarationSyntax member) + internal static bool CanBeSortedByName(SyntaxKind kind) { - switch (member.Kind()) + switch (kind) { case SyntaxKind.FieldDeclaration: - { - return ((FieldDeclarationSyntax)member).Declaration?.Variables.FirstOrDefault()?.Identifier.ValueText; - } case SyntaxKind.ConstructorDeclaration: - return ((ConstructorDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.DelegateDeclaration: - return ((DelegateDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.EventDeclaration: - return ((EventDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.EventFieldDeclaration: - return ((EventFieldDeclarationSyntax)member).Declaration?.Variables.FirstOrDefault()?.Identifier.ValueText; case SyntaxKind.PropertyDeclaration: - return ((PropertyDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.EnumDeclaration: - return ((EnumDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.InterfaceDeclaration: - return ((InterfaceDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.StructDeclaration: - return ((StructDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.RecordStructDeclaration: case SyntaxKind.ClassDeclaration: - return ((ClassDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return ((RecordDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.NamespaceDeclaration: - return ((NamespaceDeclarationSyntax)member).Name.ToString(); + return true; case SyntaxKind.DestructorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.IncompleteMember: - return ""; + return false; default: { - Debug.Fail($"unknown member '{member.Kind()}'"); - return ""; + Debug.Fail($"unknown member '{kind}'"); + return false; } } } + + private class ByKindMemberDeclarationComparer : MemberDeclarationComparer + { + public override int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + if (object.ReferenceEquals(x, y)) + return 0; + + if (x is null) + return -1; + + if (y is null) + return 1; + + return GetRank(x).CompareTo(GetRank(y)); + } + } + + private sealed class ByKindThenByNameMemberDeclarationComparer : ByKindMemberDeclarationComparer + { + public override int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y) + { + int result = base.Compare(x, y); + + if (result == 0) + { + return string.Compare(GetName(x), GetName(y), StringComparison.CurrentCulture); + } + else + { + return result; + } + } + + private static string GetName(MemberDeclarationSyntax member) + { + switch (member.Kind()) + { + case SyntaxKind.FieldDeclaration: + { + return ((FieldDeclarationSyntax)member).Declaration?.Variables.FirstOrDefault()?.Identifier.ValueText; + } + case SyntaxKind.ConstructorDeclaration: + return ((ConstructorDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.DelegateDeclaration: + return ((DelegateDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.EventDeclaration: + return ((EventDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.EventFieldDeclaration: + return ((EventFieldDeclarationSyntax)member).Declaration?.Variables.FirstOrDefault()?.Identifier.ValueText; + case SyntaxKind.PropertyDeclaration: + return ((PropertyDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.MethodDeclaration: + return ((MethodDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.EnumDeclaration: + return ((EnumDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.InterfaceDeclaration: + return ((InterfaceDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.StructDeclaration: + return ((StructDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.ClassDeclaration: + return ((ClassDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((RecordDeclarationSyntax)member).Identifier.ValueText; + case SyntaxKind.NamespaceDeclaration: + return ((NamespaceDeclarationSyntax)member).Name.ToString(); + case SyntaxKind.DestructorDeclaration: + case SyntaxKind.IndexerDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.IncompleteMember: + return ""; + default: + { + Debug.Fail($"unknown member '{member.Kind()}'"); + return ""; + } + } + } + } } } diff --git a/src/CSharp/CSharp/MemberDeclarationInserter.cs b/src/CSharp/CSharp/MemberDeclarationInserter.cs index d7eafde840..e67ff11b02 100644 --- a/src/CSharp/CSharp/MemberDeclarationInserter.cs +++ b/src/CSharp/CSharp/MemberDeclarationInserter.cs @@ -5,193 +5,194 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal abstract class MemberDeclarationInserter +namespace Roslynator.CSharp { - public static MemberDeclarationInserter Default { get; } = new DefaultSyntaxInserter(); - - public abstract int GetInsertIndex(SyntaxList members, MemberDeclarationSyntax member); - - public abstract int GetInsertIndex(SyntaxList members, SyntaxKind kind); - - /// - /// Creates a new with the specified member inserted. - /// - /// - /// - public ClassDeclarationSyntax Insert(ClassDeclarationSyntax classDeclaration, MemberDeclarationSyntax member) + internal abstract class MemberDeclarationInserter { - if (classDeclaration == null) - throw new ArgumentNullException(nameof(classDeclaration)); + public static MemberDeclarationInserter Default { get; } = new DefaultSyntaxInserter(); - if (member == null) - throw new ArgumentNullException(nameof(member)); + public abstract int GetInsertIndex(SyntaxList members, MemberDeclarationSyntax member); - return classDeclaration.WithMembers(Insert(classDeclaration.Members, member)); - } + public abstract int GetInsertIndex(SyntaxList members, SyntaxKind kind); - /// - /// Creates a new with the specified member inserted. - /// - /// - /// - public CompilationUnitSyntax Insert(CompilationUnitSyntax compilationUnit, MemberDeclarationSyntax member) - { - if (compilationUnit == null) - throw new ArgumentNullException(nameof(compilationUnit)); + /// + /// Creates a new with the specified member inserted. + /// + /// + /// + public ClassDeclarationSyntax Insert(ClassDeclarationSyntax classDeclaration, MemberDeclarationSyntax member) + { + if (classDeclaration is null) + throw new ArgumentNullException(nameof(classDeclaration)); - if (member == null) - throw new ArgumentNullException(nameof(member)); + if (member is null) + throw new ArgumentNullException(nameof(member)); - return compilationUnit.WithMembers(Insert(compilationUnit.Members, member)); - } + return classDeclaration.WithMembers(Insert(classDeclaration.Members, member)); + } - /// - /// Creates a new with the specified member inserted. - /// - /// - /// - public InterfaceDeclarationSyntax Insert(InterfaceDeclarationSyntax interfaceDeclaration, MemberDeclarationSyntax member) - { - if (interfaceDeclaration == null) - throw new ArgumentNullException(nameof(interfaceDeclaration)); + /// + /// Creates a new with the specified member inserted. + /// + /// + /// + public CompilationUnitSyntax Insert(CompilationUnitSyntax compilationUnit, MemberDeclarationSyntax member) + { + if (compilationUnit is null) + throw new ArgumentNullException(nameof(compilationUnit)); - if (member == null) - throw new ArgumentNullException(nameof(member)); + if (member is null) + throw new ArgumentNullException(nameof(member)); - return interfaceDeclaration.WithMembers(Insert(interfaceDeclaration.Members, member)); - } + return compilationUnit.WithMembers(Insert(compilationUnit.Members, member)); + } - /// - /// Creates a new with the specified member inserted. - /// - /// - /// - public NamespaceDeclarationSyntax Insert(NamespaceDeclarationSyntax namespaceDeclaration, MemberDeclarationSyntax member) - { - if (namespaceDeclaration == null) - throw new ArgumentNullException(nameof(namespaceDeclaration)); + /// + /// Creates a new with the specified member inserted. + /// + /// + /// + public InterfaceDeclarationSyntax Insert(InterfaceDeclarationSyntax interfaceDeclaration, MemberDeclarationSyntax member) + { + if (interfaceDeclaration is null) + throw new ArgumentNullException(nameof(interfaceDeclaration)); - if (member == null) - throw new ArgumentNullException(nameof(member)); + if (member is null) + throw new ArgumentNullException(nameof(member)); - return namespaceDeclaration.WithMembers(Insert(namespaceDeclaration.Members, member)); - } + return interfaceDeclaration.WithMembers(Insert(interfaceDeclaration.Members, member)); + } - /// - /// Creates a new with the specified member inserted. - /// - /// - /// - public StructDeclarationSyntax Insert(StructDeclarationSyntax structDeclaration, MemberDeclarationSyntax member) - { - if (structDeclaration == null) - throw new ArgumentNullException(nameof(structDeclaration)); + /// + /// Creates a new with the specified member inserted. + /// + /// + /// + public NamespaceDeclarationSyntax Insert(NamespaceDeclarationSyntax namespaceDeclaration, MemberDeclarationSyntax member) + { + if (namespaceDeclaration is null) + throw new ArgumentNullException(nameof(namespaceDeclaration)); - if (member == null) - throw new ArgumentNullException(nameof(member)); + if (member is null) + throw new ArgumentNullException(nameof(member)); - return structDeclaration.WithMembers(Insert(structDeclaration.Members, member)); - } + return namespaceDeclaration.WithMembers(Insert(namespaceDeclaration.Members, member)); + } - /// - /// Creates a new with the specified member inserted. - /// - /// - /// - public RecordDeclarationSyntax Insert(RecordDeclarationSyntax recordDeclaration, MemberDeclarationSyntax member) - { - if (recordDeclaration == null) - throw new ArgumentNullException(nameof(recordDeclaration)); + /// + /// Creates a new with the specified member inserted. + /// + /// + /// + public StructDeclarationSyntax Insert(StructDeclarationSyntax structDeclaration, MemberDeclarationSyntax member) + { + if (structDeclaration is null) + throw new ArgumentNullException(nameof(structDeclaration)); - if (member == null) - throw new ArgumentNullException(nameof(member)); + if (member is null) + throw new ArgumentNullException(nameof(member)); - return recordDeclaration.WithMembers(Insert(recordDeclaration.Members, member)); - } + return structDeclaration.WithMembers(Insert(structDeclaration.Members, member)); + } - /// - /// Creates a new with the specified member removed. - /// - /// - /// - public TypeDeclarationSyntax Insert(TypeDeclarationSyntax typeDeclaration, MemberDeclarationSyntax member) - { - if (typeDeclaration == null) - throw new ArgumentNullException(nameof(typeDeclaration)); + /// + /// Creates a new with the specified member inserted. + /// + /// + /// + public RecordDeclarationSyntax Insert(RecordDeclarationSyntax recordDeclaration, MemberDeclarationSyntax member) + { + if (recordDeclaration is null) + throw new ArgumentNullException(nameof(recordDeclaration)); - if (member == null) - throw new ArgumentNullException(nameof(member)); + if (member is null) + throw new ArgumentNullException(nameof(member)); - return typeDeclaration.WithMembers(Insert(typeDeclaration.Members, member)); - } + return recordDeclaration.WithMembers(Insert(recordDeclaration.Members, member)); + } - /// - /// Creates a new list with the specified node inserted. - /// - /// - /// - internal SyntaxList Insert(SyntaxList members, MemberDeclarationSyntax member) - { - int index = GetInsertIndex(members, member); + /// + /// Creates a new with the specified member removed. + /// + /// + /// + public TypeDeclarationSyntax Insert(TypeDeclarationSyntax typeDeclaration, MemberDeclarationSyntax member) + { + if (typeDeclaration is null) + throw new ArgumentNullException(nameof(typeDeclaration)); - return members.Insert(index, member); - } + if (member is null) + throw new ArgumentNullException(nameof(member)); - private class DefaultSyntaxInserter : MemberDeclarationInserter - { - public override int GetInsertIndex(SyntaxList members, MemberDeclarationSyntax member) + return typeDeclaration.WithMembers(Insert(typeDeclaration.Members, member)); + } + + /// + /// Creates a new list with the specified node inserted. + /// + /// + /// + internal SyntaxList Insert(SyntaxList members, MemberDeclarationSyntax member) { - if (member == null) - throw new ArgumentNullException(nameof(member)); + int index = GetInsertIndex(members, member); - int index = -1; + return members.Insert(index, member); + } - for (int i = members.Count - 1; i >= 0; i--) + private class DefaultSyntaxInserter : MemberDeclarationInserter + { + public override int GetInsertIndex(SyntaxList members, MemberDeclarationSyntax member) { - int result = MemberDeclarationComparer.ByKind.Compare(members[i], member); + if (member is null) + throw new ArgumentNullException(nameof(member)); - if (result == 0) - { - return i + 1; - } - else if (result < 0 - && index == -1) + int index = -1; + + for (int i = members.Count - 1; i >= 0; i--) { - index = i + 1; + int result = MemberDeclarationComparer.ByKind.Compare(members[i], member); + + if (result == 0) + { + return i + 1; + } + else if (result < 0 + && index == -1) + { + index = i + 1; + } } - } - - if (index == -1) - return 0; - return index; - } + if (index == -1) + return 0; - public override int GetInsertIndex(SyntaxList members, SyntaxKind kind) - { - int index = -1; + return index; + } - for (int i = members.Count - 1; i >= 0; i--) + public override int GetInsertIndex(SyntaxList members, SyntaxKind kind) { - int result = MemberDeclarationKindComparer.Default.Compare(members[i].Kind(), kind); + int index = -1; - if (result == 0) + for (int i = members.Count - 1; i >= 0; i--) { - return i + 1; + int result = MemberDeclarationKindComparer.Default.Compare(members[i].Kind(), kind); + + if (result == 0) + { + return i + 1; + } + else if (result < 0 + && index == -1) + { + index = i + 1; + } } - else if (result < 0 - && index == -1) - { - index = i + 1; - } - } - if (index == -1) - return 0; + if (index == -1) + return 0; - return index; + return index; + } } } } diff --git a/src/CSharp/CSharp/MemberDeclarationListSelection.cs b/src/CSharp/CSharp/MemberDeclarationListSelection.cs index eb4aec193e..e4005b93b0 100644 --- a/src/CSharp/CSharp/MemberDeclarationListSelection.cs +++ b/src/CSharp/CSharp/MemberDeclarationListSelection.cs @@ -5,148 +5,149 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -namespace Roslynator.CSharp; - -/// -/// Represents selected member declarations in a . -/// -public sealed class MemberDeclarationListSelection : SyntaxListSelection +namespace Roslynator.CSharp { - private MemberDeclarationListSelection(SyntaxNode parent, SyntaxList members, TextSpan span, in SelectionResult result) - : this(parent, members, span, result.FirstIndex, result.LastIndex) - { - } - - private MemberDeclarationListSelection(SyntaxNode parent, SyntaxList members, TextSpan span, int firstIndex, int lastIndex) - : base(members, span, firstIndex, lastIndex) - { - Parent = parent; - } - - /// - /// Gets a node that contains selected members. - /// - public SyntaxNode Parent { get; } - - /// - /// Creates a new based on the specified compilation unit and span. - /// - /// - /// - public static MemberDeclarationListSelection Create(CompilationUnitSyntax compilationUnit, TextSpan span) - { - if (compilationUnit == null) - throw new ArgumentNullException(nameof(compilationUnit)); - - return Create(compilationUnit, compilationUnit.Members, span); - } - - /// - /// Creates a new based on the specified namespace declaration and span. - /// - /// - /// - public static MemberDeclarationListSelection Create(NamespaceDeclarationSyntax namespaceDeclaration, TextSpan span) - { - if (namespaceDeclaration == null) - throw new ArgumentNullException(nameof(namespaceDeclaration)); - - return Create(namespaceDeclaration, namespaceDeclaration.Members, span); - } - - /// - /// Creates a new based on the specified type declaration and span. - /// - /// - /// - public static MemberDeclarationListSelection Create(TypeDeclarationSyntax typeDeclaration, TextSpan span) - { - if (typeDeclaration == null) - throw new ArgumentNullException(nameof(typeDeclaration)); - - return Create(typeDeclaration, typeDeclaration.Members, span); - } - - private static MemberDeclarationListSelection Create(SyntaxNode parent, SyntaxList members, TextSpan span) - { - SelectionResult result = SelectionResult.Create(members, span); - - return new MemberDeclarationListSelection(parent, members, span, result); - } - - /// - /// Creates a new based on the specified namespace declaration and span. - /// - /// - /// - /// - /// True if the specified span contains at least one member; otherwise, false. - public static bool TryCreate(NamespaceDeclarationSyntax namespaceDeclaration, TextSpan span, out MemberDeclarationListSelection selectedMembers) - { - selectedMembers = Create(namespaceDeclaration, span, 1, int.MaxValue); - return selectedMembers != null; - } - - internal static bool TryCreate(NamespaceDeclarationSyntax namespaceDeclaration, TextSpan span, int minCount, out MemberDeclarationListSelection selectedMembers) - { - selectedMembers = Create(namespaceDeclaration, span, minCount, int.MaxValue); - return selectedMembers != null; - } - - internal static bool TryCreate(NamespaceDeclarationSyntax namespaceDeclaration, TextSpan span, int minCount, int maxCount, out MemberDeclarationListSelection selectedMembers) - { - selectedMembers = Create(namespaceDeclaration, span, minCount, maxCount); - return selectedMembers != null; - } - /// - /// Creates a new based on the specified type declaration and span. + /// Represents selected member declarations in a . /// - /// - /// - /// - /// True if the specified span contains at least one member; otherwise, false. - public static bool TryCreate(TypeDeclarationSyntax typeDeclaration, TextSpan span, out MemberDeclarationListSelection selectedMembers) + public sealed class MemberDeclarationListSelection : SyntaxListSelection { - selectedMembers = Create(typeDeclaration, span, 1, int.MaxValue); - return selectedMembers != null; - } - - internal static bool TryCreate(TypeDeclarationSyntax typeDeclaration, TextSpan span, int minCount, out MemberDeclarationListSelection selectedMembers) - { - selectedMembers = Create(typeDeclaration, span, minCount, int.MaxValue); - return selectedMembers != null; - } - - internal static bool TryCreate(TypeDeclarationSyntax typeDeclaration, TextSpan span, int minCount, int maxCount, out MemberDeclarationListSelection selectedMembers) - { - selectedMembers = Create(typeDeclaration, span, minCount, maxCount); - return selectedMembers != null; - } - - private static MemberDeclarationListSelection Create(NamespaceDeclarationSyntax declaration, TextSpan span, int minCount, int maxCount) - { - if (declaration == null) - return null; - - return Create(declaration, declaration.Members, span, minCount, maxCount); - } - - private static MemberDeclarationListSelection Create(TypeDeclarationSyntax declaration, TextSpan span, int minCount, int maxCount) - { - if (declaration == null) - return null; - - return Create(declaration, declaration.Members, span, minCount, maxCount); - } - - private static MemberDeclarationListSelection Create(MemberDeclarationSyntax declaration, SyntaxList members, TextSpan span, int minCount, int maxCount) - { - SelectionResult result = SelectionResult.Create(members, span, minCount, maxCount); - - if (!result.Success) - return null; - - return new MemberDeclarationListSelection(declaration, members, span, result); + private MemberDeclarationListSelection(SyntaxNode parent, SyntaxList members, TextSpan span, in SelectionResult result) + : this(parent, members, span, result.FirstIndex, result.LastIndex) + { + } + + private MemberDeclarationListSelection(SyntaxNode parent, SyntaxList members, TextSpan span, int firstIndex, int lastIndex) + : base(members, span, firstIndex, lastIndex) + { + Parent = parent; + } + + /// + /// Gets a node that contains selected members. + /// + public SyntaxNode Parent { get; } + + /// + /// Creates a new based on the specified compilation unit and span. + /// + /// + /// + public static MemberDeclarationListSelection Create(CompilationUnitSyntax compilationUnit, TextSpan span) + { + if (compilationUnit is null) + throw new ArgumentNullException(nameof(compilationUnit)); + + return Create(compilationUnit, compilationUnit.Members, span); + } + + /// + /// Creates a new based on the specified namespace declaration and span. + /// + /// + /// + public static MemberDeclarationListSelection Create(NamespaceDeclarationSyntax namespaceDeclaration, TextSpan span) + { + if (namespaceDeclaration is null) + throw new ArgumentNullException(nameof(namespaceDeclaration)); + + return Create(namespaceDeclaration, namespaceDeclaration.Members, span); + } + + /// + /// Creates a new based on the specified type declaration and span. + /// + /// + /// + public static MemberDeclarationListSelection Create(TypeDeclarationSyntax typeDeclaration, TextSpan span) + { + if (typeDeclaration is null) + throw new ArgumentNullException(nameof(typeDeclaration)); + + return Create(typeDeclaration, typeDeclaration.Members, span); + } + + private static MemberDeclarationListSelection Create(SyntaxNode parent, SyntaxList members, TextSpan span) + { + SelectionResult result = SelectionResult.Create(members, span); + + return new MemberDeclarationListSelection(parent, members, span, result); + } + + /// + /// Creates a new based on the specified namespace declaration and span. + /// + /// + /// + /// + /// True if the specified span contains at least one member; otherwise, false. + public static bool TryCreate(NamespaceDeclarationSyntax namespaceDeclaration, TextSpan span, out MemberDeclarationListSelection selectedMembers) + { + selectedMembers = Create(namespaceDeclaration, span, 1, int.MaxValue); + return selectedMembers is not null; + } + + internal static bool TryCreate(NamespaceDeclarationSyntax namespaceDeclaration, TextSpan span, int minCount, out MemberDeclarationListSelection selectedMembers) + { + selectedMembers = Create(namespaceDeclaration, span, minCount, int.MaxValue); + return selectedMembers is not null; + } + + internal static bool TryCreate(NamespaceDeclarationSyntax namespaceDeclaration, TextSpan span, int minCount, int maxCount, out MemberDeclarationListSelection selectedMembers) + { + selectedMembers = Create(namespaceDeclaration, span, minCount, maxCount); + return selectedMembers is not null; + } + + /// + /// Creates a new based on the specified type declaration and span. + /// + /// + /// + /// + /// True if the specified span contains at least one member; otherwise, false. + public static bool TryCreate(TypeDeclarationSyntax typeDeclaration, TextSpan span, out MemberDeclarationListSelection selectedMembers) + { + selectedMembers = Create(typeDeclaration, span, 1, int.MaxValue); + return selectedMembers is not null; + } + + internal static bool TryCreate(TypeDeclarationSyntax typeDeclaration, TextSpan span, int minCount, out MemberDeclarationListSelection selectedMembers) + { + selectedMembers = Create(typeDeclaration, span, minCount, int.MaxValue); + return selectedMembers is not null; + } + + internal static bool TryCreate(TypeDeclarationSyntax typeDeclaration, TextSpan span, int minCount, int maxCount, out MemberDeclarationListSelection selectedMembers) + { + selectedMembers = Create(typeDeclaration, span, minCount, maxCount); + return selectedMembers is not null; + } + + private static MemberDeclarationListSelection Create(NamespaceDeclarationSyntax declaration, TextSpan span, int minCount, int maxCount) + { + if (declaration is null) + return null; + + return Create(declaration, declaration.Members, span, minCount, maxCount); + } + + private static MemberDeclarationListSelection Create(TypeDeclarationSyntax declaration, TextSpan span, int minCount, int maxCount) + { + if (declaration is null) + return null; + + return Create(declaration, declaration.Members, span, minCount, maxCount); + } + + private static MemberDeclarationListSelection Create(MemberDeclarationSyntax declaration, SyntaxList members, TextSpan span, int minCount, int maxCount) + { + SelectionResult result = SelectionResult.Create(members, span, minCount, maxCount); + + if (!result.Success) + return null; + + return new MemberDeclarationListSelection(declaration, members, span, result); + } } } diff --git a/src/CSharp/CSharp/MethodChain.cs b/src/CSharp/CSharp/MethodChain.cs index 85cb816129..92989839f5 100644 --- a/src/CSharp/CSharp/MethodChain.cs +++ b/src/CSharp/CSharp/MethodChain.cs @@ -7,178 +7,179 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal readonly struct MethodChain : IEnumerable +namespace Roslynator.CSharp { - public MethodChain(ExpressionSyntax expression) - { - Expression = expression; - } - - public ExpressionSyntax Expression { get; } - - IEnumerator IEnumerable.GetEnumerator() + internal readonly struct MethodChain : IEnumerable { - if (Expression != null) - return new EnumeratorImpl(this); + public MethodChain(ExpressionSyntax expression) + { + Expression = expression; + } - return Empty.Enumerator(); - } + public ExpressionSyntax Expression { get; } - IEnumerator IEnumerable.GetEnumerator() - { - if (Expression != null) - return new EnumeratorImpl(this); + IEnumerator IEnumerable.GetEnumerator() + { + if (Expression is not null) + return new EnumeratorImpl(this); - return Empty.Enumerator(); - } + return Empty.Enumerator(); + } - public Enumerator GetEnumerator() - { - return new Enumerator(this); - } + IEnumerator IEnumerable.GetEnumerator() + { + if (Expression is not null) + return new EnumeratorImpl(this); - public struct Enumerator - { - private readonly MethodChain _chain; - private SyntaxNode _current; + return Empty.Enumerator(); + } - internal Enumerator(MethodChain chain) + public Enumerator GetEnumerator() { - _chain = chain; - _current = null; + return new Enumerator(this); } - public bool MoveNext() + public struct Enumerator { - if (_current == null) - { - _current = _chain.Expression; + private readonly MethodChain _chain; + private SyntaxNode _current; - return _current != null; - } - - ExpressionSyntax last = GetLastChild(_current); - - if (last != null) + internal Enumerator(MethodChain chain) { - _current = last; + _chain = chain; + _current = null; } - else + + public bool MoveNext() { - while (_current != _chain.Expression - && IsFirstChild(_current)) + if (_current is null) { - _current = _current.Parent; + _current = _chain.Expression; + + return _current is not null; } - if (_current == _chain.Expression) + ExpressionSyntax last = GetLastChild(_current); + + if (last is not null) { - _current = null; - return false; + _current = last; } + else + { + while (_current != _chain.Expression + && IsFirstChild(_current)) + { + _current = _current.Parent; + } - _current = GetPreviousSibling(_current); - } + if (_current == _chain.Expression) + { + _current = null; + return false; + } - return true; - } + _current = GetPreviousSibling(_current); + } - private static ExpressionSyntax GetLastChild(SyntaxNode node) - { - switch (node?.Kind()) - { - case SyntaxKind.ConditionalAccessExpression: - return ((ConditionalAccessExpressionSyntax)node).WhenNotNull; - case SyntaxKind.MemberBindingExpression: - return ((MemberBindingExpressionSyntax)node).Name; - case SyntaxKind.SimpleMemberAccessExpression: - return ((MemberAccessExpressionSyntax)node).Name; - case SyntaxKind.ElementAccessExpression: - return ((ElementAccessExpressionSyntax)node).Expression; - case SyntaxKind.InvocationExpression: - return ((InvocationExpressionSyntax)node).Expression; + return true; } - return null; - } + private static ExpressionSyntax GetLastChild(SyntaxNode node) + { + switch (node?.Kind()) + { + case SyntaxKind.ConditionalAccessExpression: + return ((ConditionalAccessExpressionSyntax)node).WhenNotNull; + case SyntaxKind.MemberBindingExpression: + return ((MemberBindingExpressionSyntax)node).Name; + case SyntaxKind.SimpleMemberAccessExpression: + return ((MemberAccessExpressionSyntax)node).Name; + case SyntaxKind.ElementAccessExpression: + return ((ElementAccessExpressionSyntax)node).Expression; + case SyntaxKind.InvocationExpression: + return ((InvocationExpressionSyntax)node).Expression; + } - private static SyntaxNode GetPreviousSibling(SyntaxNode node) - { - SyntaxNode parent = node.Parent; + return null; + } - switch (parent.Kind()) + private static SyntaxNode GetPreviousSibling(SyntaxNode node) { - case SyntaxKind.ConditionalAccessExpression: - { - var conditionalAccess = (ConditionalAccessExpressionSyntax)parent; + SyntaxNode parent = node.Parent; - if (conditionalAccess.WhenNotNull == node) - return conditionalAccess.Expression; + switch (parent.Kind()) + { + case SyntaxKind.ConditionalAccessExpression: + { + var conditionalAccess = (ConditionalAccessExpressionSyntax)parent; - break; - } - case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)parent; + if (conditionalAccess.WhenNotNull == node) + return conditionalAccess.Expression; - if (memberAccess.Name == node) - return memberAccess.Expression; + break; + } + case SyntaxKind.SimpleMemberAccessExpression: + { + var memberAccess = (MemberAccessExpressionSyntax)parent; - break; - } - } + if (memberAccess.Name == node) + return memberAccess.Expression; - return null; - } + break; + } + } - private static bool IsFirstChild(SyntaxNode node) - { - SyntaxNode parent = node.Parent; + return null; + } - switch (parent.Kind()) + private static bool IsFirstChild(SyntaxNode node) { - case SyntaxKind.ConditionalAccessExpression: - return ((ConditionalAccessExpressionSyntax)parent).Expression == node; - case SyntaxKind.SimpleMemberAccessExpression: - return ((MemberAccessExpressionSyntax)parent).Expression == node; - } + SyntaxNode parent = node.Parent; - return true; - } + switch (parent.Kind()) + { + case SyntaxKind.ConditionalAccessExpression: + return ((ConditionalAccessExpressionSyntax)parent).Expression == node; + case SyntaxKind.SimpleMemberAccessExpression: + return ((MemberAccessExpressionSyntax)parent).Expression == node; + } - public SyntaxNode Current => _current ?? throw new InvalidOperationException(); + return true; + } - public void Reset() - { - _current = null; - } + public SyntaxNode Current => _current ?? throw new InvalidOperationException(); - public override bool Equals(object obj) => throw new NotSupportedException(); + public void Reset() + { + _current = null; + } - public override int GetHashCode() => throw new NotSupportedException(); - } + public override bool Equals(object obj) => throw new NotSupportedException(); - private class EnumeratorImpl : IEnumerator - { - private Enumerator _en; + public override int GetHashCode() => throw new NotSupportedException(); + } - internal EnumeratorImpl(in MethodChain methodChain) + private class EnumeratorImpl : IEnumerator { - _en = new Enumerator(methodChain); - } + private Enumerator _en; + + internal EnumeratorImpl(in MethodChain methodChain) + { + _en = new Enumerator(methodChain); + } - public SyntaxNode Current => _en.Current; + public SyntaxNode Current => _en.Current; - object IEnumerator.Current => _en.Current; + object IEnumerator.Current => _en.Current; - public bool MoveNext() => _en.MoveNext(); + public bool MoveNext() => _en.MoveNext(); - void IEnumerator.Reset() => _en.Reset(); + void IEnumerator.Reset() => _en.Reset(); - void IDisposable.Dispose() - { + void IDisposable.Dispose() + { + } } } } diff --git a/src/CSharp/CSharp/ModifierList.cs b/src/CSharp/CSharp/ModifierList.cs index fc00461096..5a0cf39a48 100644 --- a/src/CSharp/CSharp/ModifierList.cs +++ b/src/CSharp/CSharp/ModifierList.cs @@ -7,602 +7,603 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Roslynator.CSharp; - -/// -/// A set of static methods that allows manipulation with modifiers. -/// -public static class ModifierList +namespace Roslynator.CSharp { /// - /// Returns an index the specified token should be inserted at. + /// A set of static methods that allows manipulation with modifiers. /// - /// - /// - /// - public static int GetInsertIndex(SyntaxTokenList tokens, SyntaxToken token, IComparer comparer = null) + public static class ModifierList { - if (comparer == null) - comparer = ModifierComparer.Default; - - int index = -1; - - for (int i = tokens.Count - 1; i >= 0; i--) + /// + /// Returns an index the specified token should be inserted at. + /// + /// + /// + /// + public static int GetInsertIndex(SyntaxTokenList tokens, SyntaxToken token, IComparer comparer = null) { - int result = comparer.Compare(tokens[i], token); + if (comparer is null) + comparer = ModifierComparer.Default; - if (result == 0) - { - return i + 1; - } - else if (result < 0 - && index == -1) - { - index = i + 1; - } - } + int index = -1; - if (index == -1) - return 0; + for (int i = tokens.Count - 1; i >= 0; i--) + { + int result = comparer.Compare(tokens[i], token); - return index; - } + if (result == 0) + { + return i + 1; + } + else if (result < 0 + && index == -1) + { + index = i + 1; + } + } - /// - /// Returns an index a token with the specified kind should be inserted at. - /// - /// - /// - /// - public static int GetInsertIndex(SyntaxTokenList tokens, SyntaxKind kind, IComparer comparer = null) - { - if (comparer == null) - comparer = ModifierKindComparer.Default; + if (index == -1) + return 0; - int index = -1; + return index; + } - for (int i = tokens.Count - 1; i >= 0; i--) + /// + /// Returns an index a token with the specified kind should be inserted at. + /// + /// + /// + /// + public static int GetInsertIndex(SyntaxTokenList tokens, SyntaxKind kind, IComparer comparer = null) { - int result = comparer.Compare(tokens[i].Kind(), kind); + if (comparer is null) + comparer = ModifierKindComparer.Default; - if (result == 0) - { - return i + 1; - } - else if (result < 0 - && index == -1) - { - index = i + 1; - } - } - - if (index == -1) - return 0; + int index = -1; - return index; - } + for (int i = tokens.Count - 1; i >= 0; i--) + { + int result = comparer.Compare(tokens[i].Kind(), kind); - internal static SyntaxNode Insert(SyntaxNode node, Accessibility accessibility, IComparer comparer = null) - { - switch (accessibility) - { - case Accessibility.Private: + if (result == 0) { - return Insert(node, SyntaxKind.PrivateKeyword, comparer); + return i + 1; } - case Accessibility.Protected: + else if (result < 0 + && index == -1) { - return Insert(node, SyntaxKind.ProtectedKeyword, comparer); + index = i + 1; } - case Accessibility.ProtectedAndInternal: - { - node = Insert(node, SyntaxKind.PrivateKeyword, comparer); + } - return Insert(node, SyntaxKind.ProtectedKeyword, comparer); - } - case Accessibility.Internal: - { - return Insert(node, SyntaxKind.InternalKeyword, comparer); - } - case Accessibility.Public: - { - return Insert(node, SyntaxKind.PublicKeyword, comparer); - } - case Accessibility.ProtectedOrInternal: - { - node = Insert(node, SyntaxKind.ProtectedKeyword, comparer); + if (index == -1) + return 0; - return Insert(node, SyntaxKind.InternalKeyword, comparer); - } + return index; } - return node; - } - - /// - /// Creates a new node with a modifier of the specified kind inserted. - /// - /// - /// - /// - /// - public static TNode Insert(TNode node, SyntaxKind kind, IComparer comparer = null) where TNode : SyntaxNode - { - switch (node.Kind()) + internal static SyntaxNode Insert(SyntaxNode node, Accessibility accessibility, IComparer comparer = null) { - case SyntaxKind.ClassDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ClassDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.ConstructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ConstructorDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.ConversionOperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.DelegateDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((DelegateDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.DestructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((DestructorDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.EnumDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EnumDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.EventDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EventDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.EventFieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EventFieldDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.FieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((FieldDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.IndexerDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((IndexerDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.InterfaceDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((InterfaceDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.MethodDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((MethodDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.OperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((OperatorDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.PropertyDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((PropertyDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((RecordDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.StructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((StructDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.UnknownAccessorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((AccessorDeclarationSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.LocalDeclarationStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((LocalDeclarationStatementSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.LocalFunctionStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((LocalFunctionStatementSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.Parameter: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ParameterSyntax)(SyntaxNode)node, kind, comparer); - case SyntaxKind.IncompleteMember: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((IncompleteMemberSyntax)(SyntaxNode)node, kind, comparer); - } + switch (accessibility) + { + case Accessibility.Private: + { + return Insert(node, SyntaxKind.PrivateKeyword, comparer); + } + case Accessibility.Protected: + { + return Insert(node, SyntaxKind.ProtectedKeyword, comparer); + } + case Accessibility.ProtectedAndInternal: + { + node = Insert(node, SyntaxKind.PrivateKeyword, comparer); + + return Insert(node, SyntaxKind.ProtectedKeyword, comparer); + } + case Accessibility.Internal: + { + return Insert(node, SyntaxKind.InternalKeyword, comparer); + } + case Accessibility.Public: + { + return Insert(node, SyntaxKind.PublicKeyword, comparer); + } + case Accessibility.ProtectedOrInternal: + { + node = Insert(node, SyntaxKind.ProtectedKeyword, comparer); + + return Insert(node, SyntaxKind.InternalKeyword, comparer); + } + } - throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); - } + return node; + } - /// - /// Creates a new node with the specified modifier inserted. - /// - /// - /// - /// - /// - public static TNode Insert(TNode node, SyntaxToken modifier, IComparer comparer = null) where TNode : SyntaxNode - { - switch (node.Kind()) + /// + /// Creates a new node with a modifier of the specified kind inserted. + /// + /// + /// + /// + /// + public static TNode Insert(TNode node, SyntaxKind kind, IComparer comparer = null) where TNode : SyntaxNode { - case SyntaxKind.ClassDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ClassDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.ConstructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ConstructorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.ConversionOperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.DelegateDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((DelegateDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.DestructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((DestructorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.EnumDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EnumDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.EventDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EventDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.EventFieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EventFieldDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.FieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((FieldDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.IndexerDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((IndexerDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.InterfaceDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((InterfaceDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.MethodDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((MethodDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.OperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((OperatorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.PropertyDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((PropertyDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((RecordDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.StructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((StructDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.UnknownAccessorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((AccessorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.LocalDeclarationStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((LocalDeclarationStatementSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.LocalFunctionStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((LocalFunctionStatementSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.Parameter: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ParameterSyntax)(SyntaxNode)node, modifier, comparer); - case SyntaxKind.IncompleteMember: - return (TNode)(SyntaxNode)ModifierList.Instance.Insert((IncompleteMemberSyntax)(SyntaxNode)node, modifier, comparer); - } + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ClassDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.ConstructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ConstructorDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.ConversionOperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.DelegateDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((DelegateDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.DestructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((DestructorDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.EnumDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EnumDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.EventDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EventDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.EventFieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EventFieldDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.FieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((FieldDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.IndexerDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((IndexerDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.InterfaceDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((InterfaceDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.MethodDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((MethodDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.OperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((OperatorDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.PropertyDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((PropertyDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((RecordDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.StructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((StructDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((AccessorDeclarationSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.LocalDeclarationStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((LocalDeclarationStatementSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.LocalFunctionStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((LocalFunctionStatementSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.Parameter: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ParameterSyntax)(SyntaxNode)node, kind, comparer); + case SyntaxKind.IncompleteMember: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((IncompleteMemberSyntax)(SyntaxNode)node, kind, comparer); + } - throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); - } + throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); + } - /// - /// Creates a new node with a modifier of the specified kind removed. - /// - /// - /// - /// - public static TNode Remove(TNode node, SyntaxKind kind) where TNode : SyntaxNode - { - switch (node.Kind()) + /// + /// Creates a new node with the specified modifier inserted. + /// + /// + /// + /// + /// + public static TNode Insert(TNode node, SyntaxToken modifier, IComparer comparer = null) where TNode : SyntaxNode { - case SyntaxKind.ClassDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ClassDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.ConstructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ConstructorDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.ConversionOperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.DelegateDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((DelegateDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.DestructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((DestructorDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.EnumDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EnumDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.EventDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EventDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.EventFieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EventFieldDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.FieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((FieldDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.IndexerDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((IndexerDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.InterfaceDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((InterfaceDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.MethodDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((MethodDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.OperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((OperatorDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.PropertyDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((PropertyDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((RecordDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.StructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((StructDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.UnknownAccessorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((AccessorDeclarationSyntax)(SyntaxNode)node, kind); - case SyntaxKind.LocalDeclarationStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((LocalDeclarationStatementSyntax)(SyntaxNode)node, kind); - case SyntaxKind.LocalFunctionStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((LocalFunctionStatementSyntax)(SyntaxNode)node, kind); - case SyntaxKind.Parameter: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ParameterSyntax)(SyntaxNode)node, kind); - case SyntaxKind.IncompleteMember: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((IncompleteMemberSyntax)(SyntaxNode)node, kind); - } + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ClassDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.ConstructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ConstructorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.ConversionOperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.DelegateDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((DelegateDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.DestructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((DestructorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.EnumDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EnumDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.EventDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EventDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.EventFieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((EventFieldDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.FieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((FieldDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.IndexerDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((IndexerDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.InterfaceDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((InterfaceDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.MethodDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((MethodDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.OperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((OperatorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.PropertyDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((PropertyDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((RecordDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.StructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((StructDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((AccessorDeclarationSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.LocalDeclarationStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((LocalDeclarationStatementSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.LocalFunctionStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((LocalFunctionStatementSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.Parameter: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((ParameterSyntax)(SyntaxNode)node, modifier, comparer); + case SyntaxKind.IncompleteMember: + return (TNode)(SyntaxNode)ModifierList.Instance.Insert((IncompleteMemberSyntax)(SyntaxNode)node, modifier, comparer); + } - throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); - } + throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); + } - /// - /// Creates a new node with the specified modifier removed. - /// - /// - /// - /// - public static TNode Remove(TNode node, SyntaxToken modifier) where TNode : SyntaxNode - { - switch (node.Kind()) + /// + /// Creates a new node with a modifier of the specified kind removed. + /// + /// + /// + /// + public static TNode Remove(TNode node, SyntaxKind kind) where TNode : SyntaxNode { - case SyntaxKind.ClassDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ClassDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.ConstructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ConstructorDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.ConversionOperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.DelegateDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((DelegateDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.DestructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((DestructorDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.EnumDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EnumDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.EventDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EventDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.EventFieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EventFieldDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.FieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((FieldDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.IndexerDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((IndexerDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.InterfaceDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((InterfaceDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.MethodDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((MethodDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.OperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((OperatorDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.PropertyDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((PropertyDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((RecordDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.StructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((StructDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.UnknownAccessorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((AccessorDeclarationSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.LocalDeclarationStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((LocalDeclarationStatementSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.LocalFunctionStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((LocalFunctionStatementSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.Parameter: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ParameterSyntax)(SyntaxNode)node, modifier); - case SyntaxKind.IncompleteMember: - return (TNode)(SyntaxNode)ModifierList.Instance.Remove((IncompleteMemberSyntax)(SyntaxNode)node, modifier); - } + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ClassDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.ConstructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ConstructorDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.ConversionOperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.DelegateDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((DelegateDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.DestructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((DestructorDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.EnumDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EnumDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.EventDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EventDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.EventFieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EventFieldDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.FieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((FieldDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.IndexerDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((IndexerDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.InterfaceDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((InterfaceDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.MethodDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((MethodDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.OperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((OperatorDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.PropertyDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((PropertyDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((RecordDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.StructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((StructDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((AccessorDeclarationSyntax)(SyntaxNode)node, kind); + case SyntaxKind.LocalDeclarationStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((LocalDeclarationStatementSyntax)(SyntaxNode)node, kind); + case SyntaxKind.LocalFunctionStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((LocalFunctionStatementSyntax)(SyntaxNode)node, kind); + case SyntaxKind.Parameter: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ParameterSyntax)(SyntaxNode)node, kind); + case SyntaxKind.IncompleteMember: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((IncompleteMemberSyntax)(SyntaxNode)node, kind); + } - throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); - } + throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); + } - /// - /// Creates a new node with a modifier at the specified index removed. - /// - /// - /// - /// - public static TNode RemoveAt(TNode node, int index) where TNode : SyntaxNode - { - switch (node.Kind()) + /// + /// Creates a new node with the specified modifier removed. + /// + /// + /// + /// + public static TNode Remove(TNode node, SyntaxToken modifier) where TNode : SyntaxNode { - case SyntaxKind.ClassDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((ClassDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.ConstructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((ConstructorDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.ConversionOperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.DelegateDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((DelegateDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.DestructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((DestructorDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.EnumDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((EnumDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.EventDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((EventDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.EventFieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((EventFieldDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.FieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((FieldDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.IndexerDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((IndexerDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.InterfaceDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((InterfaceDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.MethodDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((MethodDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.OperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((OperatorDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.PropertyDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((PropertyDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((RecordDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.StructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((StructDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.UnknownAccessorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((AccessorDeclarationSyntax)(SyntaxNode)node, index); - case SyntaxKind.LocalDeclarationStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((LocalDeclarationStatementSyntax)(SyntaxNode)node, index); - case SyntaxKind.LocalFunctionStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((LocalFunctionStatementSyntax)(SyntaxNode)node, index); - case SyntaxKind.Parameter: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((ParameterSyntax)(SyntaxNode)node, index); - case SyntaxKind.IncompleteMember: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((IncompleteMemberSyntax)(SyntaxNode)node, index); - } + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ClassDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.ConstructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ConstructorDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.ConversionOperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.DelegateDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((DelegateDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.DestructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((DestructorDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.EnumDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EnumDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.EventDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EventDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.EventFieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((EventFieldDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.FieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((FieldDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.IndexerDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((IndexerDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.InterfaceDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((InterfaceDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.MethodDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((MethodDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.OperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((OperatorDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.PropertyDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((PropertyDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((RecordDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.StructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((StructDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((AccessorDeclarationSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.LocalDeclarationStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((LocalDeclarationStatementSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.LocalFunctionStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((LocalFunctionStatementSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.Parameter: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((ParameterSyntax)(SyntaxNode)node, modifier); + case SyntaxKind.IncompleteMember: + return (TNode)(SyntaxNode)ModifierList.Instance.Remove((IncompleteMemberSyntax)(SyntaxNode)node, modifier); + } - throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); - } + throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); + } - /// - /// Creates a new node with modifiers that matches the predicate removed. - /// - /// - /// - /// - public static TNode RemoveAll(TNode node, Func predicate) where TNode : SyntaxNode - { - switch (node.Kind()) + /// + /// Creates a new node with a modifier at the specified index removed. + /// + /// + /// + /// + public static TNode RemoveAt(TNode node, int index) where TNode : SyntaxNode { - case SyntaxKind.ClassDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ClassDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.ConstructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ConstructorDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.ConversionOperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.DelegateDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((DelegateDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.DestructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((DestructorDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.EnumDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EnumDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.EventDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EventDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.EventFieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EventFieldDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.FieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((FieldDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.IndexerDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((IndexerDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.InterfaceDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((InterfaceDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.MethodDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((MethodDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.OperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((OperatorDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.PropertyDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((PropertyDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((RecordDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.StructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((StructDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.UnknownAccessorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((AccessorDeclarationSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.LocalDeclarationStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((LocalDeclarationStatementSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.LocalFunctionStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((LocalFunctionStatementSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.Parameter: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ParameterSyntax)(SyntaxNode)node, predicate); - case SyntaxKind.IncompleteMember: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((IncompleteMemberSyntax)(SyntaxNode)node, predicate); - } + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((ClassDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.ConstructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((ConstructorDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.ConversionOperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.DelegateDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((DelegateDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.DestructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((DestructorDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.EnumDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((EnumDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.EventDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((EventDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.EventFieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((EventFieldDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.FieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((FieldDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.IndexerDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((IndexerDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.InterfaceDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((InterfaceDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.MethodDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((MethodDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.OperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((OperatorDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.PropertyDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((PropertyDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((RecordDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.StructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((StructDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((AccessorDeclarationSyntax)(SyntaxNode)node, index); + case SyntaxKind.LocalDeclarationStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((LocalDeclarationStatementSyntax)(SyntaxNode)node, index); + case SyntaxKind.LocalFunctionStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((LocalFunctionStatementSyntax)(SyntaxNode)node, index); + case SyntaxKind.Parameter: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((ParameterSyntax)(SyntaxNode)node, index); + case SyntaxKind.IncompleteMember: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAt((IncompleteMemberSyntax)(SyntaxNode)node, index); + } - throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); - } + throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); + } - /// - /// Creates a new node with all modifiers removed. - /// - /// - /// - public static TNode RemoveAll(TNode node) where TNode : SyntaxNode - { - switch (node.Kind()) + /// + /// Creates a new node with modifiers that matches the predicate removed. + /// + /// + /// + /// + public static TNode RemoveAll(TNode node, Func predicate) where TNode : SyntaxNode { - case SyntaxKind.ClassDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ClassDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.ConstructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ConstructorDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.ConversionOperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ConversionOperatorDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.DelegateDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((DelegateDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.DestructorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((DestructorDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.EnumDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EnumDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.EventDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EventDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.EventFieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EventFieldDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.FieldDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((FieldDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.IndexerDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((IndexerDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.InterfaceDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((InterfaceDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.MethodDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((MethodDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.OperatorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((OperatorDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.PropertyDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((PropertyDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((RecordDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.StructDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((StructDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.GetAccessorDeclaration: - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - case SyntaxKind.UnknownAccessorDeclaration: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((AccessorDeclarationSyntax)(SyntaxNode)node); - case SyntaxKind.LocalDeclarationStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((LocalDeclarationStatementSyntax)(SyntaxNode)node); - case SyntaxKind.LocalFunctionStatement: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((LocalFunctionStatementSyntax)(SyntaxNode)node); - case SyntaxKind.Parameter: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ParameterSyntax)(SyntaxNode)node); - case SyntaxKind.IncompleteMember: - return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((IncompleteMemberSyntax)(SyntaxNode)node); - } + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ClassDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.ConstructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ConstructorDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.ConversionOperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ConversionOperatorDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.DelegateDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((DelegateDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.DestructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((DestructorDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.EnumDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EnumDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.EventDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EventDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.EventFieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EventFieldDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.FieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((FieldDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.IndexerDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((IndexerDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.InterfaceDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((InterfaceDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.MethodDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((MethodDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.OperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((OperatorDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.PropertyDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((PropertyDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((RecordDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.StructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((StructDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((AccessorDeclarationSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.LocalDeclarationStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((LocalDeclarationStatementSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.LocalFunctionStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((LocalFunctionStatementSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.Parameter: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ParameterSyntax)(SyntaxNode)node, predicate); + case SyntaxKind.IncompleteMember: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((IncompleteMemberSyntax)(SyntaxNode)node, predicate); + } - throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); - } + throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); + } - /// - /// Creates a new list of modifiers with the modifier of the specified kind inserted. - /// - /// - /// - /// - public static SyntaxTokenList Insert(SyntaxTokenList modifiers, SyntaxKind kind, IComparer comparer = null) - { - if (!modifiers.Any()) - return modifiers.Add(Token(kind)); + /// + /// Creates a new node with all modifiers removed. + /// + /// + /// + public static TNode RemoveAll(TNode node) where TNode : SyntaxNode + { + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ClassDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.ConstructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ConstructorDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.ConversionOperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ConversionOperatorDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.DelegateDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((DelegateDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.DestructorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((DestructorDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.EnumDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EnumDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.EventDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EventDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.EventFieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((EventFieldDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.FieldDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((FieldDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.IndexerDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((IndexerDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.InterfaceDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((InterfaceDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.MethodDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((MethodDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.OperatorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((OperatorDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.PropertyDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((PropertyDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((RecordDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.StructDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((StructDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.GetAccessorDeclaration: + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + case SyntaxKind.UnknownAccessorDeclaration: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((AccessorDeclarationSyntax)(SyntaxNode)node); + case SyntaxKind.LocalDeclarationStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((LocalDeclarationStatementSyntax)(SyntaxNode)node); + case SyntaxKind.LocalFunctionStatement: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((LocalFunctionStatementSyntax)(SyntaxNode)node); + case SyntaxKind.Parameter: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((ParameterSyntax)(SyntaxNode)node); + case SyntaxKind.IncompleteMember: + return (TNode)(SyntaxNode)ModifierList.Instance.RemoveAll((IncompleteMemberSyntax)(SyntaxNode)node); + } - return InsertImpl(modifiers, Token(kind), GetInsertIndex(modifiers, kind, comparer)); - } + throw new ArgumentException($"'{node.Kind()}' cannot have modifiers.", nameof(node)); + } - /// - /// Creates a new list of modifiers with a specified modifier inserted. - /// - /// - /// - /// - public static SyntaxTokenList Insert(SyntaxTokenList modifiers, SyntaxToken modifier, IComparer comparer = null) - { - if (!modifiers.Any()) - return modifiers.Add(modifier); + /// + /// Creates a new list of modifiers with the modifier of the specified kind inserted. + /// + /// + /// + /// + public static SyntaxTokenList Insert(SyntaxTokenList modifiers, SyntaxKind kind, IComparer comparer = null) + { + if (!modifiers.Any()) + return modifiers.Add(Token(kind)); - return InsertImpl(modifiers, modifier, GetInsertIndex(modifiers, modifier, comparer)); - } + return InsertImpl(modifiers, Token(kind), GetInsertIndex(modifiers, kind, comparer)); + } - private static SyntaxTokenList InsertImpl(SyntaxTokenList modifiers, SyntaxToken modifier, int index) - { - if (index == 0) + /// + /// Creates a new list of modifiers with a specified modifier inserted. + /// + /// + /// + /// + public static SyntaxTokenList Insert(SyntaxTokenList modifiers, SyntaxToken modifier, IComparer comparer = null) { - SyntaxToken firstModifier = modifiers[index]; + if (!modifiers.Any()) + return modifiers.Add(modifier); - SyntaxTriviaList trivia = firstModifier.LeadingTrivia; + return InsertImpl(modifiers, modifier, GetInsertIndex(modifiers, modifier, comparer)); + } - if (trivia.Any()) + private static SyntaxTokenList InsertImpl(SyntaxTokenList modifiers, SyntaxToken modifier, int index) + { + if (index == 0) { - SyntaxTriviaList leadingTrivia = modifier.LeadingTrivia; + SyntaxToken firstModifier = modifiers[index]; + + SyntaxTriviaList trivia = firstModifier.LeadingTrivia; + + if (trivia.Any()) + { + SyntaxTriviaList leadingTrivia = modifier.LeadingTrivia; - if (!leadingTrivia.IsSingleElasticMarker()) - trivia = trivia.AddRange(leadingTrivia); + if (!leadingTrivia.IsSingleElasticMarker()) + trivia = trivia.AddRange(leadingTrivia); - modifier = modifier.WithLeadingTrivia(trivia); + modifier = modifier.WithLeadingTrivia(trivia); - modifiers = modifiers.ReplaceAt(index, firstModifier.WithoutLeadingTrivia()); + modifiers = modifiers.ReplaceAt(index, firstModifier.WithoutLeadingTrivia()); + } } - } - return modifiers.Insert(index, modifier); + return modifiers.Insert(index, modifier); + } } } diff --git a/src/CSharp/CSharp/ModifierList`1.cs b/src/CSharp/CSharp/ModifierList`1.cs index 75d4981f5d..e8f38529a5 100644 --- a/src/CSharp/CSharp/ModifierList`1.cs +++ b/src/CSharp/CSharp/ModifierList`1.cs @@ -8,771 +8,772 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Roslynator.CSharp; - -/// -/// Represents a list of modifiers. -/// -/// -[SuppressMessage("Usage", "RCS1223:Use DebuggerDisplay attribute for publicly visible type.")] -public abstract class ModifierList where TNode : SyntaxNode +namespace Roslynator.CSharp { - internal ModifierList() + /// + /// Represents a list of modifiers. + /// + /// + [SuppressMessage("Usage", "RCS1223:Use DebuggerDisplay attribute for publicly visible type.")] + public abstract class ModifierList where TNode : SyntaxNode { - } + internal ModifierList() + { + } - internal abstract SyntaxList GetAttributeLists(TNode node); + internal abstract SyntaxList GetAttributeLists(TNode node); - internal abstract SyntaxTokenList GetModifiers(TNode node); + internal abstract SyntaxTokenList GetModifiers(TNode node); - internal abstract TNode WithModifiers(TNode node, SyntaxTokenList modifiers); + internal abstract TNode WithModifiers(TNode node, SyntaxTokenList modifiers); - /// - /// Gets an instance of the for a syntax specified by the generic argument. - /// - public static ModifierList Instance { get; } = (ModifierList)GetInstance(); + /// + /// Gets an instance of the for a syntax specified by the generic argument. + /// + public static ModifierList Instance { get; } = (ModifierList)GetInstance(); - private static object GetInstance() - { - if (typeof(TNode) == typeof(ClassDeclarationSyntax)) - return new ClassDeclarationModifierList(); - - if (typeof(TNode) == typeof(ConstructorDeclarationSyntax)) - return new ConstructorDeclarationModifierList(); + private static object GetInstance() + { + if (typeof(TNode) == typeof(ClassDeclarationSyntax)) + return new ClassDeclarationModifierList(); - if (typeof(TNode) == typeof(ConversionOperatorDeclarationSyntax)) - return new ConversionOperatorDeclarationModifierList(); + if (typeof(TNode) == typeof(ConstructorDeclarationSyntax)) + return new ConstructorDeclarationModifierList(); - if (typeof(TNode) == typeof(DelegateDeclarationSyntax)) - return new DelegateDeclarationModifierList(); + if (typeof(TNode) == typeof(ConversionOperatorDeclarationSyntax)) + return new ConversionOperatorDeclarationModifierList(); - if (typeof(TNode) == typeof(DestructorDeclarationSyntax)) - return new DestructorDeclarationModifierList(); + if (typeof(TNode) == typeof(DelegateDeclarationSyntax)) + return new DelegateDeclarationModifierList(); - if (typeof(TNode) == typeof(EnumDeclarationSyntax)) - return new EnumDeclarationModifierList(); + if (typeof(TNode) == typeof(DestructorDeclarationSyntax)) + return new DestructorDeclarationModifierList(); - if (typeof(TNode) == typeof(EventDeclarationSyntax)) - return new EventDeclarationModifierList(); + if (typeof(TNode) == typeof(EnumDeclarationSyntax)) + return new EnumDeclarationModifierList(); - if (typeof(TNode) == typeof(EventFieldDeclarationSyntax)) - return new EventFieldDeclarationModifierList(); + if (typeof(TNode) == typeof(EventDeclarationSyntax)) + return new EventDeclarationModifierList(); - if (typeof(TNode) == typeof(FieldDeclarationSyntax)) - return new FieldDeclarationModifierList(); + if (typeof(TNode) == typeof(EventFieldDeclarationSyntax)) + return new EventFieldDeclarationModifierList(); - if (typeof(TNode) == typeof(IndexerDeclarationSyntax)) - return new IndexerDeclarationModifierList(); + if (typeof(TNode) == typeof(FieldDeclarationSyntax)) + return new FieldDeclarationModifierList(); - if (typeof(TNode) == typeof(InterfaceDeclarationSyntax)) - return new InterfaceDeclarationModifierList(); + if (typeof(TNode) == typeof(IndexerDeclarationSyntax)) + return new IndexerDeclarationModifierList(); - if (typeof(TNode) == typeof(MethodDeclarationSyntax)) - return new MethodDeclarationModifierList(); + if (typeof(TNode) == typeof(InterfaceDeclarationSyntax)) + return new InterfaceDeclarationModifierList(); - if (typeof(TNode) == typeof(OperatorDeclarationSyntax)) - return new OperatorDeclarationModifierList(); + if (typeof(TNode) == typeof(MethodDeclarationSyntax)) + return new MethodDeclarationModifierList(); - if (typeof(TNode) == typeof(PropertyDeclarationSyntax)) - return new PropertyDeclarationModifierList(); + if (typeof(TNode) == typeof(OperatorDeclarationSyntax)) + return new OperatorDeclarationModifierList(); - if (typeof(TNode) == typeof(StructDeclarationSyntax)) - return new StructDeclarationModifierList(); + if (typeof(TNode) == typeof(PropertyDeclarationSyntax)) + return new PropertyDeclarationModifierList(); - if (typeof(TNode) == typeof(AccessorDeclarationSyntax)) - return new AccessorDeclarationModifierList(); + if (typeof(TNode) == typeof(StructDeclarationSyntax)) + return new StructDeclarationModifierList(); - if (typeof(TNode) == typeof(LocalDeclarationStatementSyntax)) - return new LocalDeclarationStatementModifierList(); + if (typeof(TNode) == typeof(AccessorDeclarationSyntax)) + return new AccessorDeclarationModifierList(); - if (typeof(TNode) == typeof(LocalFunctionStatementSyntax)) - return new LocalFunctionStatementModifierList(); + if (typeof(TNode) == typeof(LocalDeclarationStatementSyntax)) + return new LocalDeclarationStatementModifierList(); - if (typeof(TNode) == typeof(ParameterSyntax)) - return new ParameterModifierList(); + if (typeof(TNode) == typeof(LocalFunctionStatementSyntax)) + return new LocalFunctionStatementModifierList(); - if (typeof(TNode) == typeof(IncompleteMemberSyntax)) - return new IncompleteMemberModifierList(); + if (typeof(TNode) == typeof(ParameterSyntax)) + return new ParameterModifierList(); - if (typeof(TNode) == typeof(RecordDeclarationSyntax)) - return new RecordDeclarationModifierList(); + if (typeof(TNode) == typeof(IncompleteMemberSyntax)) + return new IncompleteMemberModifierList(); - throw new InvalidOperationException(); - } + if (typeof(TNode) == typeof(RecordDeclarationSyntax)) + return new RecordDeclarationModifierList(); - /// - /// Creates a new node with a modifier of the specified kind inserted. - /// - /// - /// - /// - public TNode Insert(TNode node, SyntaxKind kind, IComparer comparer = null) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + throw new InvalidOperationException(); + } - SyntaxTokenList modifiers = GetModifiers(node); + /// + /// Creates a new node with a modifier of the specified kind inserted. + /// + /// + /// + /// + public TNode Insert(TNode node, SyntaxKind kind, IComparer comparer = null) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - int index = ModifierList.GetInsertIndex(modifiers, kind, comparer); + SyntaxTokenList modifiers = GetModifiers(node); - return InsertModifier(node, modifiers, Token(kind), index); - } + int index = ModifierList.GetInsertIndex(modifiers, kind, comparer); - /// - /// Creates a new node with the specified modifier inserted. - /// - /// - /// - /// - public TNode Insert(TNode node, SyntaxToken modifier, IComparer comparer = null) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + return InsertModifier(node, modifiers, Token(kind), index); + } - SyntaxTokenList modifiers = GetModifiers(node); + /// + /// Creates a new node with the specified modifier inserted. + /// + /// + /// + /// + public TNode Insert(TNode node, SyntaxToken modifier, IComparer comparer = null) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - int index = ModifierList.GetInsertIndex(modifiers, modifier, comparer); + SyntaxTokenList modifiers = GetModifiers(node); - return InsertModifier(node, modifiers, modifier, index); - } + int index = ModifierList.GetInsertIndex(modifiers, modifier, comparer); - private TNode InsertModifier(TNode node, SyntaxTokenList modifiers, SyntaxToken modifier, int index) - { - SyntaxToken token; + return InsertModifier(node, modifiers, modifier, index); + } - if (!modifiers.Any() - || index == modifiers.Count) + private TNode InsertModifier(TNode node, SyntaxTokenList modifiers, SyntaxToken modifier, int index) { - if (modifiers.Any()) - { - token = modifiers.Last().GetNextToken(); - } - else - { - AttributeListSyntax attributeList = GetAttributeLists(node).LastOrDefault(); + SyntaxToken token; - if (attributeList != null) + if (!modifiers.Any() + || index == modifiers.Count) + { + if (modifiers.Any()) { - token = attributeList.GetLastToken().GetNextToken(); + token = modifiers.Last().GetNextToken(); } else { - token = node.GetFirstToken(); + AttributeListSyntax attributeList = GetAttributeLists(node).LastOrDefault(); + + if (attributeList is not null) + { + token = attributeList.GetLastToken().GetNextToken(); + } + else + { + token = node.GetFirstToken(); + } } } - } - else - { - token = modifiers[index]; - } - - if (token != default) - { - SyntaxTriviaList newLeadingTrivia = token.LeadingTrivia; + else + { + token = modifiers[index]; + } - if (newLeadingTrivia.Any()) + if (token != default) { - SyntaxTriviaList leadingTrivia = modifier.LeadingTrivia; + SyntaxTriviaList newLeadingTrivia = token.LeadingTrivia; - if (!leadingTrivia.IsSingleElasticMarker()) - newLeadingTrivia = newLeadingTrivia.AddRange(leadingTrivia); + if (newLeadingTrivia.Any()) + { + SyntaxTriviaList leadingTrivia = modifier.LeadingTrivia; - modifier = modifier.WithLeadingTrivia(newLeadingTrivia); + if (!leadingTrivia.IsSingleElasticMarker()) + newLeadingTrivia = newLeadingTrivia.AddRange(leadingTrivia); - SyntaxToken newToken = token.WithoutLeadingTrivia(); + modifier = modifier.WithLeadingTrivia(newLeadingTrivia); - if (!modifiers.Any() - || index == modifiers.Count) - { - node = node.ReplaceToken(token, newToken); - } - else - { - modifiers = modifiers.ReplaceAt(index, newToken); + SyntaxToken newToken = token.WithoutLeadingTrivia(); + + if (!modifiers.Any() + || index == modifiers.Count) + { + node = node.ReplaceToken(token, newToken); + } + else + { + modifiers = modifiers.ReplaceAt(index, newToken); + } } - } - if (modifier.TrailingTrivia.IsSingleElasticMarker()) - modifier = modifier.WithTrailingTrivia(TriviaList(Space)); - } + if (modifier.TrailingTrivia.IsSingleElasticMarker()) + modifier = modifier.WithTrailingTrivia(TriviaList(Space)); + } - modifiers = modifiers.Insert(index, modifier); + modifiers = modifiers.Insert(index, modifier); - return WithModifiers(node, modifiers); - } + return WithModifiers(node, modifiers); + } - /// - /// Creates a new node with a modifier of the specified kind removed. - /// - /// - /// - public TNode Remove(TNode node, SyntaxKind kind) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + /// + /// Creates a new node with a modifier of the specified kind removed. + /// + /// + /// + public TNode Remove(TNode node, SyntaxKind kind) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - SyntaxTokenList modifiers = GetModifiers(node); + SyntaxTokenList modifiers = GetModifiers(node); - int i = modifiers.IndexOf(kind); + int i = modifiers.IndexOf(kind); - if (i != -1) - { - return Remove(node, modifiers, modifiers[i], i); - } - else - { - return node; + if (i != -1) + { + return Remove(node, modifiers, modifiers[i], i); + } + else + { + return node; + } } - } - /// - /// Creates a new node with the specified modifier removed. - /// - /// - /// - public TNode Remove(TNode node, SyntaxToken modifier) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + /// + /// Creates a new node with the specified modifier removed. + /// + /// + /// + public TNode Remove(TNode node, SyntaxToken modifier) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - SyntaxTokenList modifiers = GetModifiers(node); + SyntaxTokenList modifiers = GetModifiers(node); - int i = modifiers.IndexOf(modifier); + int i = modifiers.IndexOf(modifier); - if (i != -1) - { - return Remove(node, modifiers, modifier, i); + if (i != -1) + { + return Remove(node, modifiers, modifier, i); + } + else + { + return node; + } } - else + + /// + /// Creates a new node with a modifier at the specified index removed. + /// + /// + /// + public TNode RemoveAt(TNode node, int index) { - return node; + if (node is null) + throw new ArgumentNullException(nameof(node)); + + SyntaxTokenList modifiers = GetModifiers(node); + + return Remove(node, modifiers, modifiers[index], index); } - } - /// - /// Creates a new node with a modifier at the specified index removed. - /// - /// - /// - public TNode RemoveAt(TNode node, int index) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + private TNode Remove( + TNode node, + SyntaxTokenList modifiers, + SyntaxToken modifier, + int index) + { + SyntaxTriviaList leading = modifier.LeadingTrivia; + SyntaxTriviaList trailing = modifier.TrailingTrivia; - SyntaxTokenList modifiers = GetModifiers(node); + if (modifiers.Count == 1) + { + SyntaxToken nextToken = modifier.GetNextToken(); - return Remove(node, modifiers, modifiers[index], index); - } + if (!nextToken.IsKind(SyntaxKind.None)) + { + SyntaxTriviaList trivia = AddIfNotEmptyOrWhitespace(leading, trailing, nextToken.LeadingTrivia); - private TNode Remove( - TNode node, - SyntaxTokenList modifiers, - SyntaxToken modifier, - int index) - { - SyntaxTriviaList leading = modifier.LeadingTrivia; - SyntaxTriviaList trailing = modifier.TrailingTrivia; + node = node.ReplaceToken(nextToken, nextToken.WithLeadingTrivia(trivia)); + } + else + { + SyntaxToken previousToken = modifier.GetPreviousToken(); - if (modifiers.Count == 1) - { - SyntaxToken nextToken = modifier.GetNextToken(); + if (!previousToken.IsKind(SyntaxKind.None)) + { + SyntaxTriviaList trivia = AddIfNotEmptyOrWhitespace(previousToken.TrailingTrivia, leading, trailing); - if (!nextToken.IsKind(SyntaxKind.None)) + node = node.ReplaceToken(previousToken, previousToken.WithTrailingTrivia(trivia)); + } + } + } + else if (index == 0) { - SyntaxTriviaList trivia = AddIfNotEmptyOrWhitespace(leading, trailing, nextToken.LeadingTrivia); + SyntaxToken nextModifier = modifiers[index + 1]; - node = node.ReplaceToken(nextToken, nextToken.WithLeadingTrivia(trivia)); + SyntaxTriviaList trivia = AddIfNotEmptyOrWhitespace(leading, trailing, nextModifier.LeadingTrivia); + + modifiers = modifiers.Replace(nextModifier, nextModifier.WithLeadingTrivia(trivia)); } else { - SyntaxToken previousToken = modifier.GetPreviousToken(); + SyntaxToken previousModifier = modifiers[index - 1]; - if (!previousToken.IsKind(SyntaxKind.None)) - { - SyntaxTriviaList trivia = AddIfNotEmptyOrWhitespace(previousToken.TrailingTrivia, leading, trailing); + SyntaxTriviaList trivia = AddIfNotEmptyOrWhitespace(previousModifier.TrailingTrivia, leading, trailing); - node = node.ReplaceToken(previousToken, previousToken.WithTrailingTrivia(trivia)); - } + modifiers = modifiers.Replace(previousModifier, previousModifier.WithTrailingTrivia(trivia)); } - } - else if (index == 0) - { - SyntaxToken nextModifier = modifiers[index + 1]; - SyntaxTriviaList trivia = AddIfNotEmptyOrWhitespace(leading, trailing, nextModifier.LeadingTrivia); + modifiers = modifiers.RemoveAt(index); - modifiers = modifiers.Replace(nextModifier, nextModifier.WithLeadingTrivia(trivia)); + return WithModifiers(node, modifiers); } - else + + private static SyntaxTriviaList AddIfNotEmptyOrWhitespace(SyntaxTriviaList trivia, SyntaxTriviaList triviaToAdd) { - SyntaxToken previousModifier = modifiers[index - 1]; + return (triviaToAdd.IsEmptyOrWhitespace()) ? trivia : trivia.AddRange(triviaToAdd); + } - SyntaxTriviaList trivia = AddIfNotEmptyOrWhitespace(previousModifier.TrailingTrivia, leading, trailing); + private static SyntaxTriviaList AddIfNotEmptyOrWhitespace(SyntaxTriviaList trivia, SyntaxTriviaList triviaToAdd1, SyntaxTriviaList triviaToAdd2) + { + trivia = AddIfNotEmptyOrWhitespace(trivia, triviaToAdd1); - modifiers = modifiers.Replace(previousModifier, previousModifier.WithTrailingTrivia(trivia)); + return AddIfNotEmptyOrWhitespace(trivia, triviaToAdd2); } - modifiers = modifiers.RemoveAt(index); + /// + /// Creates a new node with all modifiers removed. + /// + /// + public TNode RemoveAll(TNode node) + { + SyntaxTokenList modifiers = GetModifiers(node); - return WithModifiers(node, modifiers); - } + if (!modifiers.Any()) + return node; - private static SyntaxTriviaList AddIfNotEmptyOrWhitespace(SyntaxTriviaList trivia, SyntaxTriviaList triviaToAdd) - { - return (triviaToAdd.IsEmptyOrWhitespace()) ? trivia : trivia.AddRange(triviaToAdd); - } + SyntaxToken firstModifier = modifiers[0]; - private static SyntaxTriviaList AddIfNotEmptyOrWhitespace(SyntaxTriviaList trivia, SyntaxTriviaList triviaToAdd1, SyntaxTriviaList triviaToAdd2) - { - trivia = AddIfNotEmptyOrWhitespace(trivia, triviaToAdd1); + if (modifiers.Count == 1) + return Remove(node, firstModifier); - return AddIfNotEmptyOrWhitespace(trivia, triviaToAdd2); - } + SyntaxToken nextToken = modifiers.Last().GetNextToken(); - /// - /// Creates a new node with all modifiers removed. - /// - /// - public TNode RemoveAll(TNode node) - { - SyntaxTokenList modifiers = GetModifiers(node); - - if (!modifiers.Any()) - return node; + if (!nextToken.IsKind(SyntaxKind.None)) + { + SyntaxTriviaList trivia = firstModifier.LeadingTrivia; - SyntaxToken firstModifier = modifiers[0]; + trivia = trivia.AddRange(firstModifier.TrailingTrivia.EmptyIfWhitespace()); - if (modifiers.Count == 1) - return Remove(node, firstModifier); + for (int i = 1; i < modifiers.Count; i++) + trivia = trivia.AddRange(modifiers[i].LeadingAndTrailingTrivia().EmptyIfWhitespace()); - SyntaxToken nextToken = modifiers.Last().GetNextToken(); + trivia = trivia.AddRange(nextToken.LeadingTrivia.EmptyIfWhitespace()); - if (!nextToken.IsKind(SyntaxKind.None)) - { - SyntaxTriviaList trivia = firstModifier.LeadingTrivia; + node = node.ReplaceToken(nextToken, nextToken.WithLeadingTrivia(trivia)); + } + else + { + SyntaxToken previousToken = firstModifier.GetPreviousToken(); - trivia = trivia.AddRange(firstModifier.TrailingTrivia.EmptyIfWhitespace()); + if (!previousToken.IsKind(SyntaxKind.None)) + { + SyntaxTriviaList trivia = firstModifier.LeadingAndTrailingTrivia(); - for (int i = 1; i < modifiers.Count; i++) - trivia = trivia.AddRange(modifiers[i].LeadingAndTrailingTrivia().EmptyIfWhitespace()); + for (int i = 1; i < modifiers.Count; i++) + trivia = trivia.AddRange(modifiers[i].LeadingAndTrailingTrivia().EmptyIfWhitespace()); - trivia = trivia.AddRange(nextToken.LeadingTrivia.EmptyIfWhitespace()); + node = node.ReplaceToken(nextToken, nextToken.AppendToTrailingTrivia(trivia)); + } + } - node = node.ReplaceToken(nextToken, nextToken.WithLeadingTrivia(trivia)); + return WithModifiers(node, default(SyntaxTokenList)); } - else + + /// + /// Creates a new node with modifiers that matches the predicate removed. + /// + /// + /// + public TNode RemoveAll(TNode node, Func predicate) { - SyntaxToken previousToken = firstModifier.GetPreviousToken(); + SyntaxTokenList modifiers = GetModifiers(node); - if (!previousToken.IsKind(SyntaxKind.None)) + for (int i = modifiers.Count - 1; i >= 0; i--) { - SyntaxTriviaList trivia = firstModifier.LeadingAndTrailingTrivia(); - - for (int i = 1; i < modifiers.Count; i++) - trivia = trivia.AddRange(modifiers[i].LeadingAndTrailingTrivia().EmptyIfWhitespace()); + SyntaxToken modifier = modifiers[i]; - node = node.ReplaceToken(nextToken, nextToken.AppendToTrailingTrivia(trivia)); + if (predicate(modifier)) + node = Remove(node, modifiers, modifier, i); } - } - - return WithModifiers(node, default(SyntaxTokenList)); - } - - /// - /// Creates a new node with modifiers that matches the predicate removed. - /// - /// - /// - public TNode RemoveAll(TNode node, Func predicate) - { - SyntaxTokenList modifiers = GetModifiers(node); - - for (int i = modifiers.Count - 1; i >= 0; i--) - { - SyntaxToken modifier = modifiers[i]; - if (predicate(modifier)) - node = Remove(node, modifiers, modifier, i); + return node; } - return node; - } - - private class AccessorDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(AccessorDeclarationSyntax node) + private class AccessorDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(AccessorDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(AccessorDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(AccessorDeclarationSyntax node) + { + return node.Modifiers; + } - internal override AccessorDeclarationSyntax WithModifiers(AccessorDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override AccessorDeclarationSyntax WithModifiers(AccessorDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class ClassDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(ClassDeclarationSyntax node) + private class ClassDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(ClassDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(ClassDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(ClassDeclarationSyntax node) + { + return node.Modifiers; + } - internal override ClassDeclarationSyntax WithModifiers(ClassDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override ClassDeclarationSyntax WithModifiers(ClassDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class ConstructorDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(ConstructorDeclarationSyntax node) + private class ConstructorDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(ConstructorDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(ConstructorDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(ConstructorDeclarationSyntax node) + { + return node.Modifiers; + } - internal override ConstructorDeclarationSyntax WithModifiers(ConstructorDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override ConstructorDeclarationSyntax WithModifiers(ConstructorDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class ConversionOperatorDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(ConversionOperatorDeclarationSyntax node) + private class ConversionOperatorDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(ConversionOperatorDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(ConversionOperatorDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(ConversionOperatorDeclarationSyntax node) + { + return node.Modifiers; + } - internal override ConversionOperatorDeclarationSyntax WithModifiers(ConversionOperatorDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override ConversionOperatorDeclarationSyntax WithModifiers(ConversionOperatorDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class DelegateDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(DelegateDeclarationSyntax node) + private class DelegateDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(DelegateDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(DelegateDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(DelegateDeclarationSyntax node) + { + return node.Modifiers; + } - internal override DelegateDeclarationSyntax WithModifiers(DelegateDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override DelegateDeclarationSyntax WithModifiers(DelegateDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class DestructorDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(DestructorDeclarationSyntax node) + private class DestructorDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(DestructorDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(DestructorDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(DestructorDeclarationSyntax node) + { + return node.Modifiers; + } - internal override DestructorDeclarationSyntax WithModifiers(DestructorDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override DestructorDeclarationSyntax WithModifiers(DestructorDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class EnumDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(EnumDeclarationSyntax node) + private class EnumDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(EnumDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(EnumDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(EnumDeclarationSyntax node) + { + return node.Modifiers; + } - internal override EnumDeclarationSyntax WithModifiers(EnumDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override EnumDeclarationSyntax WithModifiers(EnumDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class EventDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(EventDeclarationSyntax node) + private class EventDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(EventDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(EventDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(EventDeclarationSyntax node) + { + return node.Modifiers; + } - internal override EventDeclarationSyntax WithModifiers(EventDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override EventDeclarationSyntax WithModifiers(EventDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class EventFieldDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(EventFieldDeclarationSyntax node) + private class EventFieldDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(EventFieldDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(EventFieldDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(EventFieldDeclarationSyntax node) + { + return node.Modifiers; + } - internal override EventFieldDeclarationSyntax WithModifiers(EventFieldDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override EventFieldDeclarationSyntax WithModifiers(EventFieldDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class FieldDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(FieldDeclarationSyntax node) + private class FieldDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(FieldDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(FieldDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(FieldDeclarationSyntax node) + { + return node.Modifiers; + } - internal override FieldDeclarationSyntax WithModifiers(FieldDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override FieldDeclarationSyntax WithModifiers(FieldDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class IncompleteMemberModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(IncompleteMemberSyntax node) + private class IncompleteMemberModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(IncompleteMemberSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(IncompleteMemberSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(IncompleteMemberSyntax node) + { + return node.Modifiers; + } - internal override IncompleteMemberSyntax WithModifiers(IncompleteMemberSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override IncompleteMemberSyntax WithModifiers(IncompleteMemberSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class IndexerDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(IndexerDeclarationSyntax node) + private class IndexerDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(IndexerDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(IndexerDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(IndexerDeclarationSyntax node) + { + return node.Modifiers; + } - internal override IndexerDeclarationSyntax WithModifiers(IndexerDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override IndexerDeclarationSyntax WithModifiers(IndexerDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class InterfaceDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(InterfaceDeclarationSyntax node) + private class InterfaceDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(InterfaceDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(InterfaceDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(InterfaceDeclarationSyntax node) + { + return node.Modifiers; + } - internal override InterfaceDeclarationSyntax WithModifiers(InterfaceDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override InterfaceDeclarationSyntax WithModifiers(InterfaceDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class LocalDeclarationStatementModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(LocalDeclarationStatementSyntax node) + private class LocalDeclarationStatementModifierList : ModifierList { - return default; - } + internal override SyntaxList GetAttributeLists(LocalDeclarationStatementSyntax node) + { + return default; + } - internal override SyntaxTokenList GetModifiers(LocalDeclarationStatementSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(LocalDeclarationStatementSyntax node) + { + return node.Modifiers; + } - internal override LocalDeclarationStatementSyntax WithModifiers(LocalDeclarationStatementSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override LocalDeclarationStatementSyntax WithModifiers(LocalDeclarationStatementSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class LocalFunctionStatementModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(LocalFunctionStatementSyntax node) + private class LocalFunctionStatementModifierList : ModifierList { - return default; - } + internal override SyntaxList GetAttributeLists(LocalFunctionStatementSyntax node) + { + return default; + } - internal override SyntaxTokenList GetModifiers(LocalFunctionStatementSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(LocalFunctionStatementSyntax node) + { + return node.Modifiers; + } - internal override LocalFunctionStatementSyntax WithModifiers(LocalFunctionStatementSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override LocalFunctionStatementSyntax WithModifiers(LocalFunctionStatementSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class MethodDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(MethodDeclarationSyntax node) + private class MethodDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(MethodDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(MethodDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(MethodDeclarationSyntax node) + { + return node.Modifiers; + } - internal override MethodDeclarationSyntax WithModifiers(MethodDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override MethodDeclarationSyntax WithModifiers(MethodDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class OperatorDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(OperatorDeclarationSyntax node) + private class OperatorDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(OperatorDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(OperatorDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(OperatorDeclarationSyntax node) + { + return node.Modifiers; + } - internal override OperatorDeclarationSyntax WithModifiers(OperatorDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override OperatorDeclarationSyntax WithModifiers(OperatorDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class ParameterModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(ParameterSyntax node) + private class ParameterModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(ParameterSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(ParameterSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(ParameterSyntax node) + { + return node.Modifiers; + } - internal override ParameterSyntax WithModifiers(ParameterSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override ParameterSyntax WithModifiers(ParameterSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class PropertyDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(PropertyDeclarationSyntax node) + private class PropertyDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(PropertyDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(PropertyDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(PropertyDeclarationSyntax node) + { + return node.Modifiers; + } - internal override PropertyDeclarationSyntax WithModifiers(PropertyDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override PropertyDeclarationSyntax WithModifiers(PropertyDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class StructDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(StructDeclarationSyntax node) + private class StructDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(StructDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(StructDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(StructDeclarationSyntax node) + { + return node.Modifiers; + } - internal override StructDeclarationSyntax WithModifiers(StructDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override StructDeclarationSyntax WithModifiers(StructDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } - } - private class RecordDeclarationModifierList : ModifierList - { - internal override SyntaxList GetAttributeLists(RecordDeclarationSyntax node) + private class RecordDeclarationModifierList : ModifierList { - return node.AttributeLists; - } + internal override SyntaxList GetAttributeLists(RecordDeclarationSyntax node) + { + return node.AttributeLists; + } - internal override SyntaxTokenList GetModifiers(RecordDeclarationSyntax node) - { - return node.Modifiers; - } + internal override SyntaxTokenList GetModifiers(RecordDeclarationSyntax node) + { + return node.Modifiers; + } - internal override RecordDeclarationSyntax WithModifiers(RecordDeclarationSyntax node, SyntaxTokenList modifiers) - { - return node.WithModifiers(modifiers); + internal override RecordDeclarationSyntax WithModifiers(RecordDeclarationSyntax node, SyntaxTokenList modifiers) + { + return node.WithModifiers(modifiers); + } } } } diff --git a/src/CSharp/CSharp/StatementListSelection.cs b/src/CSharp/CSharp/StatementListSelection.cs index 536b2dc32a..3da987d4fd 100644 --- a/src/CSharp/CSharp/StatementListSelection.cs +++ b/src/CSharp/CSharp/StatementListSelection.cs @@ -30,7 +30,7 @@ private StatementListSelection(SyntaxList statements, TextSpan /// public static StatementListSelection Create(BlockSyntax block, TextSpan span) { - if (block == null) + if (block is null) throw new ArgumentNullException(nameof(block)); return CreateImpl(block.Statements, span); @@ -43,7 +43,7 @@ public static StatementListSelection Create(BlockSyntax block, TextSpan span) /// public static StatementListSelection Create(SwitchSectionSyntax switchSection, TextSpan span) { - if (switchSection == null) + if (switchSection is null) throw new ArgumentNullException(nameof(switchSection)); return CreateImpl(switchSection.Statements, span); @@ -79,24 +79,24 @@ private static StatementListSelection CreateImpl(SyntaxList sta public static bool TryCreate(BlockSyntax block, TextSpan span, out StatementListSelection selectedStatements) { selectedStatements = Create(block, span, 1, int.MaxValue); - return selectedStatements != null; + return selectedStatements is not null; } internal static bool TryCreate(BlockSyntax block, TextSpan span, int minCount, out StatementListSelection selectedStatements) { selectedStatements = Create(block, span, minCount, int.MaxValue); - return selectedStatements != null; + return selectedStatements is not null; } internal static bool TryCreate(BlockSyntax block, TextSpan span, int minCount, int maxCount, out StatementListSelection selectedStatements) { selectedStatements = Create(block, span, minCount, maxCount); - return selectedStatements != null; + return selectedStatements is not null; } private static StatementListSelection Create(BlockSyntax block, TextSpan span, int minCount, int maxCount) { - if (block == null) + if (block is null) return null; return Create(block.Statements, span, minCount, maxCount); @@ -112,24 +112,24 @@ private static StatementListSelection Create(BlockSyntax block, TextSpan span, i public static bool TryCreate(SwitchSectionSyntax switchSection, TextSpan span, out StatementListSelection selectedStatements) { selectedStatements = Create(switchSection, span, 1, int.MaxValue); - return selectedStatements != null; + return selectedStatements is not null; } internal static bool TryCreate(SwitchSectionSyntax switchSection, TextSpan span, int minCount, out StatementListSelection selectedStatements) { selectedStatements = Create(switchSection, span, minCount, int.MaxValue); - return selectedStatements != null; + return selectedStatements is not null; } internal static bool TryCreate(SwitchSectionSyntax switchSection, TextSpan span, int minCount, int maxCount, out StatementListSelection selectedStatements) { selectedStatements = Create(switchSection, span, minCount, maxCount); - return selectedStatements != null; + return selectedStatements is not null; } private static StatementListSelection Create(SwitchSectionSyntax switchSection, TextSpan span, int minCount, int maxCount) { - if (switchSection == null) + if (switchSection is null) return null; return Create(switchSection.Statements, span, minCount, maxCount); diff --git a/src/CSharp/CSharp/StringLiteralParser.cs b/src/CSharp/CSharp/StringLiteralParser.cs index 20c370e2ab..ed2edccd25 100644 --- a/src/CSharp/CSharp/StringLiteralParser.cs +++ b/src/CSharp/CSharp/StringLiteralParser.cs @@ -236,7 +236,7 @@ public static string Parse(string text, int start, int length, bool isVerbatim, (sb ??= StringBuilderCache.GetInstance(text.Length)).Append(ch); } - return new StringLiteralParserResult((sb != null) + return new StringLiteralParserResult((sb is not null) ? StringBuilderCache.GetStringAndFree(sb) : text.Substring(start, length)); } @@ -288,7 +288,7 @@ public static string Parse(string text, int start, int length, bool isVerbatim, (sb ??= StringBuilderCache.GetInstance(text.Length)).Append(ch); } - return new StringLiteralParserResult((sb != null) + return new StringLiteralParserResult((sb is not null) ? StringBuilderCache.GetStringAndFree(sb) : text.Substring(start, length)); } diff --git a/src/CSharp/CSharp/StringLiteralTextBuilder.cs b/src/CSharp/CSharp/StringLiteralTextBuilder.cs index b0c9d93dd5..b371972454 100644 --- a/src/CSharp/CSharp/StringLiteralTextBuilder.cs +++ b/src/CSharp/CSharp/StringLiteralTextBuilder.cs @@ -28,7 +28,7 @@ public StringLiteralTextBuilder(StringBuilder stringBuilder = null, bool isVerba public void Append(InterpolatedStringExpressionSyntax interpolatedString) { - if (interpolatedString == null) + if (interpolatedString is null) return; if (!IsInterpolated) @@ -68,7 +68,7 @@ public void Append(InterpolatedStringExpressionSyntax interpolatedString) public void Append(LiteralExpressionSyntax stringLiteral) { - if (stringLiteral == null) + if (stringLiteral is null) return; if (!stringLiteral.IsKind(SyntaxKind.StringLiteralExpression)) diff --git a/src/CSharp/CSharp/Syntax/AsExpressionInfo.cs b/src/CSharp/CSharp/Syntax/AsExpressionInfo.cs index 59087afa33..e12075e65f 100644 --- a/src/CSharp/CSharp/Syntax/AsExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/AsExpressionInfo.cs @@ -52,7 +52,7 @@ public SyntaxToken OperatorToken /// public bool Success { - get { return Expression != null; } + get { return Expression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] diff --git a/src/CSharp/CSharp/Syntax/AssignmentExpressionInfo.cs b/src/CSharp/CSharp/Syntax/AssignmentExpressionInfo.cs index d93dae070d..cd5729031c 100644 --- a/src/CSharp/CSharp/Syntax/AssignmentExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/AssignmentExpressionInfo.cs @@ -60,7 +60,7 @@ public SyntaxKind Kind /// public bool Success { - get { return AssignmentExpression != null; } + get { return AssignmentExpression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -82,17 +82,17 @@ private string DebuggerDisplay bool walkDownParentheses = true, bool allowMissing = false) { - if (assignmentExpression == null) + if (assignmentExpression is null) return default; ExpressionSyntax left = WalkAndCheck(assignmentExpression.Left, walkDownParentheses, allowMissing); - if (left == null) + if (left is null) return default; ExpressionSyntax right = WalkAndCheck(assignmentExpression.Right, walkDownParentheses, allowMissing); - if (right == null) + if (right is null) return default; return new AssignmentExpressionInfo(assignmentExpression, left, right); diff --git a/src/CSharp/CSharp/Syntax/BinaryExpressionInfo.cs b/src/CSharp/CSharp/Syntax/BinaryExpressionInfo.cs index a1d70148c5..5b6827f606 100644 --- a/src/CSharp/CSharp/Syntax/BinaryExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/BinaryExpressionInfo.cs @@ -60,7 +60,7 @@ public SyntaxKind Kind /// public bool Success { - get { return BinaryExpression != null; } + get { return BinaryExpression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -101,7 +101,7 @@ public ExpressionChain AsChain() bool walkDownParentheses = true, bool allowMissing = false) { - if (binaryExpression == null) + if (binaryExpression is null) return default; ExpressionSyntax left = Walk(binaryExpression.Left, walkDownParentheses); diff --git a/src/CSharp/CSharp/Syntax/ConditionalExpressionInfo.cs b/src/CSharp/CSharp/Syntax/ConditionalExpressionInfo.cs index 370565197e..fa1055d265 100644 --- a/src/CSharp/CSharp/Syntax/ConditionalExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/ConditionalExpressionInfo.cs @@ -67,7 +67,7 @@ public SyntaxToken ColonToken /// public bool Success { - get { return Condition != null; } + get { return Condition is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -81,22 +81,22 @@ private string DebuggerDisplay bool walkDownParentheses = true, bool allowMissing = false) { - if (conditionalExpression == null) + if (conditionalExpression is null) return default; ExpressionSyntax condition = WalkAndCheck(conditionalExpression.Condition, walkDownParentheses, allowMissing); - if (condition == null) + if (condition is null) return default; ExpressionSyntax whenTrue = WalkAndCheck(conditionalExpression.WhenTrue, walkDownParentheses, allowMissing); - if (whenTrue == null) + if (whenTrue is null) return default; ExpressionSyntax whenFalse = WalkAndCheck(conditionalExpression.WhenFalse, walkDownParentheses, allowMissing); - if (whenFalse == null) + if (whenFalse is null) return default; return new ConditionalExpressionInfo(condition, whenTrue, whenFalse); diff --git a/src/CSharp/CSharp/Syntax/ConditionalStatementInfo.cs b/src/CSharp/CSharp/Syntax/ConditionalStatementInfo.cs index 122263d88f..f71f2f1e37 100644 --- a/src/CSharp/CSharp/Syntax/ConditionalStatementInfo.cs +++ b/src/CSharp/CSharp/Syntax/ConditionalStatementInfo.cs @@ -59,7 +59,7 @@ public ElseClauseSyntax Else /// public bool Success { - get { return IfStatement != null; } + get { return IfStatement is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -91,7 +91,7 @@ private string DebuggerDisplay ExpressionSyntax condition = WalkAndCheck(ifStatement.Condition, walkDownParentheses, allowMissing); - if (condition == null) + if (condition is null) return default; return new ConditionalStatementInfo(ifStatement, condition, whenTrue, whenFalse); diff --git a/src/CSharp/CSharp/Syntax/GenericInfo.cs b/src/CSharp/CSharp/Syntax/GenericInfo.cs index 0bbaada9f3..7cc57a6e25 100644 --- a/src/CSharp/CSharp/Syntax/GenericInfo.cs +++ b/src/CSharp/CSharp/Syntax/GenericInfo.cs @@ -110,7 +110,7 @@ public TypeParameterConstraintClauseSyntax FindConstraintClause(string typeParam /// public bool Success { - get { return Node != null; } + get { return Node is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -126,7 +126,7 @@ private string DebuggerDisplay internal static GenericInfo Create(SyntaxNode node) { - if (node == null) + if (node is null) return default; switch (node.Kind()) @@ -193,7 +193,7 @@ internal static GenericInfo Create(TypeParameterListSyntax typeParameterList) internal static GenericInfo Create(TypeDeclarationSyntax typeDeclaration) { - if (typeDeclaration == null) + if (typeDeclaration is null) return default; return new GenericInfo(typeDeclaration); @@ -201,7 +201,7 @@ internal static GenericInfo Create(TypeDeclarationSyntax typeDeclaration) internal static GenericInfo Create(DelegateDeclarationSyntax delegateDeclaration) { - if (delegateDeclaration == null) + if (delegateDeclaration is null) return default; return new GenericInfo(delegateDeclaration); @@ -209,7 +209,7 @@ internal static GenericInfo Create(DelegateDeclarationSyntax delegateDeclaration internal static GenericInfo Create(LocalFunctionStatementSyntax localFunctionStatement) { - if (localFunctionStatement == null) + if (localFunctionStatement is null) return default; return new GenericInfo(localFunctionStatement); @@ -217,7 +217,7 @@ internal static GenericInfo Create(LocalFunctionStatementSyntax localFunctionSta internal static GenericInfo Create(MethodDeclarationSyntax methodDeclaration) { - if (methodDeclaration == null) + if (methodDeclaration is null) return default; return new GenericInfo(methodDeclaration); @@ -382,7 +382,7 @@ public GenericInfo RemoveAllConstraintClauses() private void ThrowInvalidOperationIfNotInitialized() { - if (Node == null) + if (Node is null) throw new InvalidOperationException($"{nameof(GenericInfo)} is not initalized."); } } diff --git a/src/CSharp/CSharp/Syntax/HexNumericLiteralExpressionInfo.cs b/src/CSharp/CSharp/Syntax/HexNumericLiteralExpressionInfo.cs index f753784ebd..fc3304a984 100644 --- a/src/CSharp/CSharp/Syntax/HexNumericLiteralExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/HexNumericLiteralExpressionInfo.cs @@ -65,7 +65,7 @@ public HexNumericLiteralSuffixKind GetSuffixKind() { string suffix = GetSuffix(); - if (suffix == null) + if (suffix is null) return HexNumericLiteralSuffixKind.None; if (string.Equals(GetSuffix(), "u", StringComparison.OrdinalIgnoreCase)) @@ -85,7 +85,7 @@ public HexNumericLiteralSuffixKind GetSuffixKind() public bool Success { - get { return LiteralExpression != null; } + get { return LiteralExpression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -101,7 +101,7 @@ internal static HexNumericLiteralExpressionInfo Create(SyntaxNode node, bool wal internal static HexNumericLiteralExpressionInfo Create(LiteralExpressionSyntax literalExpression) { - if (literalExpression == null) + if (literalExpression is null) return default; if (!literalExpression.IsKind(SyntaxKind.NumericLiteralExpression)) diff --git a/src/CSharp/CSharp/Syntax/IsExpressionInfo.cs b/src/CSharp/CSharp/Syntax/IsExpressionInfo.cs index a7b7411633..3464b60205 100644 --- a/src/CSharp/CSharp/Syntax/IsExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/IsExpressionInfo.cs @@ -52,7 +52,7 @@ public SyntaxToken OperatorToken /// public bool Success { - get { return Expression != null; } + get { return Expression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] diff --git a/src/CSharp/CSharp/Syntax/LocalDeclarationStatementInfo.cs b/src/CSharp/CSharp/Syntax/LocalDeclarationStatementInfo.cs index 41104175fc..9bd6779cc2 100644 --- a/src/CSharp/CSharp/Syntax/LocalDeclarationStatementInfo.cs +++ b/src/CSharp/CSharp/Syntax/LocalDeclarationStatementInfo.cs @@ -69,7 +69,7 @@ public SyntaxToken SemicolonToken /// public bool Success { - get { return Statement != null; } + get { return Statement is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] diff --git a/src/CSharp/CSharp/Syntax/MemberDeclarationListInfo.cs b/src/CSharp/CSharp/Syntax/MemberDeclarationListInfo.cs index 0858ebc444..60a72022a6 100644 --- a/src/CSharp/CSharp/Syntax/MemberDeclarationListInfo.cs +++ b/src/CSharp/CSharp/Syntax/MemberDeclarationListInfo.cs @@ -38,7 +38,7 @@ internal MemberDeclarationListInfo(SyntaxNode parent, SyntaxList public bool Success { - get { return Parent != null; } + get { return Parent is not null; } } /// @@ -117,7 +117,7 @@ public SyntaxList.Enumerator GetEnumerator() internal static MemberDeclarationListInfo Create(CompilationUnitSyntax compilationUnit) { - if (compilationUnit == null) + if (compilationUnit is null) return default; return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); @@ -125,7 +125,7 @@ internal static MemberDeclarationListInfo Create(CompilationUnitSyntax compilati internal static MemberDeclarationListInfo Create(NamespaceDeclarationSyntax namespaceDeclaration) { - if (namespaceDeclaration == null) + if (namespaceDeclaration is null) return default; return new MemberDeclarationListInfo(namespaceDeclaration, namespaceDeclaration.Members); @@ -133,7 +133,7 @@ internal static MemberDeclarationListInfo Create(NamespaceDeclarationSyntax name internal static MemberDeclarationListInfo Create(BaseNamespaceDeclarationSyntax namespaceDeclaration) { - if (namespaceDeclaration == null) + if (namespaceDeclaration is null) return default; return new MemberDeclarationListInfo(namespaceDeclaration, namespaceDeclaration.Members); @@ -141,7 +141,7 @@ internal static MemberDeclarationListInfo Create(BaseNamespaceDeclarationSyntax internal static MemberDeclarationListInfo Create(TypeDeclarationSyntax typeDeclaration) { - if (typeDeclaration == null) + if (typeDeclaration is null) return default; return new MemberDeclarationListInfo(typeDeclaration, typeDeclaration.Members); @@ -149,7 +149,7 @@ internal static MemberDeclarationListInfo Create(TypeDeclarationSyntax typeDecla internal static MemberDeclarationListInfo Create(ClassDeclarationSyntax classDeclaration) { - if (classDeclaration == null) + if (classDeclaration is null) return default; return new MemberDeclarationListInfo(classDeclaration, classDeclaration.Members); @@ -157,7 +157,7 @@ internal static MemberDeclarationListInfo Create(ClassDeclarationSyntax classDec internal static MemberDeclarationListInfo Create(StructDeclarationSyntax structDeclaration) { - if (structDeclaration == null) + if (structDeclaration is null) return default; return new MemberDeclarationListInfo(structDeclaration, structDeclaration.Members); @@ -165,7 +165,7 @@ internal static MemberDeclarationListInfo Create(StructDeclarationSyntax structD internal static MemberDeclarationListInfo Create(InterfaceDeclarationSyntax interfaceDeclaration) { - if (interfaceDeclaration == null) + if (interfaceDeclaration is null) return default; return new MemberDeclarationListInfo(interfaceDeclaration, interfaceDeclaration.Members); @@ -539,7 +539,7 @@ public MemberDeclarationListInfo ReplaceRange(MemberDeclarationSyntax memberInLi private void ThrowInvalidOperationIfNotInitialized() { - if (Parent == null) + if (Parent is null) throw new InvalidOperationException($"{nameof(MemberDeclarationListInfo)} is not initalized."); } } diff --git a/src/CSharp/CSharp/Syntax/ModifierListInfo.cs b/src/CSharp/CSharp/Syntax/ModifierListInfo.cs index c80a4bbcb1..d47558e9af 100644 --- a/src/CSharp/CSharp/Syntax/ModifierListInfo.cs +++ b/src/CSharp/CSharp/Syntax/ModifierListInfo.cs @@ -129,7 +129,7 @@ public Accessibility ExplicitAccessibility /// public bool Success { - get { return Parent != null; } + get { return Parent is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -145,7 +145,7 @@ private string DebuggerDisplay internal static ModifierListInfo Create(SyntaxNode node) { - if (node == null) + if (node is null) return default; switch (node.Kind()) @@ -204,7 +204,7 @@ internal static ModifierListInfo Create(SyntaxNode node) internal static ModifierListInfo Create(ClassDeclarationSyntax classDeclaration) { - if (classDeclaration == null) + if (classDeclaration is null) return default; return new ModifierListInfo(classDeclaration, classDeclaration.Modifiers); @@ -212,7 +212,7 @@ internal static ModifierListInfo Create(ClassDeclarationSyntax classDeclaration) internal static ModifierListInfo Create(ConstructorDeclarationSyntax constructorDeclaration) { - if (constructorDeclaration == null) + if (constructorDeclaration is null) return default; return new ModifierListInfo(constructorDeclaration, constructorDeclaration.Modifiers); @@ -220,7 +220,7 @@ internal static ModifierListInfo Create(ConstructorDeclarationSyntax constructor internal static ModifierListInfo Create(ConversionOperatorDeclarationSyntax conversionOperatorDeclaration) { - if (conversionOperatorDeclaration == null) + if (conversionOperatorDeclaration is null) return default; return new ModifierListInfo(conversionOperatorDeclaration, conversionOperatorDeclaration.Modifiers); @@ -228,7 +228,7 @@ internal static ModifierListInfo Create(ConversionOperatorDeclarationSyntax conv internal static ModifierListInfo Create(DelegateDeclarationSyntax delegateDeclaration) { - if (delegateDeclaration == null) + if (delegateDeclaration is null) return default; return new ModifierListInfo(delegateDeclaration, delegateDeclaration.Modifiers); @@ -236,7 +236,7 @@ internal static ModifierListInfo Create(DelegateDeclarationSyntax delegateDeclar internal static ModifierListInfo Create(DestructorDeclarationSyntax destructorDeclaration) { - if (destructorDeclaration == null) + if (destructorDeclaration is null) return default; return new ModifierListInfo(destructorDeclaration, destructorDeclaration.Modifiers); @@ -244,7 +244,7 @@ internal static ModifierListInfo Create(DestructorDeclarationSyntax destructorDe internal static ModifierListInfo Create(EnumDeclarationSyntax enumDeclaration) { - if (enumDeclaration == null) + if (enumDeclaration is null) return default; return new ModifierListInfo(enumDeclaration, enumDeclaration.Modifiers); @@ -252,7 +252,7 @@ internal static ModifierListInfo Create(EnumDeclarationSyntax enumDeclaration) internal static ModifierListInfo Create(EventDeclarationSyntax eventDeclaration) { - if (eventDeclaration == null) + if (eventDeclaration is null) return default; return new ModifierListInfo(eventDeclaration, eventDeclaration.Modifiers); @@ -260,7 +260,7 @@ internal static ModifierListInfo Create(EventDeclarationSyntax eventDeclaration) internal static ModifierListInfo Create(EventFieldDeclarationSyntax eventFieldDeclaration) { - if (eventFieldDeclaration == null) + if (eventFieldDeclaration is null) return default; return new ModifierListInfo(eventFieldDeclaration, eventFieldDeclaration.Modifiers); @@ -268,7 +268,7 @@ internal static ModifierListInfo Create(EventFieldDeclarationSyntax eventFieldDe internal static ModifierListInfo Create(FieldDeclarationSyntax fieldDeclaration) { - if (fieldDeclaration == null) + if (fieldDeclaration is null) return default; return new ModifierListInfo(fieldDeclaration, fieldDeclaration.Modifiers); @@ -276,7 +276,7 @@ internal static ModifierListInfo Create(FieldDeclarationSyntax fieldDeclaration) internal static ModifierListInfo Create(IndexerDeclarationSyntax indexerDeclaration) { - if (indexerDeclaration == null) + if (indexerDeclaration is null) return default; return new ModifierListInfo(indexerDeclaration, indexerDeclaration.Modifiers); @@ -284,7 +284,7 @@ internal static ModifierListInfo Create(IndexerDeclarationSyntax indexerDeclarat internal static ModifierListInfo Create(InterfaceDeclarationSyntax interfaceDeclaration) { - if (interfaceDeclaration == null) + if (interfaceDeclaration is null) return default; return new ModifierListInfo(interfaceDeclaration, interfaceDeclaration.Modifiers); @@ -292,7 +292,7 @@ internal static ModifierListInfo Create(InterfaceDeclarationSyntax interfaceDecl internal static ModifierListInfo Create(MethodDeclarationSyntax methodDeclaration) { - if (methodDeclaration == null) + if (methodDeclaration is null) return default; return new ModifierListInfo(methodDeclaration, methodDeclaration.Modifiers); @@ -300,7 +300,7 @@ internal static ModifierListInfo Create(MethodDeclarationSyntax methodDeclaratio internal static ModifierListInfo Create(OperatorDeclarationSyntax operatorDeclaration) { - if (operatorDeclaration == null) + if (operatorDeclaration is null) return default; return new ModifierListInfo(operatorDeclaration, operatorDeclaration.Modifiers); @@ -308,7 +308,7 @@ internal static ModifierListInfo Create(OperatorDeclarationSyntax operatorDeclar internal static ModifierListInfo Create(PropertyDeclarationSyntax propertyDeclaration) { - if (propertyDeclaration == null) + if (propertyDeclaration is null) return default; return new ModifierListInfo(propertyDeclaration, propertyDeclaration.Modifiers); @@ -316,7 +316,7 @@ internal static ModifierListInfo Create(PropertyDeclarationSyntax propertyDeclar internal static ModifierListInfo Create(StructDeclarationSyntax structDeclaration) { - if (structDeclaration == null) + if (structDeclaration is null) return default; return new ModifierListInfo(structDeclaration, structDeclaration.Modifiers); @@ -324,7 +324,7 @@ internal static ModifierListInfo Create(StructDeclarationSyntax structDeclaratio internal static ModifierListInfo Create(IncompleteMemberSyntax incompleteMember) { - if (incompleteMember == null) + if (incompleteMember is null) return default; return new ModifierListInfo(incompleteMember, incompleteMember.Modifiers); @@ -332,7 +332,7 @@ internal static ModifierListInfo Create(IncompleteMemberSyntax incompleteMember) internal static ModifierListInfo Create(AccessorDeclarationSyntax accessorDeclaration) { - if (accessorDeclaration == null) + if (accessorDeclaration is null) return default; return new ModifierListInfo(accessorDeclaration, accessorDeclaration.Modifiers); @@ -340,7 +340,7 @@ internal static ModifierListInfo Create(AccessorDeclarationSyntax accessorDeclar internal static ModifierListInfo Create(LocalDeclarationStatementSyntax localDeclarationStatement) { - if (localDeclarationStatement == null) + if (localDeclarationStatement is null) return default; return new ModifierListInfo(localDeclarationStatement, localDeclarationStatement.Modifiers); @@ -348,7 +348,7 @@ internal static ModifierListInfo Create(LocalDeclarationStatementSyntax localDec internal static ModifierListInfo Create(LocalFunctionStatementSyntax localFunctionStatement) { - if (localFunctionStatement == null) + if (localFunctionStatement is null) return default; return new ModifierListInfo(localFunctionStatement, localFunctionStatement.Modifiers); @@ -356,7 +356,7 @@ internal static ModifierListInfo Create(LocalFunctionStatementSyntax localFuncti internal static ModifierListInfo Create(ParameterSyntax parameter) { - if (parameter == null) + if (parameter is null) return default; return new ModifierListInfo(parameter, parameter.Modifiers); @@ -778,7 +778,7 @@ public ModifierFilter GetFilter() private void ThrowInvalidOperationIfNotInitialized() { - if (Parent == null) + if (Parent is null) throw new InvalidOperationException($"{nameof(ModifierListInfo)} is not initalized."); } } diff --git a/src/CSharp/CSharp/Syntax/NullCheckExpressionInfo.cs b/src/CSharp/CSharp/Syntax/NullCheckExpressionInfo.cs index bfe74c7d4a..f0769eccc7 100644 --- a/src/CSharp/CSharp/Syntax/NullCheckExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/NullCheckExpressionInfo.cs @@ -99,7 +99,7 @@ private string DebuggerDisplay bool allowMissing = false, CancellationToken cancellationToken = default) { - if (semanticModel == null) + if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); return CreateImpl(node, semanticModel, allowedStyles, walkDownParentheses, allowMissing, cancellationToken); @@ -115,7 +115,7 @@ private string DebuggerDisplay { ExpressionSyntax expression = WalkAndCheck(node, walkDownParentheses, allowMissing); - if (expression == null) + if (expression is null) return default; SyntaxKind kind = expression.Kind(); @@ -129,12 +129,12 @@ private string DebuggerDisplay ExpressionSyntax left = WalkAndCheck(binaryExpression.Left, walkDownParentheses, allowMissing); - if (left == null) + if (left is null) break; ExpressionSyntax right = WalkAndCheck(binaryExpression.Right, walkDownParentheses, allowMissing); - if (right == null) + if (right is null) break; NullCheckExpressionInfo info = Create(binaryExpression, kind, left, right, allowedStyles, allowMissing, semanticModel, cancellationToken); @@ -191,7 +191,7 @@ private string DebuggerDisplay ExpressionSyntax e = WalkAndCheck(isPatternExpression.Expression, walkDownParentheses, allowMissing); - if (e == null) + if (e is null) break; return new NullCheckExpressionInfo( @@ -211,7 +211,7 @@ private string DebuggerDisplay ExpressionSyntax operand = WalkAndCheck(logicalNotExpression.Operand, walkDownParentheses, allowMissing); - if (operand == null) + if (operand is null) break; switch (operand.Kind()) @@ -243,7 +243,7 @@ private string DebuggerDisplay ExpressionSyntax e = WalkAndCheck(isPatternExpression.Expression, walkDownParentheses, allowMissing); - if (e == null) + if (e is null) break; return new NullCheckExpressionInfo(expression, e, NullCheckStyles.NotIsNull); @@ -374,7 +374,7 @@ private string DebuggerDisplay } case SyntaxKind.DefaultExpression: { - if (semanticModel == null) + if (semanticModel is null) return false; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(left, cancellationToken); diff --git a/src/CSharp/CSharp/Syntax/ParameterInfo.cs b/src/CSharp/CSharp/Syntax/ParameterInfo.cs index ffd78ebd75..be9cb0fa45 100644 --- a/src/CSharp/CSharp/Syntax/ParameterInfo.cs +++ b/src/CSharp/CSharp/Syntax/ParameterInfo.cs @@ -57,7 +57,7 @@ public SeparatedSyntaxList Parameters public bool Success { - get { return ParameterList != null || Parameter != null; } + get { return ParameterList is not null || Parameter is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] diff --git a/src/CSharp/CSharp/Syntax/RegionInfo.cs b/src/CSharp/CSharp/Syntax/RegionInfo.cs index 03be56636b..d422b9d159 100644 --- a/src/CSharp/CSharp/Syntax/RegionInfo.cs +++ b/src/CSharp/CSharp/Syntax/RegionInfo.cs @@ -36,7 +36,7 @@ private RegionInfo(RegionDirectiveTriviaSyntax directive, EndRegionDirectiveTriv /// public bool Success { - get { return Directive != null; } + get { return Directive is not null; } } /// @@ -133,7 +133,7 @@ internal static RegionInfo Create(SyntaxNode node) internal static RegionInfo Create(RegionDirectiveTriviaSyntax regionDirective) { - if (regionDirective == null) + if (regionDirective is null) return default; List list = regionDirective.GetRelatedDirectives(); @@ -149,7 +149,7 @@ internal static RegionInfo Create(RegionDirectiveTriviaSyntax regionDirective) internal static RegionInfo Create(EndRegionDirectiveTriviaSyntax endRegionDirective) { - if (endRegionDirective == null) + if (endRegionDirective is null) return default; List list = endRegionDirective.GetRelatedDirectives(); diff --git a/src/CSharp/CSharp/Syntax/SimpleAssignmentExpressionInfo.cs b/src/CSharp/CSharp/Syntax/SimpleAssignmentExpressionInfo.cs index 1ff2a4555a..4bc1472bc1 100644 --- a/src/CSharp/CSharp/Syntax/SimpleAssignmentExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/SimpleAssignmentExpressionInfo.cs @@ -52,7 +52,7 @@ public SyntaxToken OperatorToken /// public bool Success { - get { return AssignmentExpression != null; } + get { return AssignmentExpression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -79,12 +79,12 @@ private string DebuggerDisplay ExpressionSyntax left = WalkAndCheck(assignmentExpression.Left, walkDownParentheses, allowMissing); - if (left == null) + if (left is null) return default; ExpressionSyntax right = WalkAndCheck(assignmentExpression.Right, walkDownParentheses, allowMissing); - if (right == null) + if (right is null) return default; return new SimpleAssignmentExpressionInfo(assignmentExpression, left, right); diff --git a/src/CSharp/CSharp/Syntax/SimpleIfStatementInfo.cs b/src/CSharp/CSharp/Syntax/SimpleIfStatementInfo.cs index 495834b2cc..85ecd93f6b 100644 --- a/src/CSharp/CSharp/Syntax/SimpleIfStatementInfo.cs +++ b/src/CSharp/CSharp/Syntax/SimpleIfStatementInfo.cs @@ -44,7 +44,7 @@ namespace Roslynator.CSharp.Syntax; /// public bool Success { - get { return IfStatement != null; } + get { return IfStatement is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -71,7 +71,7 @@ private string DebuggerDisplay ExpressionSyntax condition = WalkAndCheck(ifStatement.Condition, walkDownParentheses, allowMissing); - if (condition == null) + if (condition is null) return default; StatementSyntax statement = ifStatement.Statement; diff --git a/src/CSharp/CSharp/Syntax/SimpleMemberInvocationExpressionInfo.cs b/src/CSharp/CSharp/Syntax/SimpleMemberInvocationExpressionInfo.cs index efadc6a459..906307da2f 100644 --- a/src/CSharp/CSharp/Syntax/SimpleMemberInvocationExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/SimpleMemberInvocationExpressionInfo.cs @@ -85,7 +85,7 @@ public string NameText /// public bool Success { - get { return InvocationExpression != null; } + get { return InvocationExpression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -133,7 +133,7 @@ private string DebuggerDisplay ArgumentListSyntax argumentList = invocationExpression.ArgumentList; - if (argumentList == null) + if (argumentList is null) return default; return new SimpleMemberInvocationExpressionInfo(invocationExpression, memberAccessExpression); diff --git a/src/CSharp/CSharp/Syntax/SingleLocalDeclarationStatementInfo.cs b/src/CSharp/CSharp/Syntax/SingleLocalDeclarationStatementInfo.cs index 1f4d63d5f0..4fe243832c 100644 --- a/src/CSharp/CSharp/Syntax/SingleLocalDeclarationStatementInfo.cs +++ b/src/CSharp/CSharp/Syntax/SingleLocalDeclarationStatementInfo.cs @@ -109,7 +109,7 @@ public SyntaxToken SemicolonToken /// public bool Success { - get { return Statement != null; } + get { return Statement is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] diff --git a/src/CSharp/CSharp/Syntax/SingleParameterLambdaExpressionInfo.cs b/src/CSharp/CSharp/Syntax/SingleParameterLambdaExpressionInfo.cs index eccf68560e..2446d3426e 100644 --- a/src/CSharp/CSharp/Syntax/SingleParameterLambdaExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/SingleParameterLambdaExpressionInfo.cs @@ -68,7 +68,7 @@ public bool IsParenthesizedLambda /// public bool Success { - get { return LambdaExpression != null; } + get { return LambdaExpression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] diff --git a/src/CSharp/CSharp/Syntax/StatementListInfo.cs b/src/CSharp/CSharp/Syntax/StatementListInfo.cs index ffc91dddf8..a6f4c3d720 100644 --- a/src/CSharp/CSharp/Syntax/StatementListInfo.cs +++ b/src/CSharp/CSharp/Syntax/StatementListInfo.cs @@ -19,7 +19,7 @@ namespace Roslynator.CSharp.Syntax; { internal StatementListInfo(BlockSyntax block) { - Debug.Assert(block != null); + Debug.Assert(block is not null); Parent = block; Statements = block.Statements; @@ -27,7 +27,7 @@ internal StatementListInfo(BlockSyntax block) internal StatementListInfo(SwitchSectionSyntax switchSection) { - Debug.Assert(switchSection != null); + Debug.Assert(switchSection is not null); Parent = switchSection; Statements = switchSection.Statements; @@ -88,7 +88,7 @@ public SwitchSectionSyntax ParentAsSwitchSection /// public bool Success { - get { return Parent != null; } + get { return Parent is not null; } } /// @@ -135,7 +135,7 @@ public SyntaxList.Enumerator GetEnumerator() internal static StatementListInfo Create(StatementSyntax statementInList) { - if (statementInList == null) + if (statementInList is null) return default; SyntaxNode parent = statementInList.Parent; @@ -379,7 +379,7 @@ public StatementListInfo ReplaceRange(StatementSyntax statementInList, IEnumerab private void ThrowInvalidOperationIfNotInitialized() { - if (Parent == null) + if (Parent is null) throw new InvalidOperationException($"{nameof(StatementListInfo)} is not initalized."); } } diff --git a/src/CSharp/CSharp/Syntax/StringConcatenationExpressionInfo.cs b/src/CSharp/CSharp/Syntax/StringConcatenationExpressionInfo.cs index 5b231f2a9f..ec711a781d 100644 --- a/src/CSharp/CSharp/Syntax/StringConcatenationExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/StringConcatenationExpressionInfo.cs @@ -45,7 +45,7 @@ public BinaryExpressionSyntax BinaryExpression /// public bool Success { - get { return BinaryExpression != null; } + get { return BinaryExpression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -223,7 +223,7 @@ internal LiteralExpressionSyntax ToMultiLineStringLiteralExpression() private void ThrowInvalidOperationIfNotInitialized() { - if (BinaryExpression == null) + if (BinaryExpression is null) throw new InvalidOperationException($"{nameof(StringConcatenationExpressionInfo)} is not initalized."); } diff --git a/src/CSharp/CSharp/Syntax/StringLiteralExpressionInfo.cs b/src/CSharp/CSharp/Syntax/StringLiteralExpressionInfo.cs index 904dee0882..9a45607095 100644 --- a/src/CSharp/CSharp/Syntax/StringLiteralExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/StringLiteralExpressionInfo.cs @@ -125,7 +125,7 @@ public bool ContainsEscapeSequence /// public bool Success { - get { return Expression != null; } + get { return Expression is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] diff --git a/src/CSharp/CSharp/Syntax/SyntaxInfoHelpers.cs b/src/CSharp/CSharp/Syntax/SyntaxInfoHelpers.cs index be07b475ea..ef07e95d2a 100644 --- a/src/CSharp/CSharp/Syntax/SyntaxInfoHelpers.cs +++ b/src/CSharp/CSharp/Syntax/SyntaxInfoHelpers.cs @@ -35,7 +35,7 @@ private static ExpressionSyntax WalkAndCheck(ExpressionSyntax expression, bool a public static bool Check(SyntaxNode node, bool allowMissing) { - return node != null + return node is not null && (allowMissing || !node.IsMissing); } diff --git a/src/CSharp/CSharp/Syntax/TypeParameterConstraintInfo.cs b/src/CSharp/CSharp/Syntax/TypeParameterConstraintInfo.cs index d2dcba9b8d..baf33b0c00 100644 --- a/src/CSharp/CSharp/Syntax/TypeParameterConstraintInfo.cs +++ b/src/CSharp/CSharp/Syntax/TypeParameterConstraintInfo.cs @@ -61,14 +61,14 @@ public string NameText /// public bool Success { - get { return Constraint != null; } + get { return Constraint is not null; } } internal bool IsDuplicateConstraint { get { - if (Constraint == null) + if (Constraint is null) return false; SeparatedSyntaxList constraints = Constraints; diff --git a/src/CSharp/CSharp/Syntax/UsingDirectiveListInfo.cs b/src/CSharp/CSharp/Syntax/UsingDirectiveListInfo.cs index 6213e94615..3202a59dbc 100644 --- a/src/CSharp/CSharp/Syntax/UsingDirectiveListInfo.cs +++ b/src/CSharp/CSharp/Syntax/UsingDirectiveListInfo.cs @@ -38,7 +38,7 @@ internal UsingDirectiveListInfo(SyntaxNode parent, SyntaxList public bool Success { - get { return Parent != null; } + get { return Parent is not null; } } /// @@ -85,7 +85,7 @@ public SyntaxList.Enumerator GetEnumerator() internal static UsingDirectiveListInfo Create(NamespaceDeclarationSyntax namespaceDeclaration) { - if (namespaceDeclaration == null) + if (namespaceDeclaration is null) return default; return new UsingDirectiveListInfo(namespaceDeclaration, namespaceDeclaration.Usings); @@ -93,7 +93,7 @@ internal static UsingDirectiveListInfo Create(NamespaceDeclarationSyntax namespa internal static UsingDirectiveListInfo Create(CompilationUnitSyntax compilationUnit) { - if (compilationUnit == null) + if (compilationUnit is null) return default; return new UsingDirectiveListInfo(compilationUnit, compilationUnit.Usings); @@ -368,7 +368,7 @@ public UsingDirectiveListInfo ReplaceRange(UsingDirectiveSyntax usingInLine, IEn private void ThrowInvalidOperationIfNotInitialized() { - if (Parent == null) + if (Parent is null) throw new InvalidOperationException($"{nameof(UsingDirectiveListInfo)} is not initalized."); } } diff --git a/src/CSharp/CSharp/Syntax/XmlElementInfo.cs b/src/CSharp/CSharp/Syntax/XmlElementInfo.cs index 30114076a5..dacc039aa8 100644 --- a/src/CSharp/CSharp/Syntax/XmlElementInfo.cs +++ b/src/CSharp/CSharp/Syntax/XmlElementInfo.cs @@ -90,7 +90,7 @@ static bool IsWhitespaceOrNewLine(SyntaxToken token) /// public bool Success { - get { return Element != null; } + get { return Element is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -117,7 +117,7 @@ internal static XmlElementInfo Create(XmlNodeSyntax node) { string localName = element.StartTag?.Name?.LocalName.ValueText; - if (localName == null) + if (localName is null) return default; return new XmlElementInfo(element, localName); @@ -126,7 +126,7 @@ internal static XmlElementInfo Create(XmlNodeSyntax node) { string localName = element.Name?.LocalName.ValueText; - if (localName == null) + if (localName is null) return default; return new XmlElementInfo(element, localName); diff --git a/src/CSharp/CSharp/SyntaxAccessibility.cs b/src/CSharp/CSharp/SyntaxAccessibility.cs index d55cad471f..49d2f8fabe 100644 --- a/src/CSharp/CSharp/SyntaxAccessibility.cs +++ b/src/CSharp/CSharp/SyntaxAccessibility.cs @@ -21,7 +21,7 @@ public static class SyntaxAccessibility /// public static Accessibility GetDefaultAccessibility(SyntaxNode declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); switch (declaration.Kind()) @@ -84,7 +84,7 @@ public static Accessibility GetDefaultAccessibility(SyntaxNode declaration) /// public static Accessibility GetDefaultExplicitAccessibility(SyntaxNode declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); switch (declaration.Kind()) @@ -147,7 +147,7 @@ public static Accessibility GetDefaultExplicitAccessibility(SyntaxNode declarati /// public static Accessibility GetAccessibility(SyntaxNode declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); switch (declaration.Kind()) @@ -210,7 +210,7 @@ public static Accessibility GetAccessibility(SyntaxNode declaration) /// public static Accessibility GetExplicitAccessibility(SyntaxNode declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); switch (declaration.Kind()) @@ -330,7 +330,7 @@ public static Accessibility GetExplicitAccessibility(SyntaxTokenList modifiers) /// public static bool IsPubliclyVisible(MemberDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); do @@ -348,7 +348,7 @@ public static bool IsPubliclyVisible(MemberDeclarationSyntax declaration) SyntaxNode parent = declaration.Parent; - if (parent == null) + if (parent is null) return true; if (parent is ICompilationUnitSyntax) @@ -358,7 +358,7 @@ public static bool IsPubliclyVisible(MemberDeclarationSyntax declaration) declaration = parent as MemberDeclarationSyntax; } - while (declaration != null); + while (declaration is not null); return false; } @@ -385,7 +385,7 @@ public static bool IsPubliclyVisible(MemberDeclarationSyntax declaration) Accessibility newAccessibility, IComparer comparer = null) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); ModifierListInfo info = SyntaxInfo.ModifierListInfo(node); @@ -406,7 +406,7 @@ public static bool IsPubliclyVisible(MemberDeclarationSyntax declaration) /// Ignore "override" modifier. public static bool IsValidAccessibility(SyntaxNode node, Accessibility accessibility, bool ignoreOverride = false) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); switch (node.Parent?.Kind()) @@ -511,9 +511,9 @@ public static bool IsValidAccessibility(SyntaxNode node, Accessibility accessibi { var memberDeclaration = node.Parent?.Parent as MemberDeclarationSyntax; - SyntaxDebug.Assert(memberDeclaration != null, node); + SyntaxDebug.Assert(memberDeclaration is not null, node); - if (memberDeclaration != null) + if (memberDeclaration is not null) { if (!CheckProtectedInStaticOrSealedClass(memberDeclaration)) return false; @@ -544,7 +544,7 @@ bool CheckProtectedInStaticOrSealedClass(SyntaxNode declaration) bool CheckAccessorAccessibility(AccessorListSyntax accessorList) { - if (accessorList != null) + if (accessorList is not null) { foreach (AccessorDeclarationSyntax accessor in accessorList.Accessors) { diff --git a/src/CSharp/CSharp/SyntaxAccessibility`1.cs b/src/CSharp/CSharp/SyntaxAccessibility`1.cs index 8879451ef3..5507505f4e 100644 --- a/src/CSharp/CSharp/SyntaxAccessibility`1.cs +++ b/src/CSharp/CSharp/SyntaxAccessibility`1.cs @@ -108,7 +108,7 @@ private class AccessorAccessibility : SyntaxAccessibility.Instance.GetDefaultAccessibility((EventDeclarationSyntax)containingDeclaration); } - SyntaxDebug.Assert(containingDeclaration == null, containingDeclaration); + SyntaxDebug.Assert(containingDeclaration is null, containingDeclaration); return Accessibility.NotApplicable; } public override Accessibility GetAccessibility(AccessorDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); Accessibility accessibility = SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); SyntaxNode containingDeclaration = declaration.Parent?.Parent; - if (containingDeclaration == null) + if (containingDeclaration is null) return accessibility; Accessibility containingAccessibility = GetAccessibility(); @@ -169,7 +169,7 @@ Accessibility GetAccessibility() public override Accessibility GetExplicitAccessibility(AccessorDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); @@ -185,7 +185,7 @@ private static class BaseTypeAccessibility { public static Accessibility GetDefaultAccessibility(BaseTypeDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return (declaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration)) @@ -195,7 +195,7 @@ public static Accessibility GetDefaultAccessibility(BaseTypeDeclarationSyntax de public static Accessibility GetDefaultExplicitAccessibility(BaseTypeDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return (declaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration)) @@ -218,7 +218,7 @@ public override Accessibility GetDefaultExplicitAccessibility(ClassDeclarationSy public override Accessibility GetAccessibility(ClassDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); Accessibility accessibility = SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); @@ -230,7 +230,7 @@ public override Accessibility GetAccessibility(ClassDeclarationSyntax declaratio public override Accessibility GetExplicitAccessibility(ClassDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); @@ -241,7 +241,7 @@ private class ConstructorAccessibility : SyntaxAccessibility { public override Accessibility GetDefaultAccessibility(EventDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return Accessibility.Private; @@ -475,20 +475,20 @@ public override Accessibility GetDefaultAccessibility(EventDeclarationSyntax dec public override Accessibility GetDefaultExplicitAccessibility(EventDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); - return (declaration.ExplicitInterfaceSpecifier != null) + return (declaration.ExplicitInterfaceSpecifier is not null) ? Accessibility.NotApplicable : Accessibility.Private; } public override Accessibility GetAccessibility(EventDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); - if (declaration.ExplicitInterfaceSpecifier != null) + if (declaration.ExplicitInterfaceSpecifier is not null) return Accessibility.Private; Accessibility accessibility = SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); @@ -500,7 +500,7 @@ public override Accessibility GetAccessibility(EventDeclarationSyntax declaratio public override Accessibility GetExplicitAccessibility(EventDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); @@ -511,7 +511,7 @@ private class EventFieldAccessibility : SyntaxAccessibility { public override Accessibility GetDefaultAccessibility(FieldDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return Accessibility.Private; @@ -565,7 +565,7 @@ public override Accessibility GetDefaultAccessibility(FieldDeclarationSyntax dec public override Accessibility GetDefaultExplicitAccessibility(FieldDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return Accessibility.Private; @@ -573,7 +573,7 @@ public override Accessibility GetDefaultExplicitAccessibility(FieldDeclarationSy public override Accessibility GetAccessibility(FieldDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); Accessibility accessibility = SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); @@ -585,7 +585,7 @@ public override Accessibility GetAccessibility(FieldDeclarationSyntax declaratio public override Accessibility GetExplicitAccessibility(FieldDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); @@ -596,7 +596,7 @@ private class IndexerAccessibility : SyntaxAccessibility { public override Accessibility GetDefaultAccessibility(MethodDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return (declaration.IsParentKind(SyntaxKind.InterfaceDeclaration)) @@ -694,11 +694,11 @@ public override Accessibility GetDefaultAccessibility(MethodDeclarationSyntax de public override Accessibility GetDefaultExplicitAccessibility(MethodDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); if (declaration.Modifiers.Contains(SyntaxKind.PartialKeyword) - || declaration.ExplicitInterfaceSpecifier != null + || declaration.ExplicitInterfaceSpecifier is not null || declaration.IsParentKind(SyntaxKind.InterfaceDeclaration)) { return Accessibility.NotApplicable; @@ -711,7 +711,7 @@ public override Accessibility GetDefaultExplicitAccessibility(MethodDeclarationS public override Accessibility GetAccessibility(MethodDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); SyntaxTokenList modifiers = declaration.Modifiers; @@ -719,7 +719,7 @@ public override Accessibility GetAccessibility(MethodDeclarationSyntax declarati if (modifiers.Contains(SyntaxKind.PartialKeyword)) return Accessibility.Private; - if (declaration.ExplicitInterfaceSpecifier != null) + if (declaration.ExplicitInterfaceSpecifier is not null) return Accessibility.Private; if (declaration.IsParentKind(SyntaxKind.InterfaceDeclaration)) @@ -734,7 +734,7 @@ public override Accessibility GetAccessibility(MethodDeclarationSyntax declarati public override Accessibility GetExplicitAccessibility(MethodDeclarationSyntax declaration) { - if (declaration == null) + if (declaration is null) throw new ArgumentNullException(nameof(declaration)); return SyntaxAccessibility.GetExplicitAccessibility(declaration.Modifiers); @@ -745,7 +745,7 @@ private class NamespaceAccessibility : SyntaxAccessibility(TNode node, DocumentationCommentTriviaSyntax documentationComment) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); if (!documentationComment.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)) @@ -217,7 +217,7 @@ internal static MemberDeclarationSyntax RemoveSingleLineDocumentationComment(Mem public static TNode RemoveComments(TNode node, CommentFilter comments) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return RemoveComments(node, node.FullSpan, comments); @@ -225,7 +225,7 @@ internal static MemberDeclarationSyntax RemoveSingleLineDocumentationComment(Mem public static TNode RemoveComments(TNode node, TextSpan span, CommentFilter comments) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); List commentsToRemove = null; @@ -304,7 +304,7 @@ internal static MemberDeclarationSyntax RemoveSingleLineDocumentationComment(Mem } } - return (commentsToRemove != null) + return (commentsToRemove is not null) ? node.ReplaceTrivia(commentsToRemove, (_, __) => EmptyWhitespace()) : node; @@ -352,7 +352,7 @@ void RemoveMultiline(SyntaxTrivia trivia) public static TNode RemoveTrivia(TNode node, TextSpan? span = null) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return (TNode)TriviaRemover.GetInstance(span).Visit(node); @@ -360,7 +360,7 @@ void RemoveMultiline(SyntaxTrivia trivia) public static TNode RemoveWhitespace(TNode node, TextSpan? span = null) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return (TNode)WhitespaceRemover.GetInstance(span).Visit(node); @@ -368,10 +368,10 @@ void RemoveMultiline(SyntaxTrivia trivia) public static ClassDeclarationSyntax RemoveMember(ClassDeclarationSyntax classDeclaration, MemberDeclarationSyntax member) { - if (classDeclaration == null) + if (classDeclaration is null) throw new ArgumentNullException(nameof(classDeclaration)); - if (member == null) + if (member is null) throw new ArgumentNullException(nameof(member)); int index = classDeclaration.Members.IndexOf(member); @@ -385,10 +385,10 @@ public static ClassDeclarationSyntax RemoveMember(ClassDeclarationSyntax classDe public static CompilationUnitSyntax RemoveMember(CompilationUnitSyntax compilationUnit, MemberDeclarationSyntax member) { - if (compilationUnit == null) + if (compilationUnit is null) throw new ArgumentNullException(nameof(compilationUnit)); - if (member == null) + if (member is null) throw new ArgumentNullException(nameof(member)); int index = compilationUnit.Members.IndexOf(member); @@ -402,10 +402,10 @@ public static CompilationUnitSyntax RemoveMember(CompilationUnitSyntax compilati public static InterfaceDeclarationSyntax RemoveMember(InterfaceDeclarationSyntax interfaceDeclaration, MemberDeclarationSyntax member) { - if (interfaceDeclaration == null) + if (interfaceDeclaration is null) throw new ArgumentNullException(nameof(interfaceDeclaration)); - if (member == null) + if (member is null) throw new ArgumentNullException(nameof(member)); int index = interfaceDeclaration.Members.IndexOf(member); @@ -419,10 +419,10 @@ public static InterfaceDeclarationSyntax RemoveMember(InterfaceDeclarationSyntax public static BaseNamespaceDeclarationSyntax RemoveMember(BaseNamespaceDeclarationSyntax namespaceDeclaration, MemberDeclarationSyntax member) { - if (namespaceDeclaration == null) + if (namespaceDeclaration is null) throw new ArgumentNullException(nameof(namespaceDeclaration)); - if (member == null) + if (member is null) throw new ArgumentNullException(nameof(member)); int index = namespaceDeclaration.Members.IndexOf(member); @@ -443,10 +443,10 @@ public static BaseNamespaceDeclarationSyntax RemoveMember(BaseNamespaceDeclarati public static StructDeclarationSyntax RemoveMember(StructDeclarationSyntax structDeclaration, MemberDeclarationSyntax member) { - if (structDeclaration == null) + if (structDeclaration is null) throw new ArgumentNullException(nameof(structDeclaration)); - if (member == null) + if (member is null) throw new ArgumentNullException(nameof(member)); int index = structDeclaration.Members.IndexOf(member); @@ -460,10 +460,10 @@ public static StructDeclarationSyntax RemoveMember(StructDeclarationSyntax struc public static RecordDeclarationSyntax RemoveMember(RecordDeclarationSyntax recordDeclaration, MemberDeclarationSyntax member) { - if (recordDeclaration == null) + if (recordDeclaration is null) throw new ArgumentNullException(nameof(recordDeclaration)); - if (member == null) + if (member is null) throw new ArgumentNullException(nameof(member)); int index = recordDeclaration.Members.IndexOf(member); @@ -477,10 +477,10 @@ public static RecordDeclarationSyntax RemoveMember(RecordDeclarationSyntax recor public static TypeDeclarationSyntax RemoveMember(TypeDeclarationSyntax typeDeclaration, MemberDeclarationSyntax member) { - if (typeDeclaration == null) + if (typeDeclaration is null) throw new ArgumentNullException(nameof(typeDeclaration)); - if (member == null) + if (member is null) throw new ArgumentNullException(nameof(member)); int index = typeDeclaration.Members.IndexOf(member); @@ -571,7 +571,7 @@ public static InvocationExpressionSyntax ChangeInvokedMethodName(InvocationExpre { ExpressionSyntax expression = invocationExpression.Expression; - if (expression != null) + if (expression is not null) { SyntaxKind kind = expression.Kind(); @@ -580,7 +580,7 @@ public static InvocationExpressionSyntax ChangeInvokedMethodName(InvocationExpre var memberAccess = (MemberAccessExpressionSyntax)expression; SimpleNameSyntax simpleName = memberAccess.Name; - if (simpleName != null) + if (simpleName is not null) { SimpleNameSyntax newSimpleName = ChangeName(simpleName); @@ -592,7 +592,7 @@ public static InvocationExpressionSyntax ChangeInvokedMethodName(InvocationExpre var memberBinding = (MemberBindingExpressionSyntax)expression; SimpleNameSyntax simpleName = memberBinding.Name; - if (simpleName != null) + if (simpleName is not null) { SimpleNameSyntax newSimpleName = ChangeName(simpleName); @@ -693,7 +693,7 @@ string GetCharacterLiteralText() ExpressionSyntax expression = expressionStatement.Expression; - if (expression == null + if (expression is null || !CSharpFacts.IsIncrementOrDecrementExpression(expression.Kind())) { break; diff --git a/src/CSharp/CSharp/SyntaxRewriters/BinaryExpressionToMultiLineRewriter.cs b/src/CSharp/CSharp/SyntaxRewriters/BinaryExpressionToMultiLineRewriter.cs index 52a9fb5b0f..5ea478321d 100644 --- a/src/CSharp/CSharp/SyntaxRewriters/BinaryExpressionToMultiLineRewriter.cs +++ b/src/CSharp/CSharp/SyntaxRewriters/BinaryExpressionToMultiLineRewriter.cs @@ -19,7 +19,7 @@ public BinaryExpressionToMultiLineRewriter(SyntaxTriviaList leadingTrivia) public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node) { - if (_previous == null + if (_previous is null || (_previous.Equals(node.Parent) && node.IsKind(_previous.Kind()))) { node = node diff --git a/src/CSharp/CSharp/SyntaxRewriters/TriviaRemover.cs b/src/CSharp/CSharp/SyntaxRewriters/TriviaRemover.cs index 5a71c0aab1..0f82afe448 100644 --- a/src/CSharp/CSharp/SyntaxRewriters/TriviaRemover.cs +++ b/src/CSharp/CSharp/SyntaxRewriters/TriviaRemover.cs @@ -21,7 +21,7 @@ private TriviaRemover(TextSpan? span = null) public static TriviaRemover GetInstance(TextSpan? span = null) { - if (span != null) + if (span is not null) { return new TriviaRemover(span); } diff --git a/src/CSharp/CSharp/SyntaxRewriters/WhitespaceRemover.cs b/src/CSharp/CSharp/SyntaxRewriters/WhitespaceRemover.cs index 7fde18d8d9..a1378653f4 100644 --- a/src/CSharp/CSharp/SyntaxRewriters/WhitespaceRemover.cs +++ b/src/CSharp/CSharp/SyntaxRewriters/WhitespaceRemover.cs @@ -21,7 +21,7 @@ private WhitespaceRemover(TextSpan? span = null) public static WhitespaceRemover GetInstance(TextSpan? span = null) { - if (span != null) + if (span is not null) { return new WhitespaceRemover(span); } diff --git a/src/CSharp/CSharp/SyntaxTriviaAnalysis.cs b/src/CSharp/CSharp/SyntaxTriviaAnalysis.cs index f3cb1d05f2..08945b9caa 100644 --- a/src/CSharp/CSharp/SyntaxTriviaAnalysis.cs +++ b/src/CSharp/CSharp/SyntaxTriviaAnalysis.cs @@ -211,7 +211,7 @@ public static SyntaxTrivia DetermineIndentation(SyntaxNodeOrToken nodeOrToken, C { SyntaxTree tree = nodeOrToken.SyntaxTree; - if (tree == null) + if (tree is null) return CSharpFactory.EmptyWhitespace(); TextSpan span = nodeOrToken.Span; @@ -272,7 +272,7 @@ public static SyntaxTrivia DetermineIndentation(SyntaxNodeOrToken nodeOrToken, C { node = node.Parent; - while (node != null) + while (node is not null) { if (IsMemberDeclarationOrStatementOrAccessorDeclaration(node)) { diff --git a/src/CSharp/CSharp/SyntaxWalkers/ContainsCommentWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/ContainsCommentWalker.cs index af3ff2ccc0..99cc8f20c1 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/ContainsCommentWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/ContainsCommentWalker.cs @@ -61,7 +61,7 @@ public static ContainsCommentWalker GetInstance(TextSpan span) { ContainsCommentWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { _cachedInstance = null; walker.Result = false; diff --git a/src/CSharp/CSharp/SyntaxWalkers/ContainsLocalOrParameterReferenceWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/ContainsLocalOrParameterReferenceWalker.cs index 862a739291..0a7642c257 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/ContainsLocalOrParameterReferenceWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/ContainsLocalOrParameterReferenceWalker.cs @@ -126,10 +126,10 @@ public override void VisitIdentifierName(IdentifierNameSyntax node) { ContainsLocalOrParameterReferenceWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { - Debug.Assert(walker.Symbol == null); - Debug.Assert(walker.SemanticModel == null); + Debug.Assert(walker.Symbol is null); + Debug.Assert(walker.SemanticModel is null); Debug.Assert(walker.CancellationToken == default); _cachedInstance = null; diff --git a/src/CSharp/CSharp/SyntaxWalkers/ContainsYieldWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/ContainsYieldWalker.cs index dc7950d9cd..0c999f7124 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/ContainsYieldWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/ContainsYieldWalker.cs @@ -22,7 +22,7 @@ internal sealed class ContainsYieldWalker : StatementWalker public override bool ShouldVisit { - get { return YieldStatement == null; } + get { return YieldStatement is null; } } public bool SearchForYieldBreak { get; private set; } @@ -33,7 +33,7 @@ public override bool ShouldVisit public static bool ContainsYield(StatementSyntax statement, bool searchForYieldReturn = true, bool searchForYieldBreak = true) { - if (statement == null) + if (statement is null) throw new ArgumentNullException(nameof(statement)); ContainsYieldWalker walker = GetInstance(); @@ -42,7 +42,7 @@ public static bool ContainsYield(StatementSyntax statement, bool searchForYieldR walker.VisitStatement(statement); - bool success = walker.YieldStatement != null; + bool success = walker.YieldStatement is not null; Free(walker); @@ -75,9 +75,9 @@ public static ContainsYieldWalker GetInstance() { ContainsYieldWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { - Debug.Assert(walker.YieldStatement == null); + Debug.Assert(walker.YieldStatement is null); _cachedInstance = null; return walker; diff --git a/src/CSharp/CSharp/SyntaxWalkers/MethodReferencedAsMethodGroupWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/MethodReferencedAsMethodGroupWalker.cs index 00414979b5..af00f02389 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/MethodReferencedAsMethodGroupWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/MethodReferencedAsMethodGroupWalker.cs @@ -105,7 +105,7 @@ static bool IsInvoked(IdentifierNameSyntax identifierName) } finally { - if (walker != null) + if (walker is not null) Free(walker); } @@ -116,10 +116,10 @@ private static MethodReferencedAsMethodGroupWalker GetInstance() { MethodReferencedAsMethodGroupWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { - Debug.Assert(walker.Symbol == null); - Debug.Assert(walker.SemanticModel == null); + Debug.Assert(walker.Symbol is null); + Debug.Assert(walker.SemanticModel is null); Debug.Assert(walker.CancellationToken == default); _cachedInstance = null; diff --git a/src/CSharp/CSharp/SyntaxWalkers/StatementWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/StatementWalker.cs index bf6fbe9259..c3a124e44c 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/StatementWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/StatementWalker.cs @@ -139,7 +139,7 @@ public override void VisitTryStatement(TryStatementSyntax node) FinallyClauseSyntax finallyClause = node.Finally; - if (finallyClause != null) + if (finallyClause is not null) VisitBlockIfNotNull(finallyClause.Block); } @@ -164,7 +164,7 @@ public override void VisitYieldStatement(YieldStatementSyntax node) private void VisitBlockIfNotNull(BlockSyntax node) { - if (node != null + if (node is not null && ShouldVisit) { VisitBlock(node); @@ -173,7 +173,7 @@ private void VisitBlockIfNotNull(BlockSyntax node) private void VisitStatementIfNotNull(StatementSyntax node) { - if (node != null + if (node is not null && ShouldVisit) { VisitStatement(node); diff --git a/src/CSharp/CSharp/SyntaxWalkers/TriviaWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/TriviaWalker.cs index 5f8c17cb5b..e1950cda12 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/TriviaWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/TriviaWalker.cs @@ -104,7 +104,7 @@ public static ContainsOnlyWhitespaceOrEndOfLineTriviaWalker GetInstance(TextSpan { ContainsOnlyWhitespaceOrEndOfLineTriviaWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { _cachedInstance = null; walker.Result = true; diff --git a/src/CSharp/DetermineParameterHelper.cs b/src/CSharp/DetermineParameterHelper.cs index a95298cc11..44f11e7a56 100644 --- a/src/CSharp/DetermineParameterHelper.cs +++ b/src/CSharp/DetermineParameterHelper.cs @@ -22,12 +22,12 @@ internal static class DetermineParameterHelper if (argument.Parent is not BaseArgumentListSyntax argumentList) return null; - if (argumentList.Parent == null) + if (argumentList.Parent is null) return null; ISymbol symbol = GetSymbol(argumentList.Parent, allowCandidate, semanticModel, cancellationToken); - if (symbol == null) + if (symbol is null) return null; ImmutableArray parameters = symbol.ParametersOrDefault(); @@ -48,7 +48,7 @@ internal static class DetermineParameterHelper { string name = argument.NameColon?.Name?.Identifier.ValueText; - if (name != null) + if (name is not null) { foreach (IParameterSymbol parameter in parameters) { @@ -85,7 +85,7 @@ internal static class DetermineParameterHelper bool allowCandidate = false, CancellationToken cancellationToken = default) { - if (attributeArgument.NameEquals != null) + if (attributeArgument.NameEquals is not null) return null; SyntaxNode parent = attributeArgument.Parent; @@ -98,7 +98,7 @@ internal static class DetermineParameterHelper ISymbol symbol = GetSymbol(attribute, allowCandidate, semanticModel, cancellationToken); - if (symbol == null) + if (symbol is null) return null; ImmutableArray parameters = symbol.ParametersOrDefault(); @@ -119,7 +119,7 @@ internal static class DetermineParameterHelper { string name = attributeArgument.NameColon?.Name?.Identifier.ValueText; - if (name != null) + if (name is not null) { foreach (IParameterSymbol parameter in parameters) { @@ -155,7 +155,7 @@ private static ISymbol GetSymbol(SyntaxNode node, bool allowCandidate, SemanticM ISymbol symbol = symbolInfo.Symbol; - if (symbol == null + if (symbol is null && allowCandidate) { return symbolInfo.CandidateSymbols.FirstOrDefault(); diff --git a/src/CSharp/DetermineParameterTypeHelper.cs b/src/CSharp/DetermineParameterTypeHelper.cs index 1117bb8629..6cccc6467c 100644 --- a/src/CSharp/DetermineParameterTypeHelper.cs +++ b/src/CSharp/DetermineParameterTypeHelper.cs @@ -22,13 +22,13 @@ internal static class DetermineParameterTypeHelper { SyntaxNode parent = argumentList.Parent; - if (parent != null) + if (parent is not null) { SymbolInfo symbolInfo = GetSymbolInfo(parent, semanticModel, cancellationToken); ISymbol symbol = symbolInfo.Symbol; - if (symbol != null) + if (symbol is not null) { ITypeSymbol typeSymbol = DetermineParameterType(symbol, argument, argumentList); @@ -49,7 +49,7 @@ internal static class DetermineParameterTypeHelper } } - if (typeSymbols != null) + if (typeSymbols is not null) return typeSymbols.ToImmutableArray(); } } @@ -76,7 +76,7 @@ private static SymbolInfo GetSymbolInfo(SyntaxNode node, SemanticModel semanticM { IParameterSymbol parameterSymbol = DetermineParameterSymbol(symbol, argument, argumentList); - if (parameterSymbol == null) + if (parameterSymbol is null) return null; RefKind refKind = parameterSymbol.RefKind; @@ -117,7 +117,7 @@ private static SymbolInfo GetSymbolInfo(SyntaxNode node, SemanticModel semanticM string name = argument.NameColon?.Name?.Identifier.ValueText; - if (name != null) + if (name is not null) return parameters.FirstOrDefault(f => f.Name == name); int index = argumentList.Arguments.IndexOf(argument); diff --git a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeArgumentCodeFixProvider.cs b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeArgumentCodeFixProvider.cs index 39240b608f..6775d812b7 100644 --- a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeArgumentCodeFixProvider.cs +++ b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeArgumentCodeFixProvider.cs @@ -62,7 +62,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) string languageName, CancellationToken cancellationToken) { - if (_languageNames == null) + if (_languageNames is null) Interlocked.CompareExchange(ref _languageNames, LoadLanguageNames(), null); AttributeArgumentSyntax newAttributeArgument = AttributeArgument( diff --git a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/UsePatternMatchingCodeFixProvider.cs b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/UsePatternMatchingCodeFixProvider.cs index e0d5ad8839..59b2723773 100644 --- a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/UsePatternMatchingCodeFixProvider.cs +++ b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/UsePatternMatchingCodeFixProvider.cs @@ -126,7 +126,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) .WithExpression(newExpression.WithTriviaFrom(expression)) .WithSections(newSections); - if (localDeclaration != null) + if (localDeclaration is not null) { StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(switchStatement); diff --git a/src/CodeAnalysis.Analyzers/CSharp/ElementAccessExpressionAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/ElementAccessExpressionAnalyzer.cs index 5f5dd427ea..355d5813ad 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/ElementAccessExpressionAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/ElementAccessExpressionAnalyzer.cs @@ -44,7 +44,7 @@ private static void AnalyzeElementAccessExpression(SyntaxNodeAnalysisContext con .Expression .WalkDownParentheses(); - if (expression == null) + if (expression is null) return; if (!expression.IsKind(SyntaxKind.SubtractExpression)) diff --git a/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs index d4b529afab..a21c2d2328 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs @@ -190,7 +190,7 @@ void UseElementAccessInsteadOfCallingElementAt() void UseReturnValue() { - if (symbol == null) + if (symbol is null) symbol = context.SemanticModel.GetSymbol(invocationExpression, context.CancellationToken); if (symbol?.Kind != SymbolKind.Method) diff --git a/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs index cd801cfc74..f9e08eae6f 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs @@ -47,7 +47,7 @@ private static void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context) INamedTypeSymbol baseType = symbol.BaseType; - while (baseType != null) + while (baseType is not null) { switch (baseType.Name) { @@ -91,7 +91,7 @@ private static void AnalyzeDiagnosticAnalyzer(SymbolAnalysisContext context, INa { AttributeData attribute = symbol.GetAttribute(RoslynMetadataNames.Microsoft_CodeAnalysis_Diagnostics_DiagnosticAnalyzerAttribute); - if (attribute == null) + if (attribute is null) return; if (DiagnosticRules.UnknownLanguageName.IsEffective(context)) @@ -102,7 +102,7 @@ private static void AnalyzeCodeFixProvider(SymbolAnalysisContext context, INamed { AttributeData attribute = symbol.GetAttribute(RoslynMetadataNames.Microsoft_CodeAnalysis_CodeFixes_ExportCodeFixProviderAttribute); - if (attribute == null) + if (attribute is null) return; if (DiagnosticRules.UnknownLanguageName.IsEffective(context)) @@ -119,7 +119,7 @@ private static void AnalyzeCodeRefactoringProvider(SymbolAnalysisContext context { AttributeData attribute = symbol.GetAttribute(RoslynMetadataNames.Microsoft_CodeAnalysis_CodeRefactorings_ExportCodeRefactoringProviderAttribute); - if (attribute == null) + if (attribute is null) return; if (DiagnosticRules.UnknownLanguageName.IsEffective(context)) diff --git a/src/CodeAnalysis.Analyzers/CSharp/SimpleMemberAccessExpressionAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/SimpleMemberAccessExpressionAnalyzer.cs index 1a2a3a2e77..5ead22c74d 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/SimpleMemberAccessExpressionAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/SimpleMemberAccessExpressionAnalyzer.cs @@ -61,7 +61,7 @@ private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContex ISymbol symbol = context.SemanticModel.GetSymbol(memberAccessExpression, context.CancellationToken); - if (symbol == null) + if (symbol is null) break; if (!symbol.ContainingType.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_Text_TextSpan)) @@ -79,7 +79,7 @@ private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContex ISymbol symbol2 = context.SemanticModel.GetSymbol(expression, context.CancellationToken); - if (symbol2 == null) + if (symbol2 is null) break; if (!symbol2.ContainingType.HasMetadataName(MetadataNames.Microsoft_CodeAnalysis_SyntaxNode)) diff --git a/src/CodeAnalysis.Analyzers/CSharp/Syntax/IsKindExpressionInfo.cs b/src/CodeAnalysis.Analyzers/CSharp/Syntax/IsKindExpressionInfo.cs index ad87ee67ee..ac738f188d 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/Syntax/IsKindExpressionInfo.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/Syntax/IsKindExpressionInfo.cs @@ -55,7 +55,7 @@ private string DebuggerDisplay { ExpressionSyntax expression = WalkAndCheck(node, walkDownParentheses, allowMissing); - if (expression == null) + if (expression is null) return default; SyntaxKind kind = expression.Kind(); @@ -69,12 +69,12 @@ private string DebuggerDisplay ExpressionSyntax left = WalkAndCheck(binaryExpression.Left, walkDownParentheses, allowMissing); - if (left == null) + if (left is null) break; ExpressionSyntax right = WalkAndCheck(binaryExpression.Right, walkDownParentheses, allowMissing); - if (right == null) + if (right is null) break; IsKindExpressionInfo info = Create(binaryExpression, kind, left, right, semanticModel, cancellationToken); diff --git a/src/CodeAnalysis.Analyzers/CSharp/UsePatternMatchingAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/UsePatternMatchingAnalyzer.cs index ce499038bc..d13eae301b 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/UsePatternMatchingAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/UsePatternMatchingAnalyzer.cs @@ -42,13 +42,13 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(startContext => { - if (_syntaxKindNames == null) + if (_syntaxKindNames is null) { Compilation compilation = startContext.Compilation; INamedTypeSymbol csharpSyntaxNodeSymbol = compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode"); - if (csharpSyntaxNodeSymbol == null) + if (csharpSyntaxNodeSymbol is null) return; Dictionary kindsToNames = compilation @@ -105,7 +105,7 @@ private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) string name = GetName(); - if (name == null) + if (name is null) return; ITypeSymbol kindSymbol = context.SemanticModel.GetTypeSymbol(switchExpression, context.CancellationToken); @@ -117,7 +117,7 @@ private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) { SwitchLabelSyntax label = section.Labels.SingleOrDefault(shouldThrow: false); - if (label == null) + if (label is null) return; SyntaxKind labelKind = label.Kind(); @@ -152,7 +152,7 @@ private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) StatementSyntax statement = statements.FirstOrDefault(); - if (statement == null) + if (statement is null) return; if (statement is BlockSyntax block) @@ -288,12 +288,12 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) case IsKindExpressionStyle.NotKind: case IsKindExpressionStyle.NotKindConditional: { - if (ifStatement.Else != null) + if (ifStatement.Else is not null) return; StatementSyntax statement = ifStatement.Statement.SingleNonBlockStatementOrDefault(); - if (statement == null) + if (statement is null) return; if (!CSharpFacts.IsJumpStatement(statement.Kind())) @@ -387,7 +387,7 @@ void Analyze(StatementSyntax statement) } finally { - if (walker != null) + if (walker is not null) ContainsLocalOrParameterReferenceWalker.Free(walker); } diff --git a/src/CodeAnalysis.Analyzers/RoslynUtility.cs b/src/CodeAnalysis.Analyzers/RoslynUtility.cs index b3554c73ab..e58941b486 100644 --- a/src/CodeAnalysis.Analyzers/RoslynUtility.cs +++ b/src/CodeAnalysis.Analyzers/RoslynUtility.cs @@ -16,7 +16,7 @@ public static ImmutableHashSet WellKnownLanguageNames { get { - if (_wellKnownLanguageNames == null) + if (_wellKnownLanguageNames is null) Interlocked.CompareExchange(ref _wellKnownLanguageNames, LoadLanguageNames(), null); return _wellKnownLanguageNames; diff --git a/src/CodeFixes/CSharp/CodeFixes/AddBodyCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/AddBodyCodeFixProvider.cs index 73dbfdbba8..e567215ca1 100644 --- a/src/CodeFixes/CSharp/CodeFixes/AddBodyCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/AddBodyCodeFixProvider.cs @@ -51,7 +51,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) Func> createChangedDocument = GetCreateChangedDocument(context, node); - if (createChangedDocument == null) + if (createChangedDocument is null) return; CodeAction codeAction = CodeAction.Create( @@ -77,7 +77,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ParameterListSyntax parameterList = methodDeclaration.ParameterList; - if (parameterList == null) + if (parameterList is null) break; return ct => @@ -102,7 +102,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ParameterListSyntax parameterList = constructorDeclaration.ParameterList; - if (parameterList == null) + if (parameterList is null) break; return ct => @@ -127,7 +127,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ParameterListSyntax parameterList = destructorDeclaration.ParameterList; - if (parameterList == null) + if (parameterList is null) break; return ct => @@ -152,7 +152,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ParameterListSyntax parameterList = operatorDeclaration.ParameterList; - if (parameterList == null) + if (parameterList is null) break; return ct => @@ -177,7 +177,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ParameterListSyntax parameterList = conversionOperatorDeclaration.ParameterList; - if (parameterList == null) + if (parameterList is null) break; return ct => @@ -229,7 +229,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ParameterListSyntax parameterList = localFunction.ParameterList; - if (parameterList == null) + if (parameterList is null) break; return ct => diff --git a/src/CodeFixes/CSharp/CodeFixes/AddReturnStatementCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/AddReturnStatementCodeFixProvider.cs index d015982589..3b3c4d721b 100644 --- a/src/CodeFixes/CSharp/CodeFixes/AddReturnStatementCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/AddReturnStatementCodeFixProvider.cs @@ -127,7 +127,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) BlockSyntax body, SemanticModel semanticModel) { - if (type != null + if (type is not null && body?.Statements.Count > 0) { ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); diff --git a/src/CodeFixes/CSharp/CodeFixes/ArgumentCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ArgumentCodeFixProvider.cs index 9a22cb4df0..8956c2fc5a 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ArgumentCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ArgumentCodeFixProvider.cs @@ -49,7 +49,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) IParameterSymbol parameter = semanticModel.DetermineParameter(argument, allowCandidate: true, cancellationToken: context.CancellationToken); - if (parameter == null) + if (parameter is null) return; SyntaxToken refOrOutKeyword = default; diff --git a/src/CodeFixes/CSharp/CodeFixes/AssignDefaultValueToOutParameterCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/AssignDefaultValueToOutParameterCodeFixProvider.cs index 68c7b38c33..49d175fc40 100644 --- a/src/CodeFixes/CSharp/CodeFixes/AssignDefaultValueToOutParameterCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/AssignDefaultValueToOutParameterCodeFixProvider.cs @@ -55,15 +55,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) node = node.FirstAncestor(f => f.IsKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement)); - Debug.Assert(node != null, "Containing method or local function not found."); + Debug.Assert(node is not null, "Containing method or local function not found."); - if (node == null) + if (node is null) return; } SyntaxNode bodyOrExpressionBody = GetBodyOrExpressionBody(node); - if (bodyOrExpressionBody == null) + if (bodyOrExpressionBody is null) return; if (bodyOrExpressionBody is BlockSyntax body @@ -93,7 +93,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) if (parameter.RefKind == RefKind.Out && !alwaysAssigned.Contains(parameter)) { - if (singleParameter == null) + if (singleParameter is null) { singleParameter = parameter; isAny = true; @@ -112,7 +112,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) return; CodeAction codeAction = CodeAction.Create( - (singleParameter != null) + (singleParameter is not null) ? $"Assign default value to parameter '{singleParameter.Name}'" : "Assign default value to parameters", ct => RefactorAsync(context.Document, node, statement, bodyOrExpressionBody, parameters, alwaysAssigned, semanticModel, ct), @@ -160,7 +160,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) newNode = InsertStatements(newNode, expressionStatements); } - else if (statement != null) + else if (statement is not null) { if (statement.IsEmbedded()) { @@ -189,7 +189,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) StatementSyntax lastStatement = statements.LastOrDefault(f => !f.IsKind(SyntaxKind.LocalFunctionStatement, SyntaxKind.ReturnStatement)); - int index = (lastStatement != null) + int index = (lastStatement is not null) ? statements.IndexOf(lastStatement) + 1 : 0; diff --git a/src/CodeFixes/CSharp/CodeFixes/CannotConvertArgumentTypeCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/CannotConvertArgumentTypeCodeFixProvider.cs index b907cf0fcc..0780a1aeee 100644 --- a/src/CodeFixes/CSharp/CodeFixes/CannotConvertArgumentTypeCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/CannotConvertArgumentTypeCodeFixProvider.cs @@ -85,7 +85,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) != null) + if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) is not null) { CodeAction codeAction = CodeAction.Create( "Add argument list", diff --git a/src/CodeFixes/CSharp/CodeFixes/CaseSwitchLabelCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/CaseSwitchLabelCodeFixProvider.cs index 94f5fe07b9..b98306b027 100644 --- a/src/CodeFixes/CSharp/CodeFixes/CaseSwitchLabelCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/CaseSwitchLabelCodeFixProvider.cs @@ -66,7 +66,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) if (semanticModel.GetDiagnostic( CompilerDiagnosticIdentifiers.CS0152_SwitchStatementContainsMultipleCasesWithSameLabelValue, label.Span, - cancellationToken) != null) + cancellationToken) is not null) { labelsToRemove.Add(label); } diff --git a/src/CodeFixes/CSharp/CodeFixes/ChangeTypeOfLocalVariableCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ChangeTypeOfLocalVariableCodeFixProvider.cs index b0b63c026a..41a9a797c5 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ChangeTypeOfLocalVariableCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ChangeTypeOfLocalVariableCodeFixProvider.cs @@ -52,14 +52,14 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ExpressionSyntax value = variableDeclarator.Initializer?.Value; - if (value == null) + if (value is null) return; SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(value, context.CancellationToken); - if (symbolInfo.Symbol != null) + if (symbolInfo.Symbol is not null) { ComputeCodeFix(context, diagnostic, variableDeclarator, symbolInfo.Symbol, semanticModel); } diff --git a/src/CodeFixes/CSharp/CodeFixes/CodeFixRegistrator.cs b/src/CodeFixes/CSharp/CodeFixes/CodeFixRegistrator.cs index 2a2f0a3e19..20d3e509a8 100644 --- a/src/CodeFixes/CSharp/CodeFixes/CodeFixRegistrator.cs +++ b/src/CodeFixes/CSharp/CodeFixes/CodeFixRegistrator.cs @@ -85,7 +85,7 @@ internal static class CodeFixRegistrator { ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(expression, context.CancellationToken).ConvertedType; - if (typeSymbol == null) + if (typeSymbol is null) return; ReplaceNullWithDefaultValue(context, diagnostic, expression, typeSymbol, additionalKey); @@ -119,7 +119,7 @@ internal static class CodeFixRegistrator TypeSyntax type = CSharpUtility.GetTypeOrReturnType(node); - if (type == null) + if (type is null) return; CodeAction codeAction = CodeActionFactory.ChangeType(context.Document, type, newTypeSymbol, semanticModel, equivalenceKey: EquivalenceKey.Create(diagnostic, additionalKey)); diff --git a/src/CodeFixes/CSharp/CodeFixes/ConditionalExpressionClauseCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ConditionalExpressionClauseCodeFixProvider.cs index 2740012aa1..44c8ef5353 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ConditionalExpressionClauseCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ConditionalExpressionClauseCodeFixProvider.cs @@ -50,7 +50,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ITypeSymbol destinationType = FindDestinationType(whenTrue, falseType.BaseType, semanticModel); - if (destinationType == null) + if (destinationType is null) return; CodeFixRegistrator.AddExplicitCast(context, diagnostic, whenTrue, destinationType, semanticModel); @@ -58,7 +58,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) private static ITypeSymbol FindDestinationType(ExpressionSyntax expression, ITypeSymbol type, SemanticModel semanticModel) { - while (type != null) + while (type is not null) { if (semanticModel.IsImplicitConversion(expression, type)) return type; diff --git a/src/CodeFixes/CSharp/CodeFixes/ElementAccessCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ElementAccessCodeFixProvider.cs index 667a8b496d..e8839c0918 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ElementAccessCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ElementAccessCodeFixProvider.cs @@ -48,7 +48,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) argumentList.Arguments, Token(closeBracket.LeadingTrivia, SyntaxKind.CloseParenToken, closeBracket.TrailingTrivia))); - if (semanticModel.GetSpeculativeMethodSymbol(elementAccess.SpanStart, invocationExpression) == null) + if (semanticModel.GetSpeculativeMethodSymbol(elementAccess.SpanStart, invocationExpression) is null) return; CodeAction codeAction = CodeAction.Create( diff --git a/src/CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs index be84e27207..7d58b39afb 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs @@ -274,7 +274,7 @@ static bool IsRightExpressionOfAssignment(ExpressionSyntax expression) { SyntaxNode invocationExpression = InvocationExpression(expression); - if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) != null) + if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) is not null) { CodeAction codeAction = CodeAction.Create( "Add argument list", @@ -315,13 +315,13 @@ static bool IsRightExpressionOfAssignment(ExpressionSyntax expression) if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceConditionalExpressionWithIfElse, context.Document, root.SyntaxTree) && (expression is ConditionalExpressionSyntax conditionalExpression) - && conditionalExpression.Condition != null) + && conditionalExpression.Condition is not null) { ExpressionSyntax whenTrue = conditionalExpression.WhenTrue; ExpressionSyntax whenFalse = conditionalExpression.WhenFalse; - if (whenTrue != null - && whenFalse != null + 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) { @@ -685,9 +685,9 @@ static bool IsRightExpressionOfAssignment(ExpressionSyntax expression) SyntaxNode nodeToRemove, SyntaxNode newNode) where TRoot : SyntaxNode { - if (newNode == null) + if (newNode is null) { - if (nodeToRemove == null) + if (nodeToRemove is null) return root; if (nodeToRemove is StatementSyntax statement) diff --git a/src/CodeFixes/CSharp/CodeFixes/ExtractDeclarationFromUsingStatementCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ExtractDeclarationFromUsingStatementCodeFixProvider.cs index 8283641130..460f291495 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ExtractDeclarationFromUsingStatementCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ExtractDeclarationFromUsingStatementCodeFixProvider.cs @@ -80,7 +80,7 @@ private static IEnumerable GetStatements(UsingStatementSyntax u { StatementSyntax statement = usingStatement.Statement; - if (statement != null) + if (statement is not null) { if (statement.IsKind(SyntaxKind.Block)) { diff --git a/src/CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs index 8ac6677d22..06787fd942 100644 --- a/src/CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs @@ -116,7 +116,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) MethodDeclarationSyntax otherPart = semanticModel.GetOtherPart(methodDeclaration, context.CancellationToken); - if (otherPart == null) + if (otherPart is null) break; CodeAction codeAction = CodeAction.Create( @@ -208,9 +208,9 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } } - SyntaxDebug.Assert(node != null, memberDeclaration); + SyntaxDebug.Assert(node is not null, memberDeclaration); - if (node == null) + if (node is null) break; ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.PartialKeyword, title: $"Make {CSharpFacts.GetTitle(node)} partial"); @@ -433,7 +433,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) CodeAction codeAction = AddParameterToInterfaceMemberRefactoring.ComputeRefactoringForExplicitImplementation(context2, memberDeclaration); - if (codeAction != null) + if (codeAction is not null) context.RegisterCodeFix(codeAction, diagnostic); break; diff --git a/src/CodeFixes/CSharp/CodeFixes/MethodDeclarationOrLocalFunctionStatementCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/MethodDeclarationOrLocalFunctionStatementCodeFixProvider.cs index edd75ba2c8..88864df16e 100644 --- a/src/CodeFixes/CSharp/CodeFixes/MethodDeclarationOrLocalFunctionStatementCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/MethodDeclarationOrLocalFunctionStatementCodeFixProvider.cs @@ -38,9 +38,9 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ? methodDeclaration.Body : ((LocalFunctionStatementSyntax)node).Body; - SyntaxDebug.Assert(body != null, node); + SyntaxDebug.Assert(body is not null, node); - if (body == null) + if (body is null) return; SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -58,7 +58,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ExpressionSyntax expression = yieldReturn.Expression; - if (expression == null) + if (expression is null) continue; var namedTypeSymbol = semanticModel.GetTypeSymbol(expression, context.CancellationToken) as INamedTypeSymbol; @@ -66,13 +66,13 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) if (namedTypeSymbol?.IsErrorType() != false) continue; - if (typeSymbol == null) + if (typeSymbol is null) { typeSymbol = namedTypeSymbol; } else { - if (typeSymbols == null) + if (typeSymbols is null) { typeSymbols = new HashSet() { typeSymbol }; } @@ -81,7 +81,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) continue; } - if (ienumerableOfTSymbol == null) + if (ienumerableOfTSymbol is null) ienumerableOfTSymbol = semanticModel.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1"); CodeFixRegistrator.ChangeTypeOrReturnType( diff --git a/src/CodeFixes/CSharp/CodeFixes/ModifiersCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ModifiersCodeFixProvider.cs index 4910e542b5..c1c200f2e7 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ModifiersCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ModifiersCodeFixProvider.cs @@ -92,9 +92,9 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) if (!CSharpFacts.CanHaveModifiers(node.Kind())) node = node.FirstAncestor(f => CSharpFacts.CanHaveModifiers(f.Kind())); - Debug.Assert(node != null, $"{nameof(node)} is null"); + Debug.Assert(node is not null, $"{nameof(node)} is null"); - if (node == null) + if (node is null) return; foreach (Diagnostic diagnostic in context.Diagnostics) @@ -508,7 +508,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) if (semanticModel.GetDiagnostic( CompilerDiagnosticIdentifiers.CS0114_MemberHidesInheritedMemberToMakeCurrentMethodOverrideThatImplementationAddOverrideKeyword, CSharpUtility.GetIdentifier(node).Span, - context.CancellationToken) != null) + context.CancellationToken) is not null) { break; } @@ -538,17 +538,17 @@ private static bool IsInterfaceMemberOrExplicitInterfaceImplementation(SyntaxNod case SyntaxKind.MethodDeclaration: { return node.IsParentKind(SyntaxKind.InterfaceDeclaration) - || ((MethodDeclarationSyntax)node).ExplicitInterfaceSpecifier != null; + || ((MethodDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; } case SyntaxKind.PropertyDeclaration: { return node.IsParentKind(SyntaxKind.InterfaceDeclaration) - || ((PropertyDeclarationSyntax)node).ExplicitInterfaceSpecifier != null; + || ((PropertyDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; } case SyntaxKind.IndexerDeclaration: { return node.IsParentKind(SyntaxKind.InterfaceDeclaration) - || ((IndexerDeclarationSyntax)node).ExplicitInterfaceSpecifier != null; + || ((IndexerDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; } case SyntaxKind.EventFieldDeclaration: { @@ -556,7 +556,7 @@ private static bool IsInterfaceMemberOrExplicitInterfaceImplementation(SyntaxNod } case SyntaxKind.EventDeclaration: { - return ((EventDeclarationSyntax)node).ExplicitInterfaceSpecifier != null; + return ((EventDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; } } diff --git a/src/CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs index 06f316579b..e8417d46f2 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs @@ -38,7 +38,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) .FindNode(context.Span, getInnermostNodeForTie: true)? .FirstAncestorOrSelf(); - if (objectCreationExpression == null) + if (objectCreationExpression is null) return; switch (diagnostic.Id) @@ -58,7 +58,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) InitializerExpressionSyntax initializer = objectCreationExpression.Initializer; - if (initializer == null) + if (initializer is null) return; SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -71,18 +71,18 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) && semanticModel.GetDiagnostic( CompilerDiagnosticIdentifiers.CS0272_PropertyOrIndexerCannotBeUsedInThisContextBecauseSetAccessorIsAccessible, assignment.Left.Span, - context.CancellationToken) != null) + context.CancellationToken) is not null) { (expressions ??= new List()).Add(expression); } } - if (expressions == null) + if (expressions is null) return; TypeSyntax type = objectCreationExpression.Type; - if (argumentList == null) + if (argumentList is null) { argumentList = ArgumentList().WithTrailingTrivia(type.GetTrailingTrivia()); type = type.WithoutTrailingTrivia(); diff --git a/src/CodeFixes/CSharp/CodeFixes/ObjectReferenceIsRequiredForNonStaticMemberCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ObjectReferenceIsRequiredForNonStaticMemberCodeFixProvider.cs index 1e78a229e4..848b27c155 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ObjectReferenceIsRequiredForNonStaticMemberCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ObjectReferenceIsRequiredForNonStaticMemberCodeFixProvider.cs @@ -30,7 +30,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) Diagnostic diagnostic = context.Diagnostics[0]; - for (SyntaxNode parent = node.Parent; parent != null; parent = parent.Parent) + for (SyntaxNode parent = node.Parent; parent is not null; parent = parent.Parent) { if (parent is MemberDeclarationSyntax memberDeclaration) { @@ -84,12 +84,12 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { ISymbol symbol = semanticModel.GetSymbol(node, context.CancellationToken); - if (symbol == null) + if (symbol is null) return; SyntaxNode syntax = symbol.GetSyntaxOrDefault(context.CancellationToken); - if (syntax == null) + if (syntax is null) return; if (syntax.IsKind(SyntaxKind.VariableDeclarator)) diff --git a/src/CodeFixes/CSharp/CodeFixes/OperatorDeclarationCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/OperatorDeclarationCodeFixProvider.cs index 447bb7ac73..0c2eed1159 100644 --- a/src/CodeFixes/CSharp/CodeFixes/OperatorDeclarationCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/OperatorDeclarationCodeFixProvider.cs @@ -42,7 +42,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) SyntaxToken newToken = SyntaxFactory.Token(token.LeadingTrivia, matchingKind, token.TrailingTrivia); - if (operatorDeclaration.BodyOrExpressionBody() == null) + if (operatorDeclaration.BodyOrExpressionBody() is null) return; if (operatorDeclaration.Parent is not TypeDeclarationSyntax typeDeclaration) diff --git a/src/CodeFixes/CSharp/CodeFixes/ReturnStatementCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ReturnStatementCodeFixProvider.cs index fad5c673ba..88f0fce73b 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ReturnStatementCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ReturnStatementCodeFixProvider.cs @@ -46,7 +46,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ExpressionSyntax expression = returnStatement.Expression; - if (expression != null) + if (expression is not null) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); diff --git a/src/CodeFixes/CSharp/CodeFixes/ReturnTypeOfAsyncMethodMustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ReturnTypeOfAsyncMethodMustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs index 9aa727553a..128979d713 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ReturnTypeOfAsyncMethodMustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ReturnTypeOfAsyncMethodMustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs @@ -37,7 +37,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) var methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(node, context.CancellationToken); - SyntaxDebug.Assert(methodSymbol != null, node); + SyntaxDebug.Assert(methodSymbol is not null, node); ITypeSymbol typeSymbol = methodSymbol.ReturnType; @@ -69,7 +69,7 @@ private static (bool containsReturnAwait, bool containsAwaitStatement) AnalyzeAw { ArrowExpressionClauseSyntax expressionBody = methodDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) return (expressionBody.Expression?.Kind() == SyntaxKind.AwaitExpression, false); node = methodDeclaration.Body; @@ -80,13 +80,13 @@ private static (bool containsReturnAwait, bool containsAwaitStatement) AnalyzeAw ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) return (expressionBody.Expression?.Kind() == SyntaxKind.AwaitExpression, false); node = localFunction.Body; } - if (node == null) + if (node is null) return (false, false); var containsReturnAwait = false; diff --git a/src/CodeFixes/CSharp/CodeFixes/SimpleNameCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/SimpleNameCodeFixProvider.cs index 64fa11bfec..4dbf6ce38b 100644 --- a/src/CodeFixes/CSharp/CodeFixes/SimpleNameCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/SimpleNameCodeFixProvider.cs @@ -77,7 +77,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { ExpressionSyntax expression = arrayCreation.Initializer?.Expressions.FirstOrDefault(); - if (expression != null) + if (expression is not null) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -104,7 +104,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { ExpressionSyntax expression = GetReturnExpression(simpleName); - if (expression != null) + if (expression is not null) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -124,7 +124,7 @@ private static ExpressionSyntax GetReturnExpression(SyntaxNode node) { ExpressionSyntax expression = methodDeclaration.ExpressionBody?.Expression; - if (expression != null) + if (expression is not null) return expression; StatementSyntax statement = methodDeclaration.Body?.SingleNonBlockStatementOrDefault(); @@ -140,7 +140,7 @@ private static ExpressionSyntax GetReturnExpression(SyntaxNode node) { ExpressionSyntax expression = localFunction.ExpressionBody?.Expression; - if (expression != null) + if (expression is not null) return expression; StatementSyntax statement = localFunction.Body?.SingleNonBlockStatementOrDefault(); diff --git a/src/CodeFixes/CSharp/CodeFixes/SyntaxErrorCharExpectedCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/SyntaxErrorCharExpectedCodeFixProvider.cs index 7b93c7474e..08f44b1f9d 100644 --- a/src/CodeFixes/CSharp/CodeFixes/SyntaxErrorCharExpectedCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/SyntaxErrorCharExpectedCodeFixProvider.cs @@ -34,7 +34,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ExpressionSyntax expression = root.FindNode(context.Span).FirstAncestorOrSelf(); - if (expression == null) + if (expression is null) return; int position = -1; diff --git a/src/CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs index 6504a64411..cc7d368db0 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs @@ -118,7 +118,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ExpressionSyntax value = parameter.Default?.Value; - if (value == null) + if (value is null) break; if (value.IsKind(SyntaxKind.NullLiteralExpression)) @@ -162,7 +162,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) ISymbol symbol = semanticModel.GetEnclosingSymbol(token.SpanStart, context.CancellationToken); - if (symbol == null) + if (symbol is null) break; SymbolKind symbolKind = symbol.Kind; @@ -193,7 +193,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) Debug.Fail(symbolKind.ToString()); } - if (typeSymbol == null) + if (typeSymbol is null) break; if (typeSymbol.Kind == SymbolKind.ErrorType) @@ -280,7 +280,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { BlockSyntax body = methodDeclaration.Body; - if (body == null) + if (body is null) break; CodeAction codeAction = CodeAction.Create( @@ -308,7 +308,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { AccessorListSyntax accessorList = propertyDeclaration.AccessorList; - if (accessorList == null) + if (accessorList is null) break; CodeAction codeAction = CodeAction.Create( @@ -336,7 +336,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { BlockSyntax body = accessorDeclaration.Body; - if (body == null) + if (body is null) break; CodeAction codeAction = CodeAction.Create( diff --git a/src/CodeFixes/CSharp/CodeFixes/TypeDoesNotContainDefinitionCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TypeDoesNotContainDefinitionCodeFixProvider.cs index d7746ce314..118d823c2c 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TypeDoesNotContainDefinitionCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TypeDoesNotContainDefinitionCodeFixProvider.cs @@ -132,11 +132,11 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) string newName = GetNewName(); - if (newName != null) + if (newName is not null) { ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, context.CancellationToken); - if (typeSymbol != null) + if (typeSymbol is not null) { if (typeSymbol is IArrayTypeSymbol arrayType) typeSymbol = arrayType.ElementType; diff --git a/src/CodeFixes/CSharp/CodeFixes/TypeParameterCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TypeParameterCodeFixProvider.cs index 7e1fb2628a..9b1609279a 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TypeParameterCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TypeParameterCodeFixProvider.cs @@ -48,7 +48,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) TypeParameterConstraintClauseSyntax constraintClause = genericInfo.FindConstraintClause(name); - if (constraintClause != null) + if (constraintClause is not null) newGenericInfo = newGenericInfo.RemoveConstraintClause(constraintClause); return context.Document.ReplaceNodeAsync(genericInfo.Node, newGenericInfo.Node, ct); diff --git a/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintClauseCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintClauseCodeFixProvider.cs index 8136b3ba80..bdb717613d 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintClauseCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintClauseCodeFixProvider.cs @@ -73,7 +73,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) TypeParameterConstraintClauseSyntax constraintClause2 = genericInfo.FindConstraintClause(name); - if (constraintClause2 == null) + if (constraintClause2 is null) break; CodeAction codeAction = CodeAction.Create( diff --git a/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintCodeFixProvider.cs index ec42431d80..413134a4cd 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintCodeFixProvider.cs @@ -97,12 +97,12 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) TypeParameterConstraintSyntax classConstraint = constraintInfo.Constraints.Find(SyntaxKind.ClassConstraint); - if (classConstraint != null) + if (classConstraint is not null) RemoveConstraint(context, diagnostic, classConstraint); TypeParameterConstraintSyntax structConstraint = constraintInfo.Constraints.Find(SyntaxKind.StructConstraint); - if (structConstraint != null) + if (structConstraint is not null) RemoveConstraint(context, diagnostic, structConstraint); break; diff --git a/src/CodeFixes/CSharp/CodeFixes/UnreachableCodeCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/UnreachableCodeCodeFixProvider.cs index 9740e1be4c..346fa54ea4 100644 --- a/src/CodeFixes/CSharp/CodeFixes/UnreachableCodeCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/UnreachableCodeCodeFixProvider.cs @@ -46,7 +46,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) CodeAction codeAction = CreateCodeActionForIfElse(context.Document, diagnostic, statement.Parent); - if (codeAction != null) + if (codeAction is not null) { context.RegisterCodeFix(codeAction, diagnostic); return; @@ -95,7 +95,7 @@ private CodeAction CreateCodeActionForIfElse(Document document, Diagnostic diagn ElseClauseSyntax elseClause = ifStatement.Else; - if (elseClause != null + if (elseClause is not null && ifStatement.IsParentKind(SyntaxKind.ElseClause)) { return CodeAction.Create( @@ -106,7 +106,7 @@ private CodeAction CreateCodeActionForIfElse(Document document, Diagnostic diagn StatementSyntax statement = elseClause?.Statement; - if (statement != null) + if (statement is not null) { if (statement is BlockSyntax block) { @@ -140,7 +140,7 @@ private CodeAction CreateCodeActionForIfElse(Document document, Diagnostic diagn { StatementSyntax statement = ifStatement.Statement; - if (statement != null) + if (statement is not null) { if (statement is BlockSyntax block) { diff --git a/src/CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs index 568b69ed11..7ec13b63ea 100644 --- a/src/CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs @@ -89,12 +89,12 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) VariableDeclaratorSyntax variableDeclarator = variableDeclaration.Variables.SingleOrDefault(shouldThrow: false); - if (variableDeclarator == null) + if (variableDeclarator is null) break; ExpressionSyntax value = variableDeclarator.Initializer?.Value; - if (value == null) + if (value is null) break; SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); diff --git a/src/CodeFixes/CSharp/Refactorings/ChangeMemberTypeRefactoring.cs b/src/CodeFixes/CSharp/Refactorings/ChangeMemberTypeRefactoring.cs index 3a4ba34da8..81ea991e95 100644 --- a/src/CodeFixes/CSharp/Refactorings/ChangeMemberTypeRefactoring.cs +++ b/src/CodeFixes/CSharp/Refactorings/ChangeMemberTypeRefactoring.cs @@ -24,7 +24,7 @@ internal static class ChangeMemberTypeRefactoring ITypeSymbol expressionTypeSymbol = typeInfo.Type; - if (expressionTypeSymbol == null) + if (expressionTypeSymbol is null) return; if (!expressionTypeSymbol.SupportsExplicitDeclaration()) @@ -32,9 +32,9 @@ internal static class ChangeMemberTypeRefactoring (ISymbol symbol, ITypeSymbol typeSymbol) = GetContainingSymbolAndType(expression, semanticModel, context.CancellationToken); - SyntaxDebug.Assert(symbol != null, expression); + SyntaxDebug.Assert(symbol is not null, expression); - if (symbol == null) + if (symbol is null) return; if (symbol.IsOverride) @@ -50,7 +50,7 @@ internal static class ChangeMemberTypeRefactoring TypeSyntax type = CSharpUtility.GetTypeOrReturnType(node); - if (type == null) + if (type is null) return; ITypeSymbol newTypeSymbol = expressionTypeSymbol; @@ -67,7 +67,7 @@ internal static class ChangeMemberTypeRefactoring INamedTypeSymbol taskOfT = semanticModel.GetTypeByMetadataName("System.Threading.Tasks.Task`1"); - if (taskOfT == null) + if (taskOfT is null) return; if (expression.Kind() == SyntaxKind.AwaitExpression) @@ -193,7 +193,7 @@ internal static class ChangeMemberTypeRefactoring } if (methodKind == MethodKind.Ordinary - && methodSymbol.PartialImplementationPart != null) + && methodSymbol.PartialImplementationPart is not null) { methodSymbol = methodSymbol.PartialImplementationPart; } diff --git a/src/CodeFixes/CSharp/Refactorings/ChangeTypeAccordingToInitializerRefactoring.cs b/src/CodeFixes/CSharp/Refactorings/ChangeTypeAccordingToInitializerRefactoring.cs index 32e05ba1c1..84fabdac20 100644 --- a/src/CodeFixes/CSharp/Refactorings/ChangeTypeAccordingToInitializerRefactoring.cs +++ b/src/CodeFixes/CSharp/Refactorings/ChangeTypeAccordingToInitializerRefactoring.cs @@ -98,7 +98,7 @@ CodeFixRegistrationResult ComputeChangeTypeAndAddAwait() semanticModel, context.CancellationToken); - if (createChangedDocument == null) + if (createChangedDocument is null) return default; ITypeSymbol typeArgument = ((INamedTypeSymbol)typeSymbol).TypeArguments[0]; @@ -123,7 +123,7 @@ CodeFixRegistrationResult ComputeChangeTypeAndAddAwait() { TypeSyntax type = propertyDeclaration.Type; - if (type == null) + if (type is null) return default; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, context.CancellationToken); diff --git a/src/CodeFixes/CodeFixMap.cs b/src/CodeFixes/CodeFixMap.cs index 2c5ab70990..4ffd9e01a1 100644 --- a/src/CodeFixes/CodeFixMap.cs +++ b/src/CodeFixes/CodeFixMap.cs @@ -55,7 +55,7 @@ public static IEnumerable GetCompilerDiagnosticFixes() { get { - if (_codeFixDescriptorsById == null) + if (_codeFixDescriptorsById is null) Interlocked.CompareExchange(ref _codeFixDescriptorsById, LoadCodeFixDescriptorsById(), null); return _codeFixDescriptorsById; @@ -76,7 +76,7 @@ public static IEnumerable GetCompilerDiagnosticFixes() { get { - if (_codeFixDescriptorsByCompilerDiagnosticId == null) + if (_codeFixDescriptorsByCompilerDiagnosticId is null) Interlocked.CompareExchange(ref _codeFixDescriptorsByCompilerDiagnosticId, LoadCodeFixDescriptorsByCompilerDiagnosticId(), null); return _codeFixDescriptorsByCompilerDiagnosticId; @@ -99,7 +99,7 @@ public static IEnumerable GetCompilerDiagnosticFixes() { get { - if (_compilerDiagnosticsById == null) + if (_compilerDiagnosticsById is null) Interlocked.CompareExchange(ref _compilerDiagnosticsById, LoadCompilerDiagnosticsById(), null); return _compilerDiagnosticsById; diff --git a/src/CodeFixes/CodeFixes/CodeFixIdentifier.cs b/src/CodeFixes/CodeFixes/CodeFixIdentifier.cs index 4d901d590c..3bedd5ca08 100644 --- a/src/CodeFixes/CodeFixes/CodeFixIdentifier.cs +++ b/src/CodeFixes/CodeFixes/CodeFixIdentifier.cs @@ -26,7 +26,7 @@ public CodeFixIdentifier(string compilerDiagnosticId, string codeFixId) public bool IsDefault { - get { return CompilerDiagnosticId == null && CodeFixId == null; } + get { return CompilerDiagnosticId is null && CodeFixId is null; } } public static CodeFixIdentifier Parse(string text) @@ -43,7 +43,7 @@ public static bool TryParse(string text, out CodeFixIdentifier codeFixIdentifier private static CodeFixIdentifier Parse(string text, bool shouldThrow) { - if (text == null) + if (text is null) { if (shouldThrow) throw new ArgumentNullException(nameof(text)); @@ -99,9 +99,9 @@ public override int GetHashCode() public override string ToString() { - if (CompilerDiagnosticId != null) + if (CompilerDiagnosticId is not null) { - if (CodeFixId != null) + if (CodeFixId is not null) { return CompilerDiagnosticId + "." + CodeFixId; } @@ -110,7 +110,7 @@ public override string ToString() return CompilerDiagnosticId; } } - else if (CodeFixId != null) + else if (CodeFixId is not null) { return CodeFixId; } @@ -130,7 +130,7 @@ public int CompareTo(CodeFixIdentifier other) public int CompareTo(object obj) { - if (obj == null) + if (obj is null) return 1; if (obj is CodeFixIdentifier other) diff --git a/src/CodeFixes/CodeFixes/CompilerCodeFixOptions.cs b/src/CodeFixes/CodeFixes/CompilerCodeFixOptions.cs index 9b7c4d2d58..9930d61941 100644 --- a/src/CodeFixes/CodeFixes/CompilerCodeFixOptions.cs +++ b/src/CodeFixes/CodeFixes/CompilerCodeFixOptions.cs @@ -24,7 +24,7 @@ private static CompilerCodeFixOptions LoadSettings() protected override void SetValues(CodeAnalysisConfig configuration) { - if (configuration == null) + if (configuration is null) return; foreach (KeyValuePair kvp in configuration.CodeFixes) diff --git a/src/CommandLine/AssemblyFactory.cs b/src/CommandLine/AssemblyFactory.cs index 0552152304..fffaf69365 100644 --- a/src/CommandLine/AssemblyFactory.cs +++ b/src/CommandLine/AssemblyFactory.cs @@ -106,7 +106,7 @@ public static Assembly FromSyntaxTree(SyntaxTree syntaxTree, TextSpan? expressio ImmutableArray diagnostics = compilation.GetDiagnostics(); - if (expressionSpan != null) + if (expressionSpan is not null) { foreach (Diagnostic diagnostic in diagnostics) { @@ -154,7 +154,7 @@ public static Assembly FromSyntaxTree(SyntaxTree syntaxTree, TextSpan? expressio private static void WriteDiagnostic(Diagnostic diagnostic, TextSpan? expressionSpan = null) { string location; - if (expressionSpan != null) + if (expressionSpan is not null) { location = $"1,{diagnostic.Location.SourceSpan.Start - expressionSpan.Value.Start + 1}"; } diff --git a/src/CommandLine/AssemblyResolver.cs b/src/CommandLine/AssemblyResolver.cs index c5d2cf68f8..9b21392930 100644 --- a/src/CommandLine/AssemblyResolver.cs +++ b/src/CommandLine/AssemblyResolver.cs @@ -46,7 +46,7 @@ private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEven { Assembly assembly = FindLoadedAssembly(); - if (assembly != null) + if (assembly is not null) return assembly; break; @@ -76,7 +76,7 @@ Assembly FindLoadedAssembly() if (assemblyName.Name == an.Name && assemblyName.Version <= an.Version) { - if (result == null) + if (result is null) { result = assembly; } diff --git a/src/CommandLine/Commands/AnalyzeAssemblyCommand.cs b/src/CommandLine/Commands/AnalyzeAssemblyCommand.cs index 289ec6e0ac..f524e31168 100644 --- a/src/CommandLine/Commands/AnalyzeAssemblyCommand.cs +++ b/src/CommandLine/Commands/AnalyzeAssemblyCommand.cs @@ -78,7 +78,7 @@ public CommandStatus Execute(AnalyzeAssemblyCommandLineOptions options) if (analyzerAssemblies.Length > 0) { - CultureInfo culture = (options.Culture != null) ? CultureInfo.GetCultureInfo(options.Culture) : null; + CultureInfo culture = (options.Culture is not null) ? CultureInfo.GetCultureInfo(options.Culture) : null; foreach (string path in options.Output) { @@ -243,7 +243,7 @@ private static void WriteCodeFixProviders(IEnumerable fixers) FixAllProvider fixAllProvider = fixer.GetFixAllProvider(); - if (fixAllProvider != null) + if (fixAllProvider is not null) { WriteLine($"{fixAllProvider.GetType().FullName} ({string.Join(", ", fixAllProvider.GetSupportedFixAllScopes().Select(f => f.ToString()).OrderBy(f => f))})", ConsoleColors.DarkGray, Verbosity.Diagnostic); } @@ -269,7 +269,7 @@ private static void WriteCodeFixProviders(IEnumerable fixers) void WriteDiagnostic(string diagnosticId, DiagnosticDescriptor descriptor) { - if (descriptor == null) + if (descriptor is null) { WriteLine($" {diagnosticId}", Verbosity.Detailed); } diff --git a/src/CommandLine/Commands/AnalyzeCommand.cs b/src/CommandLine/Commands/AnalyzeCommand.cs index 9bf846053f..a465a6cf70 100644 --- a/src/CommandLine/Commands/AnalyzeCommand.cs +++ b/src/CommandLine/Commands/AnalyzeCommand.cs @@ -43,7 +43,7 @@ public override async Task ExecuteAsync(ProjectOrSolution IEnumerable analyzerAssemblies = Options.AnalyzerAssemblies .SelectMany(path => AnalyzerAssemblyLoader.LoadFrom(path, loadFixers: false).Select(info => info.AnalyzerAssembly)); - CultureInfo culture = (Options.Culture != null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; + CultureInfo culture = (Options.Culture is not null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; var analyzerLoader = new AnalyzerLoader(analyzerAssemblies, codeAnalyzerOptions); @@ -95,10 +95,10 @@ protected override void ProcessResults(IList results) if (results.Count > 1) WriteAnalysisResults(analysisResults); - if (Options.Output != null + if (Options.Output is not null && analysisResults.Any(f => f.Diagnostics.Any())) { - CultureInfo culture = (Options.Culture != null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; + CultureInfo culture = (Options.Culture is not null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; DiagnosticXmlSerializer.Serialize(analysisResults, Options.Output, culture); } diff --git a/src/CommandLine/Commands/FindSymbolsCommand.cs b/src/CommandLine/Commands/FindSymbolsCommand.cs index c21aad41b9..435fa665f7 100644 --- a/src/CommandLine/Commands/FindSymbolsCommand.cs +++ b/src/CommandLine/Commands/FindSymbolsCommand.cs @@ -90,7 +90,7 @@ public override async Task ExecuteAsync(ProjectOrSolution project ImmutableDictionary symbolsById = ignoredSymbolIds .Select(f => (id: f, symbol: DocumentationCommentId.GetFirstSymbolForDeclarationId(f, compilation))) - .Where(f => f.id != null) + .Where(f => f.id is not null) .ToImmutableDictionary(f => f.id, f => f.symbol); ignoredSymbolIds.ExceptWith(symbolsById.Select(f => f.Key)); diff --git a/src/CommandLine/Commands/FixCommand.cs b/src/CommandLine/Commands/FixCommand.cs index 5525a79d31..387e5d2d6a 100644 --- a/src/CommandLine/Commands/FixCommand.cs +++ b/src/CommandLine/Commands/FixCommand.cs @@ -65,7 +65,7 @@ public override async Task ExecuteAsync(ProjectOrSolution proj IEnumerable analyzerAssemblies = Options.AnalyzerAssemblies .SelectMany(path => AnalyzerAssemblyLoader.LoadFrom(path).Select(info => info.AnalyzerAssembly)); - CultureInfo culture = (Options.Culture != null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; + CultureInfo culture = (Options.Culture is not null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; var projectFilter = new ProjectFilter(Options.Projects, Options.IgnoredProjects, Language); diff --git a/src/CommandLine/Commands/GenerateSourceReferencesCommand.cs b/src/CommandLine/Commands/GenerateSourceReferencesCommand.cs index 532eff96ec..ccf8547451 100644 --- a/src/CommandLine/Commands/GenerateSourceReferencesCommand.cs +++ b/src/CommandLine/Commands/GenerateSourceReferencesCommand.cs @@ -118,7 +118,7 @@ private void WriteSymbol(XmlWriter writer, ISymbol symbol, CancellationToken can if (Path.DirectorySeparatorChar == '\\') path = path.Replace(Path.DirectorySeparatorChar, '/'); - Debug.Assert(path != null, symbol.ToDisplayString()); + Debug.Assert(path is not null, symbol.ToDisplayString()); writer.WriteAttributeString("path", path); diff --git a/src/CommandLine/Commands/HelpCommand.cs b/src/CommandLine/Commands/HelpCommand.cs index 69f8d3e5ac..93f596b8dd 100644 --- a/src/CommandLine/Commands/HelpCommand.cs +++ b/src/CommandLine/Commands/HelpCommand.cs @@ -53,11 +53,11 @@ public CommandStatus Execute() { OpenHelpInBrowser(commandName); } - else if (commandName != null) + else if (commandName is not null) { Command command = CommandLoader.LoadCommand(typeof(HelpCommand).Assembly, commandName); - if (command == null) + if (command is null) throw new InvalidOperationException($"Command '{commandName}' does not exist."); WriteCommandHelp(command, includeValues: includeValues, filter: filter); diff --git a/src/CommandLine/Commands/ListReferencesCommand.cs b/src/CommandLine/Commands/ListReferencesCommand.cs index a43111960b..e133ad89b8 100644 --- a/src/CommandLine/Commands/ListReferencesCommand.cs +++ b/src/CommandLine/Commands/ListReferencesCommand.cs @@ -42,7 +42,7 @@ public override async Task ExecuteAsync(ProjectOrSolution project foreach (string display in compilations .SelectMany(compilation => compilation.ExternalReferences.Select(reference => (compilation, reference))) .Select(f => GetDisplay(f.compilation, f.reference)) - .Where(f => f != null) + .Where(f => f is not null) .Distinct() .OrderBy(f => f, StringComparer.InvariantCulture)) { diff --git a/src/CommandLine/Commands/ListSymbolsCommand.cs b/src/CommandLine/Commands/ListSymbolsCommand.cs index 337a8ff87f..61386d7090 100644 --- a/src/CommandLine/Commands/ListSymbolsCommand.cs +++ b/src/CommandLine/Commands/ListSymbolsCommand.cs @@ -75,11 +75,11 @@ public override async Task ExecuteAsync(ProjectOrSolution project { hierarchyRoot = compilation.GetTypeByMetadataName(Options.HierarchyRoot); - if (hierarchyRoot != null) + if (hierarchyRoot is not null) break; } - if (hierarchyRoot == null) + if (hierarchyRoot is null) { WriteLine($"Cannot find type '{Options.HierarchyRoot}'", Verbosity.Quiet); return CommandResults.Fail; @@ -94,7 +94,7 @@ public override async Task ExecuteAsync(ProjectOrSolution project { IAssemblySymbol externalAssembly = FindExternalAssembly(compilations, reference); - if (externalAssembly == null) + if (externalAssembly is null) { WriteLine($"Cannot find external assembly '{reference}'", Verbosity.Quiet); return CommandResults.Fail; @@ -103,7 +103,7 @@ public override async Task ExecuteAsync(ProjectOrSolution project (externalAssemblies ??= new HashSet()).Add(externalAssembly); } - if (externalAssemblies != null) + if (externalAssemblies is not null) assemblies = assemblies.Concat(externalAssemblies); string text = null; diff --git a/src/CommandLine/Commands/LogicalLinesOfCodeCommand.cs b/src/CommandLine/Commands/LogicalLinesOfCodeCommand.cs index 3713564bc4..145949afc4 100644 --- a/src/CommandLine/Commands/LogicalLinesOfCodeCommand.cs +++ b/src/CommandLine/Commands/LogicalLinesOfCodeCommand.cs @@ -35,7 +35,7 @@ public override async Task ExecuteAsync(ProjectOrSolut ICodeMetricsService service = MefWorkspaceServices.Default.GetService(project.Language); - if (service != null) + if (service is not null) { codeMetrics = await CountLogicalLinesAsync(project, service, codeMetricsOptions, cancellationToken); } diff --git a/src/CommandLine/Commands/MSBuildWorkspaceCommand.cs b/src/CommandLine/Commands/MSBuildWorkspaceCommand.cs index 6d8c43b0fb..4c6eb3b6f2 100644 --- a/src/CommandLine/Commands/MSBuildWorkspaceCommand.cs +++ b/src/CommandLine/Commands/MSBuildWorkspaceCommand.cs @@ -33,7 +33,7 @@ public string Language public async Task ExecuteAsync(IEnumerable paths, string msbuildPath = null, IEnumerable properties = null) { - if (paths == null) + if (paths is null) throw new ArgumentNullException(nameof(paths)); if (!paths.Any()) @@ -45,7 +45,7 @@ public async Task ExecuteAsync(IEnumerable paths, string { workspace = CreateMSBuildWorkspace(msbuildPath, properties); - if (workspace == null) + if (workspace is null) return CommandStatus.Fail; workspace.WorkspaceFailed += (sender, args) => WorkspaceFailed(sender, args); @@ -105,7 +105,7 @@ public async Task ExecuteAsync(IEnumerable paths, string { OperationCanceledException operationCanceledException = ex.GetOperationCanceledException(); - if (operationCanceledException != null) + if (operationCanceledException is not null) { OperationCanceled(operationCanceledException); } @@ -130,14 +130,14 @@ private async Task ExecuteAsync(string path, MSBuildWorkspace wo TCommandResult result = await ExecuteAsync(path, workspace, ConsoleProgressReporter.Default, cancellationToken); - if (result != null) + if (result is not null) return result; ProjectOrSolution projectOrSolution = await OpenProjectOrSolutionAsync(path, workspace, ConsoleProgressReporter.Default, cancellationToken); Solution solution = projectOrSolution.AsSolution(); - if (solution != null + if (solution is not null && !VerifyProjectNames(solution)) { return null; @@ -162,7 +162,7 @@ private bool VerifyProjectNames(Solution solution) foreach (string moniker in grouping .Select(f => f.Moniker) - .Where(f => f != null) + .Where(f => f is not null) .OrderBy(f => f)) { WriteLine($" {moniker}", Verbosity.Detailed); @@ -245,7 +245,7 @@ protected virtual void WorkspaceFailed(object sender, WorkspaceDiagnosticEventAr private static MSBuildWorkspace CreateMSBuildWorkspace(string msbuildPath, IEnumerable rawProperties) { - if (msbuildPath != null) + if (msbuildPath is not null) { MSBuildLocator.RegisterMSBuildPath(msbuildPath); } @@ -264,7 +264,7 @@ private static MSBuildWorkspace CreateMSBuildWorkspace(string msbuildPath, IEnum if (!ParseHelpers.TryParseMSBuildProperties(rawProperties, out Dictionary properties)) return null; - if (properties == null) + if (properties is null) properties = new Dictionary(); // https://github.com/Microsoft/MSBuildLocator/issues/16 @@ -330,7 +330,7 @@ private static bool TryGetVisualStudioInstance(out VisualStudioInstance instance { Workspace workspace = solution.Workspace; - foreach (ProjectId projectId in (getProjects != null) ? getProjects(solution) : solution.ProjectIds) + foreach (ProjectId projectId in (getProjects is not null) ? getProjects(solution) : solution.ProjectIds) { Project project = workspace.CurrentSolution.GetProject(projectId); @@ -415,20 +415,20 @@ public void Report(ProjectLoadProgress value) { string targetFramework = value.TargetFramework; - if (targetFramework != null) + if (targetFramework is not null) text += $" ({targetFramework})"; - if (Projects != null) + if (Projects is not null) { if (!Projects.TryGetValue(value.FilePath, out List targetFrameworks)) { - if (targetFramework != null) + if (targetFramework is not null) targetFrameworks = new List(); Projects[value.FilePath] = targetFrameworks; } - if (targetFramework != null) + if (targetFramework is not null) targetFrameworks.Add(targetFramework); } } diff --git a/src/CommandLine/Commands/MigrateCommand.cs b/src/CommandLine/Commands/MigrateCommand.cs index b5eaf8b0c2..1ff910971f 100644 --- a/src/CommandLine/Commands/MigrateCommand.cs +++ b/src/CommandLine/Commands/MigrateCommand.cs @@ -75,7 +75,7 @@ public CommandStatus Execute() { OperationCanceledException operationCanceledException = ex.GetOperationCanceledException(); - if (operationCanceledException != null) + if (operationCanceledException is not null) { OperationCanceled(operationCanceledException); } @@ -220,7 +220,7 @@ private CommandStatus ExecuteProject(string path, XDocument document) { string packageId = e.Attribute("Include")?.Value; - if (packageId == null) + if (packageId is null) continue; if (packageId == "Roslynator.Formatting.Analyzers") @@ -230,20 +230,20 @@ private CommandStatus ExecuteProject(string path, XDocument document) analyzers = e; } - if (analyzers == null) + if (analyzers is null) continue; - if (formattingAnalyzers != null) + if (formattingAnalyzers is not null) { string versionText = formattingAnalyzers.Attribute("Version")?.Value; - if (versionText == null) + if (versionText is null) { WriteXmlError(formattingAnalyzers, "Version attribute not found"); continue; } - if (versionText != null) + if (versionText is not null) { Match match = _versionRegex.Match(versionText); @@ -269,7 +269,7 @@ private CommandStatus ExecuteProject(string path, XDocument document) } } - if (formattingAnalyzers != null) + if (formattingAnalyzers is not null) { var message = new LogMessage("Update package 'Roslynator.Formatting.Analyzers' to '1.0.0'", Colors.Message_OK, Verbosity.Normal); @@ -286,7 +286,7 @@ private CommandStatus ExecuteProject(string path, XDocument document) XText whitespace = null; if (analyzers.NodesBeforeSelf().LastOrDefault() is XText xtext - && xtext != null + && xtext is not null && string.IsNullOrWhiteSpace(xtext.Value)) { whitespace = xtext; @@ -296,7 +296,7 @@ private CommandStatus ExecuteProject(string path, XDocument document) } } - if (messages != null) + if (messages is not null) { WriteUpdateMessages(path, messages); @@ -339,7 +339,7 @@ private CommandStatus ExecuteRuleSet(string path) { string id = element.Attribute("Id")?.Value; - if (id != null) + if (id is not null) ids[id] = element; } @@ -347,7 +347,7 @@ private CommandStatus ExecuteRuleSet(string path) XElement formattingAnalyzers = rules.FirstOrDefault(f => f.Attribute("AnalyzerId")?.Value == "Roslynator.Formatting.Analyzers"); - if (formattingAnalyzers == null) + if (formattingAnalyzers is null) { formattingAnalyzers = new XElement( "Rules", @@ -381,12 +381,12 @@ private CommandStatus ExecuteRuleSet(string path) formattingAnalyzers.Add(newRule); - if (kvp.Value.Parent != null) + if (kvp.Value.Parent is not null) kvp.Value.Remove(); } } - if (messages != null) + if (messages is not null) { WriteUpdateMessages(path, messages); @@ -478,7 +478,7 @@ private CommandStatus ExecuteEditorConfig(string path) return newValue; }); - if (messages != null) + if (messages is not null) { WriteUpdateMessages(path, messages); @@ -529,7 +529,7 @@ protected virtual void OperationCanceled(OperationCanceledException ex) { Encoding encodingFromBom = EncodingHelpers.DetectEncoding(stream); - if (encodingFromBom != null) + if (encodingFromBom is not null) encoding = encodingFromBom; stream.Position = 0; @@ -537,7 +537,7 @@ protected virtual void OperationCanceled(OperationCanceledException ex) using (var reader = new StreamReader( stream, encoding ?? Encodings.UTF8NoBom, - detectEncodingFromByteOrderMarks: encodingFromBom == null)) + detectEncodingFromByteOrderMarks: encodingFromBom is null)) { return reader.ReadToEnd(); } diff --git a/src/CommandLine/Commands/PhysicalLinesOfCodeCommand.cs b/src/CommandLine/Commands/PhysicalLinesOfCodeCommand.cs index 96fda2450b..1034885247 100644 --- a/src/CommandLine/Commands/PhysicalLinesOfCodeCommand.cs +++ b/src/CommandLine/Commands/PhysicalLinesOfCodeCommand.cs @@ -40,7 +40,7 @@ public override async Task ExecuteAsync(ProjectOrSolut ICodeMetricsService service = MefWorkspaceServices.Default.GetService(project.Language); - if (service != null) + if (service is not null) { codeMetrics = await CountLinesAsync(project, service, codeMetricsOptions, cancellationToken); } diff --git a/src/CommandLine/Commands/SlnListCommand.cs b/src/CommandLine/Commands/SlnListCommand.cs index b03aa48847..24a6215c34 100644 --- a/src/CommandLine/Commands/SlnListCommand.cs +++ b/src/CommandLine/Commands/SlnListCommand.cs @@ -63,10 +63,10 @@ public override Task ExecuteAsync(ProjectOrSolution projectOrSolu { List frameworks = f.Value; - return (frameworks != null) ? $"({string.Join(", ", frameworks)})".Length : 0; + return (frameworks is not null) ? $"({string.Join(", ", frameworks)})".Length : 0; }); - bool anyHasTargetFrameworks = projects.Any(f => f.Value != null); + bool anyHasTargetFrameworks = projects.Any(f => f.Value is not null); WriteLine(); WriteLine($"{projects.Count} {((projects.Count == 1) ? "project" : "projects")} found in solution '{Path.GetFileNameWithoutExtension(solutionInfo.FilePath)}' [{solutionInfo.FilePath}]", ConsoleColors.Green, Verbosity.Minimal); @@ -86,7 +86,7 @@ public override Task ExecuteAsync(ProjectOrSolution projectOrSolu if (anyHasTargetFrameworks) Write(" ", Verbosity.Normal); - if (targetFrameworks != null) + if (targetFrameworks is not null) { string targetFrameworksText = $"({string.Join(", ", targetFrameworks.OrderBy(f => f))})"; Write(targetFrameworksText.PadRight(targetFrameworksMaxLength), Verbosity.Normal); diff --git a/src/CommandLine/Commands/SpellcheckCommand.cs b/src/CommandLine/Commands/SpellcheckCommand.cs index 367220f96f..1bc637518b 100644 --- a/src/CommandLine/Commands/SpellcheckCommand.cs +++ b/src/CommandLine/Commands/SpellcheckCommand.cs @@ -65,7 +65,7 @@ public override async Task ExecuteAsync(ProjectOrSoluti interactive: Options.Interactive, dryRun: Options.DryRun); - CultureInfo culture = (Options.Culture != null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; + CultureInfo culture = (Options.Culture is not null) ? CultureInfo.GetCultureInfo(Options.Culture) : null; var projectFilter = new ProjectFilter(Options.Projects, Options.IgnoredProjects, Language); @@ -142,7 +142,7 @@ private void WriteSummary(ImmutableArray results) if (ShouldWrite(Verbosity.Normal)) { foreach (IGrouping grouping in results - .Where(f => !f.HasFix && f.ContainingValue != null) + .Where(f => !f.HasFix && f.ContainingValue is not null) .GroupBy(f => f.ContainingValue!, comparer) .OrderBy(f => f.Key, comparer)) { @@ -262,7 +262,7 @@ private void WriteSummary(ImmutableArray results) WriteLine(grouping2.Key, ConsoleColors.Cyan, Verbosity.Detailed); foreach (SpellingFixResult result in grouping2 - .Where(f => f.SourceText != null) + .Where(f => f.SourceText is not null) .Distinct(SpellingFixResultEqualityComparer.ValueAndLineSpan) .OrderBy(f => f.LineNumber) .ThenBy(f => f.LineSpan.StartLinePosition.Character)) @@ -318,7 +318,7 @@ protected override void ProcessResults(IList results) string outputPath = null, CancellationToken cancellationToken = default) { - if (newFixesPath != null) + if (newFixesPath is not null) { Dictionary> fixes = spellingData.Fixes.Items.ToDictionary( f => f.Key, @@ -368,7 +368,7 @@ protected override void ProcessResults(IList results) const StringComparison comparison = StringComparison.InvariantCulture; StringComparer comparer = StringComparerUtility.FromComparison(comparison); - if (newWordsPath != null) + if (newWordsPath is not null) { HashSet newValues = spellingData.IgnoredValues .Concat(results.Select(f => f.Value)) @@ -394,13 +394,13 @@ protected override void ProcessResults(IList results) IEnumerable compoundWords = results .Select(f => f.ContainingValue) - .Where(f => f != null) + .Where(f => f is not null) .Select(f => f!); WordList.Save(newWordsPath, newValues.Concat(compoundWords).Concat(possibleNewFixes), comparer, merge: true); } - if (outputPath != null + if (outputPath is not null && results.Count > 0) { using (var writer = new StreamWriter(outputPath, false, Encoding.UTF8)) @@ -412,7 +412,7 @@ protected override void ProcessResults(IList results) writer.WriteLine(grouping.Key); foreach (IGrouping grouping2 in grouping - .Where(f => f.SourceText != null) + .Where(f => f.SourceText is not null) .GroupBy(f => f.FilePath) .OrderBy(f => f.Key, comparer)) { diff --git a/src/CommandLine/ConsoleDialog.cs b/src/CommandLine/ConsoleDialog.cs index cdfac251cd..b9e8fcccbd 100644 --- a/src/CommandLine/ConsoleDialog.cs +++ b/src/CommandLine/ConsoleDialog.cs @@ -24,7 +24,7 @@ public DialogResult ShowDialog(string text) string s = Console.ReadLine()?.Trim(); - if (s != null) + if (s is not null) { if (s.Length == 0) return DialogResult.None; diff --git a/src/CommandLine/ConsoleDialogDefinition.cs b/src/CommandLine/ConsoleDialogDefinition.cs index fe2f71eb2a..886dac40f5 100644 --- a/src/CommandLine/ConsoleDialogDefinition.cs +++ b/src/CommandLine/ConsoleDialogDefinition.cs @@ -20,7 +20,7 @@ public static ConsoleDialogDefinition Default { get { - if (_default == null) + if (_default is null) Interlocked.CompareExchange(ref _default, CreateDefaultDefinition(), null); return _default; diff --git a/src/CommandLine/ConsoleHelpWriter.cs b/src/CommandLine/ConsoleHelpWriter.cs index fb27fb1c48..2bb3bd1d03 100644 --- a/src/CommandLine/ConsoleHelpWriter.cs +++ b/src/CommandLine/ConsoleHelpWriter.cs @@ -59,7 +59,7 @@ public override void WriteCommands(CommandsHelp commands) WriteEndCommands(commands); } - else if (Options.Filter != null) + else if (Options.Filter is not null) { WriteLine("No command found"); } @@ -115,11 +115,11 @@ protected override void WriteTextLine(HelpItem helpItem) { string value = helpItem.Text; - if (Filter != null) + if (Filter is not null) { Match match = Filter.Match(value); - if (match != null) + if (match is not null) { int prevIndex = 0; diff --git a/src/CommandLine/ConsoleHelpers.cs b/src/CommandLine/ConsoleHelpers.cs index 4dcc543e9d..8b79456ba7 100644 --- a/src/CommandLine/ConsoleHelpers.cs +++ b/src/CommandLine/ConsoleHelpers.cs @@ -17,7 +17,7 @@ public static IEnumerable ReadRedirectedInputAsLines() { string line; - while ((line = streamReader.ReadLine()) != null) + while ((line = streamReader.ReadLine()) is not null) yield return line; } } diff --git a/src/CommandLine/DelegateFactory.cs b/src/CommandLine/DelegateFactory.cs index 24c63235ce..276267116c 100644 --- a/src/CommandLine/DelegateFactory.cs +++ b/src/CommandLine/DelegateFactory.cs @@ -29,7 +29,7 @@ internal static class DelegateFactory parameterTypeName, parameterName); - if (assembly == null) + if (assembly is null) { result = null; return false; @@ -42,7 +42,7 @@ internal static class DelegateFactory $"Roslynator.Runtime.{className}", methodName); - return result != null; + return result is not null; } public static bool TryCreateFromSourceText( @@ -53,14 +53,14 @@ internal static class DelegateFactory { Assembly assembly = AssemblyFactory.FromSourceText(sourceText); - if (assembly == null) + if (assembly is null) { result = null; return false; } result = CreateDelegateAndCatchIfThrows(assembly, returnType, new Type[] { parameterType }); - return result != null; + return result is not null; } public static bool TryCreateFromCodeFile( @@ -77,14 +77,14 @@ internal static class DelegateFactory Assembly assembly = AssemblyFactory.FromSourceText(content); - if (assembly == null) + if (assembly is null) { result = null; return false; } result = CreateDelegateAndCatchIfThrows(assembly, returnType, new Type[] { parameterType }); - return result != null; + return result is not null; } public static bool TryCreateFromAssembly( @@ -104,7 +104,7 @@ internal static class DelegateFactory { result = default; - if (path == null) + if (path is null) return false; int index = path.LastIndexOf(','); @@ -153,7 +153,7 @@ internal static class DelegateFactory result = CreateDelegateAndCatchIfThrows(assembly, returnType, parameters, typeName, methodName); - return result != null; + return result is not null; } private static TDelegate CreateDelegateAndCatchIfThrows( @@ -189,21 +189,21 @@ internal static class DelegateFactory Type type; MethodInfo method; - if (typeName != null) + if (typeName is not null) { type = assembly.GetType(typeName); - if (type == null) + if (type is null) { WriteError($"Cannot find type '{typeName}' in assembly '{assembly.FullName}'"); return null; } - if (methodName != null) + if (methodName is not null) { method = type.GetMethod(methodName, parameters); - if (method == null) + if (method is null) { WriteError($"Cannot find method '{methodName}' in type '{typeName}'"); return null; @@ -213,7 +213,7 @@ internal static class DelegateFactory { method = FindMethod(type, returnType, parameters); - if (method == null) + if (method is null) { WriteError("Cannot find public method with signature " + $"'{returnType.Name} M({string.Join(", ", parameters.Select(f => f.Name))})'" @@ -229,7 +229,7 @@ internal static class DelegateFactory { method = FindMethod(assembly, returnType, parameters, methodName); - if (method == null) + if (method is null) { WriteError("Cannot find public method with signature " + $"'{returnType.Name} {methodName ?? "M"}({string.Join(", ", parameters.Select(f => f.Name))})'"); @@ -250,7 +250,7 @@ internal static class DelegateFactory { object typeInstance = Activator.CreateInstance(type!); - if (typeInstance == null) + if (typeInstance is null) { WriteError($"Cannot create instance of '{typeName}'"); return null; @@ -268,11 +268,11 @@ internal static class DelegateFactory { foreach (Type type in assembly.GetTypes()) { - MethodInfo method = (methodName != null) + MethodInfo method = (methodName is not null) ? type.GetMethod(methodName, parameters) : FindMethod(type, returnType, parameters); - if (method != null) + if (method is not null) return method; } diff --git a/src/CommandLine/DiagnosticMap.cs b/src/CommandLine/DiagnosticMap.cs index f58e926c08..8a735a1c34 100644 --- a/src/CommandLine/DiagnosticMap.cs +++ b/src/CommandLine/DiagnosticMap.cs @@ -39,7 +39,7 @@ internal sealed class DiagnosticMap { get { - if (_analyzersById == null) + if (_analyzersById is null) Interlocked.CompareExchange(ref _analyzersById, LoadAnalyzersById(), null); return _analyzersById; @@ -61,7 +61,7 @@ public ImmutableArray SupportedDiagnostics { get { - if (_supportedDiagnosticsByPrefix == null) + if (_supportedDiagnosticsByPrefix is null) Interlocked.CompareExchange(ref _supportedDiagnosticsByPrefix, LoadSupportedDiagnosticsByPrefix(), null); return _supportedDiagnosticsByPrefix; @@ -72,7 +72,7 @@ public ImmutableArray SupportedDiagnostics { get { - if (_fixersById == null) + if (_fixersById is null) Interlocked.CompareExchange(ref _fixersById, LoadFixersById(), null); return _fixersById; @@ -94,7 +94,7 @@ public ImmutableArray FixableDiagnosticIds { get { - if (_fixableDiagnosticIdsByPrefix == null) + if (_fixableDiagnosticIdsByPrefix is null) Interlocked.CompareExchange(ref _fixableDiagnosticIdsByPrefix, LoadFixableDiagnosticIdsByPrefix(), null); return _fixableDiagnosticIdsByPrefix; @@ -105,7 +105,7 @@ public ImmutableArray FixableDiagnosticIds { get { - if (_diagnosticsById == null) + if (_diagnosticsById is null) Interlocked.CompareExchange(ref _diagnosticsById, LoadDiagnosticsById(), null); return _diagnosticsById; @@ -192,7 +192,7 @@ private ImmutableArray LoadFixAllProviders() { return Fixers .Select(f => f.GetFixAllProvider()) - .Where(f => f != null) + .Where(f => f is not null) .Distinct() .ToImmutableArray(); } diff --git a/src/CommandLine/Html/SymbolDefinitionHtmlWriter.cs b/src/CommandLine/Html/SymbolDefinitionHtmlWriter.cs index 722f521f44..f2772006f7 100644 --- a/src/CommandLine/Html/SymbolDefinitionHtmlWriter.cs +++ b/src/CommandLine/Html/SymbolDefinitionHtmlWriter.cs @@ -178,7 +178,7 @@ public override void WriteEndTypes() public override void WriteStartType(INamedTypeSymbol typeSymbol) { - if (typeSymbol != null) + if (typeSymbol is not null) { WriteLocalRef(typeSymbol); @@ -233,7 +233,7 @@ public override void WriteStartType(INamedTypeSymbol typeSymbol) public override void WriteTypeDefinition(INamedTypeSymbol typeSymbol, SymbolDisplayFormat format = null) { - if (typeSymbol != null) + if (typeSymbol is not null) { if (DocumentationDisplayMode == DocumentationDisplayMode.Xml) WriteDocumentationComment(typeSymbol); @@ -405,7 +405,7 @@ protected override void WriteDefinitionName(ISymbol symbol, SymbolDisplayFormat string url = SourceReferenceProvider?.GetSourceReferences(symbol).FirstOrDefault().Url ?? WellKnownExternalUrlProviders.MicrosoftDocs.CreateUrl(symbol).Url; - if (url != null) + if (url is not null) { WriteStartElement("a"); WriteAttributeString("href", url); @@ -416,7 +416,7 @@ protected override void WriteDefinitionName(ISymbol symbol, SymbolDisplayFormat base.WriteDefinitionName(symbol, format); - if (url != null) + if (url is not null) WriteEndElement(); WriteEndElement(); @@ -442,7 +442,7 @@ protected override void WriteDefinitionName(ISymbol symbol, SymbolDisplayFormat { string url = WellKnownExternalUrlProviders.MicrosoftDocs.CreateUrl(symbol).Url; - if (url != null) + if (url is not null) { if (shouldWriteContainingNamespace) WriteContainingNamespace(symbol); @@ -478,7 +478,7 @@ bool ShouldWriteContainingNamespace() && !symbol.ContainingNamespace.IsGlobalNamespace && Format.Includes(SymbolDefinitionPartFilter.ContainingNamespace) && !CSharpFacts.IsPredefinedType(((INamedTypeSymbol)symbol).SpecialType) - && (format == null || format.TypeQualificationStyle == SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); + && (format is null || format.TypeQualificationStyle == SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); } void WriteName() @@ -504,7 +504,7 @@ protected override void WriteParameterName(ISymbol symbol, SymbolDisplayPart par .GetXmlDocumentation(symbol)? .GetElement(WellKnownXmlTags.Param, "name", part.ToString()); - if (element != null) + if (element is not null) { WriteStartElement("span"); WriteStartAttribute("title"); @@ -514,7 +514,7 @@ protected override void WriteParameterName(ISymbol symbol, SymbolDisplayPart par base.WriteParameterName(symbol, part); - if (element != null) + if (element is not null) WriteEndElement(); } else @@ -614,7 +614,7 @@ public override void WriteDocumentationComment(ISymbol symbol) IEnumerable elementsText = DocumentationProvider?.GetXmlDocumentation(symbol)?.GetElementsAsText(skipEmptyElement: true, makeSingleLine: true); - if (elementsText == null) + if (elementsText is null) return; foreach (string elementText in elementsText) @@ -633,7 +633,7 @@ public override void WriteDocumentationComment(ISymbol symbol) { int lineNumber = ((IXmlLineInfo)e).LineNumber; - if (elementsByLine == null) + if (elementsByLine is null) elementsByLine = new Dictionary>(); if (elementsByLine.ContainsKey(lineNumber)) @@ -656,11 +656,11 @@ public override void WriteDocumentationComment(ISymbol symbol) string line = null; - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) { Write("/// "); - if (elementsByLine != null + if (elementsByLine is not null && elementsByLine.TryGetValue(lineNumber, out List elements)) { int lastPos = 0; @@ -676,7 +676,7 @@ public override void WriteDocumentationComment(ISymbol symbol) { string name = e.Attribute("name")?.Value; - if (name != null) + if (name is not null) { Write(line.Substring(lastPos, linePos - lastPos)); Write(name); @@ -689,13 +689,13 @@ public override void WriteDocumentationComment(ISymbol symbol) { string commentId = e.Attribute("cref")?.Value; - if (commentId != null) + if (commentId is not null) { Write(line.Substring(lastPos, linePos - lastPos)); ISymbol s = DocumentationProvider.GetFirstSymbolForDeclarationId(commentId)?.OriginalDefinition; - if (s != null) + if (s is not null) { if (s.Kind == SymbolKind.Field && s.ContainingType.TypeKind == TypeKind.Enum) @@ -720,7 +720,7 @@ public override void WriteDocumentationComment(ISymbol symbol) { string langword = e.Attribute("langword")?.Value; - if (langword != null) + if (langword is not null) { Write(line.Substring(lastPos, linePos - lastPos)); Write(langword); @@ -754,12 +754,12 @@ private void WriteDocumentationCommentToolTip(ISymbol symbol) SymbolXmlDocumentation xmlDocumentation = DocumentationProvider?.GetXmlDocumentation(symbol); - if (xmlDocumentation == null) + if (xmlDocumentation is null) return; XElement summaryElement = xmlDocumentation.GetElement(WellKnownXmlTags.Summary); - if (summaryElement != null) + if (summaryElement is not null) { WriteStartAttribute("title"); WriteDocumentationCommentToolTip(summaryElement); @@ -773,7 +773,7 @@ private void WriteDocumentationCommentToolTip(ISymbol symbol) { hasExceptions = true; - if (summaryElement != null) + if (summaryElement is not null) { Write("\n\n"); } @@ -790,11 +790,11 @@ private void WriteDocumentationCommentToolTip(ISymbol symbol) string commentId = en.Current.Attribute("cref").Value; - if (commentId != null) + if (commentId is not null) { ISymbol exceptionSymbol = DocumentationProvider.GetFirstSymbolForDeclarationId(commentId); - if (exceptionSymbol != null) + if (exceptionSymbol is not null) { Write(exceptionSymbol.ToDisplayParts(Format.GetFormat())); } @@ -808,7 +808,7 @@ private void WriteDocumentationCommentToolTip(ISymbol symbol) } } - if (summaryElement != null + if (summaryElement is not null || hasExceptions) { WriteEndAttribute(); @@ -861,7 +861,7 @@ private void WriteDocumentationCommentToolTip(XElement element) { string parameterName = e.Attribute("name")?.Value; - if (parameterName != null) + if (parameterName is not null) Write(parameterName); break; @@ -870,11 +870,11 @@ private void WriteDocumentationCommentToolTip(XElement element) { string commentId = e.Attribute("cref")?.Value; - if (commentId != null) + if (commentId is not null) { ISymbol symbol = DocumentationProvider.GetFirstSymbolForDeclarationId(commentId); - if (symbol != null) + if (symbol is not null) { Write(symbol.ToDisplayParts(Format.GetFormat())); } @@ -890,7 +890,7 @@ private void WriteDocumentationCommentToolTip(XElement element) { string typeParameterName = e.Attribute("name")?.Value; - if (typeParameterName != null) + if (typeParameterName is not null) Write(typeParameterName); break; @@ -931,7 +931,7 @@ private bool IsExternal(ISymbol symbol) public override void Close() { - if (_writer != null) + if (_writer is not null) { try { diff --git a/src/CommandLine/Json/SymbolDefinitionJsonWriter.cs b/src/CommandLine/Json/SymbolDefinitionJsonWriter.cs index d0547b9beb..b3b5a82e7e 100644 --- a/src/CommandLine/Json/SymbolDefinitionJsonWriter.cs +++ b/src/CommandLine/Json/SymbolDefinitionJsonWriter.cs @@ -154,7 +154,7 @@ public override void WriteTypeDefinition(INamedTypeSymbol typeSymbol, SymbolDisp { if (HasContent(typeSymbol)) { - if (typeSymbol != null) + if (typeSymbol is not null) { WritePropertyName("type"); WriteDefinition(typeSymbol, format); @@ -170,7 +170,7 @@ public override void WriteTypeDefinition(INamedTypeSymbol typeSymbol, SymbolDisp WriteProperty("type", ""); } } - else if (typeSymbol != null) + else if (typeSymbol is not null) { WriteDefinition(typeSymbol, format); } @@ -296,7 +296,7 @@ public override void WriteStartAttribute(AttributeData attribute, ISymbol symbol public override void WriteAttribute(AttributeData attribute) { - if (_definitionWriter == null) + if (_definitionWriter is null) { _attributeStringBuilder = new StringBuilder(); var stringWriter = new StringWriter(_attributeStringBuilder); @@ -423,7 +423,7 @@ internal override void WriteTypeHierarchyItem(TypeHierarchyItem item, Cancellati WriteEndObject(); } - else if (typeSymbol != null) + else if (typeSymbol is not null) { WriteDefinition(typeSymbol, DefinitionFormat); } @@ -441,7 +441,7 @@ private bool HasContent(TypeHierarchyItem item) private bool HasContent(INamedTypeSymbol typeSymbol) { - if (typeSymbol == null) + if (typeSymbol is null) return true; if (Format.Includes(SymbolDefinitionPartFilter.Attributes) @@ -498,7 +498,7 @@ protected override void WriteEndHierarchyTypes() public override void WriteDefinition(ISymbol symbol, ImmutableArray parts) { - if (_definitionWriter == null) + if (_definitionWriter is null) { _attributeStringBuilder = new StringBuilder(); var stringWriter = new StringWriter(_attributeStringBuilder); @@ -585,7 +585,7 @@ public override void WriteDocumentationComment(ISymbol symbol) public override void Close() { - if (_writer != null) + if (_writer is not null) { try { diff --git a/src/CommandLine/LinesOfCodeHelpers.cs b/src/CommandLine/LinesOfCodeHelpers.cs index 219576c178..f6df9a54a9 100644 --- a/src/CommandLine/LinesOfCodeHelpers.cs +++ b/src/CommandLine/LinesOfCodeHelpers.cs @@ -29,7 +29,7 @@ internal static class LinesOfCodeHelpers { ICodeMetricsService service = MefWorkspaceServices.Default.GetService(project.Language); - CodeMetricsInfo projectMetrics = (service != null) + CodeMetricsInfo projectMetrics = (service is not null) ? service.CountLinesAsync(project, kind, options, cancellationToken).Result : CodeMetricsInfo.NotAvailable; diff --git a/src/CommandLine/Migration/AnalyzersMapping.cs b/src/CommandLine/Migration/AnalyzersMapping.cs index 1461288f48..b7092be061 100644 --- a/src/CommandLine/Migration/AnalyzersMapping.cs +++ b/src/CommandLine/Migration/AnalyzersMapping.cs @@ -52,7 +52,7 @@ internal static class AnalyzersMapping { get { - if (_mapping == null) + if (_mapping is null) Interlocked.CompareExchange(ref _mapping, LoadMapping(), null); return _mapping; @@ -67,7 +67,7 @@ internal static class AnalyzersMapping { string line = null; - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) { if (line.Length > 0) { diff --git a/src/CommandLine/Options/MSBuildCommandLineOptions.cs b/src/CommandLine/Options/MSBuildCommandLineOptions.cs index 637840c346..264f5e00f6 100644 --- a/src/CommandLine/Options/MSBuildCommandLineOptions.cs +++ b/src/CommandLine/Options/MSBuildCommandLineOptions.cs @@ -43,7 +43,7 @@ public abstract class MSBuildCommandLineOptions : BaseCommandLineOptions internal bool TryGetLanguage(out string value) { - if (Language != null) + if (Language is not null) return ParseHelpers.TryParseLanguage(Language, out value); value = null; @@ -56,7 +56,7 @@ internal bool TryGetProjectFilter(out ProjectFilter projectFilter) string language = null; - if (Language != null + if (Language is not null && !ParseHelpers.TryParseLanguage(Language, out language)) { return false; diff --git a/src/CommandLine/Orang/CommandLine.Core/CommandLoader.cs b/src/CommandLine/Orang/CommandLine.Core/CommandLoader.cs index 38df1d0f16..41be173dfc 100644 --- a/src/CommandLine/Orang/CommandLine.Core/CommandLoader.cs +++ b/src/CommandLine/Orang/CommandLine.Core/CommandLoader.cs @@ -20,7 +20,7 @@ public static IEnumerable LoadCommands(Assembly assembly) { VerbAttribute verbAttribute = type.GetCustomAttribute(); - if (verbAttribute != null) + if (verbAttribute is not null) yield return CreateCommand(type, verbAttribute); } } @@ -73,16 +73,16 @@ private static Command CreateCommand(Type type, VerbAttribute verbAttribute) arguments.Add(argument); break; } - else if (optionAttribute == null) + else if (optionAttribute is null) { optionAttribute = attribute as OptionAttribute; - if (optionAttribute != null) + if (optionAttribute is not null) continue; } } - if (optionAttribute != null) + if (optionAttribute is not null) { Debug.Assert( propertyInfo.PropertyType != typeof(bool) || string.IsNullOrEmpty(optionAttribute.MetaValue), @@ -108,7 +108,7 @@ private static Command CreateCommand(Type type, VerbAttribute verbAttribute) return new Command( verbAttribute.Name, verbAttribute.HelpText, - (commandGroupAttribute != null) + (commandGroupAttribute is not null) ? new CommandGroup(commandGroupAttribute.Name, commandGroupAttribute.Ordinal) : CommandGroup.Default, arguments.OrderBy(f => f.Index), diff --git a/src/CommandLine/Orang/CommandLine.Core/CommandOptionComparer.cs b/src/CommandLine/Orang/CommandLine.Core/CommandOptionComparer.cs index fd2c289764..3c974d68c5 100644 --- a/src/CommandLine/Orang/CommandLine.Core/CommandOptionComparer.cs +++ b/src/CommandLine/Orang/CommandLine.Core/CommandOptionComparer.cs @@ -19,10 +19,10 @@ public override int Compare(CommandOption x, CommandOption y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; string name1 = x.Name; diff --git a/src/CommandLine/Orang/CommandLine.Core/Help/HelpProvider.cs b/src/CommandLine/Orang/CommandLine.Core/Help/HelpProvider.cs index 28d25ddddb..7191469f13 100644 --- a/src/CommandLine/Orang/CommandLine.Core/Help/HelpProvider.cs +++ b/src/CommandLine/Orang/CommandLine.Core/Help/HelpProvider.cs @@ -147,7 +147,7 @@ public static ImmutableArray GetOptionItems(IEnumerable options) { int length = f.Name.Length; - if (f.MetaValue != null) + if (f.MetaValue is not null) { length++; // separator between option name and meta value; length += f.MetaValue.Length; diff --git a/src/CommandLine/Orang/CommandLine.Core/Help/HelpWriter.cs b/src/CommandLine/Orang/CommandLine.Core/Help/HelpWriter.cs index c91aab1691..f2e7338e95 100644 --- a/src/CommandLine/Orang/CommandLine.Core/Help/HelpWriter.cs +++ b/src/CommandLine/Orang/CommandLine.Core/Help/HelpWriter.cs @@ -27,7 +27,7 @@ public virtual void WriteCommand(CommandHelp commandHelp) WriteArguments(arguments); WriteEndArguments(commandHelp); } - else if (Options.Filter != null + else if (Options.Filter is not null && commandHelp.Command.Arguments.Any()) { WriteLine(); @@ -42,7 +42,7 @@ public virtual void WriteCommand(CommandHelp commandHelp) WriteOptions(options); WriteEndOptions(commandHelp); } - else if (Options.Filter != null + else if (Options.Filter is not null && commandHelp.Command.Options.Any()) { WriteLine(); @@ -114,7 +114,7 @@ public virtual void WriteCommands(CommandsHelp commandsHelp) WriteEndCommands(commandsHelp); } - else if (Options.Filter != null) + else if (Options.Filter is not null) { WriteLine("No command found"); } diff --git a/src/CommandLine/Orang/CommandLine.Core/KeyValuePairOptionValue.cs b/src/CommandLine/Orang/CommandLine.Core/KeyValuePairOptionValue.cs index 1725e4873d..78acc2a6e2 100644 --- a/src/CommandLine/Orang/CommandLine.Core/KeyValuePairOptionValue.cs +++ b/src/CommandLine/Orang/CommandLine.Core/KeyValuePairOptionValue.cs @@ -49,15 +49,15 @@ public bool IsKeyOrShortKey(string value) bool hidden = false, bool canContainExpression = false) { - if (key == null) + if (key is null) throw new ArgumentNullException(nameof(key)); - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); shortKey ??= key.Substring(0, 1); - if (helpValue == null) + if (helpValue is null) { if (!string.IsNullOrEmpty(shortKey)) { diff --git a/src/CommandLine/Orang/CommandLine.Core/SimpleOptionValue.cs b/src/CommandLine/Orang/CommandLine.Core/SimpleOptionValue.cs index 7afc6b56aa..786f8da672 100644 --- a/src/CommandLine/Orang/CommandLine.Core/SimpleOptionValue.cs +++ b/src/CommandLine/Orang/CommandLine.Core/SimpleOptionValue.cs @@ -32,7 +32,7 @@ public class SimpleOptionValue : OptionValue public bool IsValueOrShortValue(string value) { - return value == Value || (ShortValue != null && value == ShortValue); + return value == Value || (ShortValue is not null && value == ShortValue); } public static SimpleOptionValue Create( @@ -64,7 +64,7 @@ public bool IsValueOrShortValue(string value) value ??= _lowerLetterUpperLetterRegex.Replace(name, e => e.Value.Insert(1, "-")).ToLowerInvariant(); shortValue ??= value.Substring(0, 1); - if (helpValue == null) + if (helpValue is null) { if (!string.IsNullOrEmpty(shortValue)) { diff --git a/src/CommandLine/Orang/Core/CoreExtensions.cs b/src/CommandLine/Orang/Core/CoreExtensions.cs index 2c83515967..a9b225f4c3 100644 --- a/src/CommandLine/Orang/Core/CoreExtensions.cs +++ b/src/CommandLine/Orang/Core/CoreExtensions.cs @@ -91,7 +91,7 @@ public static int GetDigitCount(this int value) public static T SingleOrDefault(this IReadOnlyCollection values, bool shouldThrow) { - if (values == null) + if (values is null) throw new ArgumentNullException(nameof(values)); if (shouldThrow) @@ -109,7 +109,7 @@ public static T SingleOrDefault(this IReadOnlyCollection values, bool shou Func predicate, bool shouldThrow) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); if (shouldThrow) diff --git a/src/CommandLine/Orang/Core/Filter.cs b/src/CommandLine/Orang/Core/Filter.cs index 94f7aee9ae..8fcec6db97 100644 --- a/src/CommandLine/Orang/Core/Filter.cs +++ b/src/CommandLine/Orang/Core/Filter.cs @@ -62,7 +62,7 @@ public Match Match(string input) internal Match Match(Match match) { - if (Predicate != null) + if (Predicate is not null) { if (GroupNumber < 1) { @@ -110,11 +110,11 @@ internal Match Match(Match match) internal bool IsMatch(string input) { - return Match(input) != null; + return Match(input) is not null; } internal bool IsMatch(Match match) { - return Match(match) != null; + return Match(match) is not null; } } diff --git a/src/CommandLine/Orang/Core/ListCache`1.cs b/src/CommandLine/Orang/Core/ListCache`1.cs index 5d1f7440f5..2e5d32180c 100644 --- a/src/CommandLine/Orang/Core/ListCache`1.cs +++ b/src/CommandLine/Orang/Core/ListCache`1.cs @@ -20,9 +20,9 @@ public static List GetInstance(int capacity = DefaultCapacity) { List list = _cachedInstance; - Debug.Assert(list == null || list.Count == 0, ""); + Debug.Assert(list is null || list.Count == 0, ""); - if (list != null + if (list is not null && capacity <= list.Capacity) { _cachedInstance = null; diff --git a/src/CommandLine/Orang/Core/StringBuilderCache.cs b/src/CommandLine/Orang/Core/StringBuilderCache.cs index 19300cfce8..289007e2d8 100644 --- a/src/CommandLine/Orang/Core/StringBuilderCache.cs +++ b/src/CommandLine/Orang/Core/StringBuilderCache.cs @@ -19,7 +19,7 @@ public static StringBuilder GetInstance(int capacity = DefaultCapacity) { StringBuilder sb = _cachedInstance; - if (sb != null + if (sb is not null && capacity <= sb.Capacity) { _cachedInstance = null; diff --git a/src/CommandLine/Orang/Core/Text/RegularExpressions/GroupDefinitionCollection.cs b/src/CommandLine/Orang/Core/Text/RegularExpressions/GroupDefinitionCollection.cs index 4d9182f7f4..bbacb39a50 100644 --- a/src/CommandLine/Orang/Core/Text/RegularExpressions/GroupDefinitionCollection.cs +++ b/src/CommandLine/Orang/Core/Text/RegularExpressions/GroupDefinitionCollection.cs @@ -22,7 +22,7 @@ public GroupDefinitionCollection(Regex regex) private static GroupDefinition[] CreateGroupDefinitions(Regex regex) { - if (regex == null) + if (regex is null) throw new ArgumentNullException(nameof(regex)); string[] names = regex.GetGroupNames(); @@ -37,7 +37,7 @@ private static GroupDefinition[] CreateGroupDefinitions(Regex regex) public bool Contains(string name) { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); return _names.ContainsKey(name); @@ -55,7 +55,7 @@ public bool Contains(int number) { get { - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); try diff --git a/src/CommandLine/Orang/Core/Text/RegularExpressions/MatchData.cs b/src/CommandLine/Orang/Core/Text/RegularExpressions/MatchData.cs index a79743d5a8..8e461f890b 100644 --- a/src/CommandLine/Orang/Core/Text/RegularExpressions/MatchData.cs +++ b/src/CommandLine/Orang/Core/Text/RegularExpressions/MatchData.cs @@ -29,10 +29,10 @@ internal sealed class MatchData int maxCount = -1, CancellationToken cancellationToken = default) { - if (regex == null) + if (regex is null) throw new ArgumentNullException(nameof(regex)); - if (input == null) + if (input is null) throw new ArgumentNullException(nameof(input)); Match match = regex.Match(input); diff --git a/src/CommandLine/Orang/Core/Text/RegularExpressions/RegexEscape.cs b/src/CommandLine/Orang/Core/Text/RegularExpressions/RegexEscape.cs index 7dc7cd0546..0a69eda378 100644 --- a/src/CommandLine/Orang/Core/Text/RegularExpressions/RegexEscape.cs +++ b/src/CommandLine/Orang/Core/Text/RegularExpressions/RegexEscape.cs @@ -10,7 +10,7 @@ internal static class RegexEscape { public static string Escape(string input, bool inCharGroup = false) { - if (input == null) + if (input is null) throw new ArgumentNullException(nameof(input)); for (int i = 0; i < input.Length; i++) @@ -129,7 +129,7 @@ internal static CharEscapeMode GetEscapeMode(int charCode, bool inCharGroup) public static string EscapeSubstitution(string input) { - if (input == null) + if (input is null) throw new ArgumentNullException(nameof(input)); for (int i = 0; i < input.Length; i++) diff --git a/src/CommandLine/Orang/Core/Text/RegularExpressions/ReplaceData.cs b/src/CommandLine/Orang/Core/Text/RegularExpressions/ReplaceData.cs index 7de6d84144..f55485b0bc 100644 --- a/src/CommandLine/Orang/Core/Text/RegularExpressions/ReplaceData.cs +++ b/src/CommandLine/Orang/Core/Text/RegularExpressions/ReplaceData.cs @@ -30,13 +30,13 @@ internal sealed class ReplaceData int count = -1, CancellationToken cancellationToken = default) { - if (regex == null) + if (regex is null) throw new ArgumentNullException(nameof(regex)); - if (input == null) + if (input is null) throw new ArgumentNullException(nameof(input)); - if (replacement == null) + if (replacement is null) replacement = ""; return Create(regex, input, f => Evaluate(f), count, cancellationToken); @@ -54,13 +54,13 @@ string Evaluate(Match match) int count = -1, CancellationToken cancellationToken = default) { - if (regex == null) + if (regex is null) throw new ArgumentNullException(nameof(regex)); - if (input == null) + if (input is null) throw new ArgumentNullException(nameof(input)); - if (evaluator == null) + if (evaluator is null) throw new ArgumentNullException(nameof(evaluator)); var items = new List(); diff --git a/src/CommandLine/Orang/Core/Text/RegularExpressions/SplitData.cs b/src/CommandLine/Orang/Core/Text/RegularExpressions/SplitData.cs index 591299c3bb..483d86d84f 100644 --- a/src/CommandLine/Orang/Core/Text/RegularExpressions/SplitData.cs +++ b/src/CommandLine/Orang/Core/Text/RegularExpressions/SplitData.cs @@ -33,10 +33,10 @@ internal sealed class SplitData bool omitGroups = false, CancellationToken cancellationToken = default) { - if (regex == null) + if (regex is null) throw new ArgumentNullException(nameof(regex)); - if (input == null) + if (input is null) throw new ArgumentNullException(nameof(input)); var groupDefinitions = new GroupDefinitionCollection(regex); diff --git a/src/CommandLine/Orang/Core/TextHelpers.cs b/src/CommandLine/Orang/Core/TextHelpers.cs index e125a70313..7e46e54299 100644 --- a/src/CommandLine/Orang/Core/TextHelpers.cs +++ b/src/CommandLine/Orang/Core/TextHelpers.cs @@ -16,7 +16,7 @@ public static IEnumerable ReadLines(string value) { string line = null; - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) { yield return line; } @@ -112,10 +112,10 @@ public static string SplitCamelCase(string value) public static string SplitCamelCase(string value, string separator) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (separator == null) + if (separator is null) throw new ArgumentNullException(nameof(separator)); int len = value.Length; diff --git a/src/CommandLine/ParseHelpers.cs b/src/CommandLine/ParseHelpers.cs index 73a8457fb9..c59f8841e5 100644 --- a/src/CommandLine/ParseHelpers.cs +++ b/src/CommandLine/ParseHelpers.cs @@ -76,7 +76,7 @@ public static bool TryParseMSBuildProperties(IEnumerable values, out Dic string key = property.Substring(0, index); - if (properties == null) + if (properties is null) properties = new Dictionary(); properties[key] = property.Substring(index + 1); @@ -126,7 +126,7 @@ public static bool TryParseKeyValuePairs(IEnumerable values, out List values, out List(string value, string optionName, out TEnum result, TEnum? defaultValue = null) where TEnum : struct { - if (value == null - && defaultValue != null) + if (value is null + && defaultValue is not null) { result = defaultValue.Value; return true; diff --git a/src/CommandLine/ProjectFilter.cs b/src/CommandLine/ProjectFilter.cs index 40b9e12af5..650ee70abc 100644 --- a/src/CommandLine/ProjectFilter.cs +++ b/src/CommandLine/ProjectFilter.cs @@ -36,15 +36,15 @@ public bool IsDefault { get { - return Names == null - && IgnoredNames == null - && Language == null; + return Names is null + && IgnoredNames is null + && Language is null; } } public bool IsMatch(Project project) { - if (Language != null + if (Language is not null && Language != project.Language) { return false; @@ -65,9 +65,9 @@ private static bool IsMatch(string name, ImmutableHashSet projectNa foreach (ProjectName projectName2 in projectNames) { - if (projectName2.Moniker != null) + if (projectName2.Moniker is not null) { - if (projectName.Moniker != null + if (projectName.Moniker is not null && string.Equals(projectName.Name, projectName2.Name, StringComparison.Ordinal)) { return true; diff --git a/src/CommandLine/TypeComparer.cs b/src/CommandLine/TypeComparer.cs index 3f4769a899..f06bd3b419 100644 --- a/src/CommandLine/TypeComparer.cs +++ b/src/CommandLine/TypeComparer.cs @@ -21,10 +21,10 @@ public int Compare(object x, object y) if (x == y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is Type a @@ -41,10 +41,10 @@ public int Compare(object x, object y) if (x == y) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x is Type a @@ -58,7 +58,7 @@ public int Compare(object x, object y) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) return 0; if (obj is Type type) @@ -74,10 +74,10 @@ public override int Compare(Type x, Type y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; int result = CompareNamespace(x.Namespace, y.Namespace); @@ -132,10 +132,10 @@ public override bool Equals(Type x, Type y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return string.Equals(x.FullName, y.FullName, StringComparison.Ordinal); @@ -143,7 +143,7 @@ public override bool Equals(Type x, Type y) public override int GetHashCode(Type obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); return StringComparer.Ordinal.GetHashCode(obj.FullName); diff --git a/src/CommandLine/VisualStudioInstanceComparer.cs b/src/CommandLine/VisualStudioInstanceComparer.cs index 73f5bb73da..db9e85028d 100644 --- a/src/CommandLine/VisualStudioInstanceComparer.cs +++ b/src/CommandLine/VisualStudioInstanceComparer.cs @@ -18,10 +18,10 @@ public override bool Equals(VisualStudioInstance x, VisualStudioInstance y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return FileSystemHelpers.Comparer.Equals(x.MSBuildPath, y.MSBuildPath); @@ -29,6 +29,6 @@ public override bool Equals(VisualStudioInstance x, VisualStudioInstance y) public override int GetHashCode(VisualStudioInstance obj) { - return (obj == null) ? 0 : FileSystemHelpers.Comparer.GetHashCode(obj.MSBuildPath); + return (obj is null) ? 0 : FileSystemHelpers.Comparer.GetHashCode(obj.MSBuildPath); } } diff --git a/src/CommandLine/Xml/AnalyzerAssemblyXmlSerializer.cs b/src/CommandLine/Xml/AnalyzerAssemblyXmlSerializer.cs index 6206beb36c..f23fbd765c 100644 --- a/src/CommandLine/Xml/AnalyzerAssemblyXmlSerializer.cs +++ b/src/CommandLine/Xml/AnalyzerAssemblyXmlSerializer.cs @@ -142,7 +142,7 @@ static XElement CreateFixAllProviderElement(CodeFixProvider fixer) { FixAllProvider fixAllProvider = fixer.GetFixAllProvider(); - if (fixAllProvider != null) + if (fixAllProvider is not null) { return new XElement("FixAllProvider", new XAttribute("Name", fixAllProvider.GetType().FullName)); } @@ -175,7 +175,7 @@ static XElement CreateFixAllProviderElement(CodeFixProvider fixer) { var element = new XElement("Diagnostic", new XAttribute("Id", diagnosticId)); - if (descriptor != null) + if (descriptor is not null) { string title = descriptor.Title?.ToString(formatProvider); string messageFormat = descriptor.MessageFormat?.ToString(formatProvider); diff --git a/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysis.cs b/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysis.cs index 28e095c5d5..8900f90aed 100644 --- a/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysis.cs +++ b/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysis.cs @@ -68,7 +68,7 @@ internal static class AddExceptionToDocumentationCommentAnalysis DocumentationCommentTriviaSyntax comment = containingMember.GetSingleLineDocumentationComment(); - if (comment == null) + if (comment is null) return Fail; if (!CanAddExceptionToComment(comment, typeSymbol, semanticModel, cancellationToken)) @@ -145,7 +145,7 @@ private static bool ContainsException(XmlElementSyntax xmlElement, INamedTypeSym { XmlElementStartTagSyntax startTag = xmlElement.StartTag; - return startTag != null + return startTag is not null && ContainsException(startTag.Attributes, exceptionSymbol, semanticModel, cancellationToken); } @@ -164,7 +164,7 @@ private static bool ContainsException(SyntaxList attributes, CrefSyntax cref = xmlCrefAttribute.Cref; - if (cref != null + if (cref is not null && (semanticModel.GetSymbol(cref, cancellationToken) is INamedTypeSymbol symbol)) { if (SymbolEqualityComparer.Default.Equals(exceptionSymbol, symbol)) diff --git a/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysisResult.cs b/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysisResult.cs index 52c3f29121..b11b8862cc 100644 --- a/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysisResult.cs +++ b/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysisResult.cs @@ -16,7 +16,7 @@ internal AddExceptionToDocumentationCommentAnalysisResult(ThrowInfo info, Syntax public bool Success { - get { return ThrowInfo != null; } + get { return ThrowInfo is not null; } } public ISymbol DeclarationSymbol diff --git a/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/ThrowStatementInfo.cs b/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/ThrowStatementInfo.cs index 36c4c36ed3..504595537c 100644 --- a/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/ThrowStatementInfo.cs +++ b/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/ThrowStatementInfo.cs @@ -20,7 +20,7 @@ internal ThrowStatementInfo(ThrowStatementSyntax node, ExpressionSyntax expressi { SyntaxNode parent = Node.Parent; - if (parent == null) + if (parent is null) return null; if (parent.IsKind(SyntaxKind.Block)) @@ -38,7 +38,7 @@ internal ThrowStatementInfo(ThrowStatementSyntax node, ExpressionSyntax expressi ExpressionSyntax left = equalsExpression.Left; - if (left == null) + if (left is null) return null; ISymbol leftSymbol = semanticModel.GetSymbol(left, cancellationToken); diff --git a/src/Common/CSharp/Analysis/BlockExpressionAnalysis.cs b/src/Common/CSharp/Analysis/BlockExpressionAnalysis.cs index 7752a3590e..ce7dca0940 100644 --- a/src/Common/CSharp/Analysis/BlockExpressionAnalysis.cs +++ b/src/Common/CSharp/Analysis/BlockExpressionAnalysis.cs @@ -24,9 +24,9 @@ private BlockExpressionAnalysis(StatementSyntax statement, ExpressionSyntax expr public SyntaxToken ReturnOrThrowKeyword { get; } - public BlockSyntax Block => (Statement != null) ? (BlockSyntax)Statement.Parent : default; + public BlockSyntax Block => (Statement is not null) ? (BlockSyntax)Statement.Parent : default; - public bool Success => Expression != null; + public bool Success => Expression is not null; public static bool SupportsExpressionBody(BlockSyntax block, bool allowExpressionStatement = true) { @@ -47,7 +47,7 @@ public static BlockExpressionAnalysis Create(BlockSyntax block, bool allowExpres { StatementSyntax statement = block?.Statements.SingleOrDefault(shouldThrow: false); - if (statement == null) + if (statement is null) return default; switch (statement.Kind()) diff --git a/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysis.cs b/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysis.cs index 055113495f..6342c36ac1 100644 --- a/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysis.cs +++ b/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysis.cs @@ -29,7 +29,7 @@ public static class CallExtensionMethodAsInstanceMethodAnalysis .Expression? .WalkDownParentheses(); - if (expression == null) + if (expression is null) return Fail; if (!allowAnyExpression) @@ -51,7 +51,7 @@ public static class CallExtensionMethodAsInstanceMethodAnalysis IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationExpression, cancellationToken); - if (methodSymbol == null) + if (methodSymbol is null) return Fail; if (!methodSymbol.IsOrdinaryExtensionMethod()) @@ -59,7 +59,7 @@ public static class CallExtensionMethodAsInstanceMethodAnalysis InvocationExpressionSyntax newInvocationExpression = GetNewInvocation(invocationExpression); - if (newInvocationExpression == null) + if (newInvocationExpression is null) return Fail; if (!SymbolEqualityComparer.Default.Equals( @@ -96,7 +96,7 @@ private static InvocationExpressionSyntax GetNewInvocation(InvocationExpressionS MemberAccessExpressionSyntax newMemberAccess = CreateNewMemberAccessExpression(); - if (newMemberAccess == null) + if (newMemberAccess is null) return null; return invocation diff --git a/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysisResult.cs b/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysisResult.cs index 3249f85ca1..5a907c9571 100644 --- a/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysisResult.cs +++ b/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysisResult.cs @@ -29,8 +29,8 @@ public bool Success { get { - return InvocationExpression != null - && NewInvocationExpression != null; + return InvocationExpression is not null + && NewInvocationExpression is not null; } } diff --git a/src/Common/CSharp/Analysis/ChangeAccessibilityAnalysis.cs b/src/Common/CSharp/Analysis/ChangeAccessibilityAnalysis.cs index 25a1e74780..211217ecfa 100644 --- a/src/Common/CSharp/Analysis/ChangeAccessibilityAnalysis.cs +++ b/src/Common/CSharp/Analysis/ChangeAccessibilityAnalysis.cs @@ -149,18 +149,18 @@ public static ISymbol GetBaseSymbolOrDefault(SyntaxNode node, SemanticModel sema { ISymbol symbol = GetDeclaredSymbol(); - if (symbol != null) + if (symbol is not null) { if (!symbol.IsOverride) return symbol; symbol = symbol.BaseOverriddenSymbol(); - if (symbol != null) + if (symbol is not null) { SyntaxNode syntax = symbol.GetSyntaxOrDefault(cancellationToken); - if (syntax != null) + if (syntax is not null) { if (syntax is MemberDeclarationSyntax || syntax.IsKind(SyntaxKind.VariableDeclarator)) @@ -179,7 +179,7 @@ ISymbol GetDeclaredSymbol() { VariableDeclaratorSyntax declarator = eventFieldDeclaration.Declaration?.Variables.SingleOrDefault(shouldThrow: false); - if (declarator != null) + if (declarator is not null) return semanticModel.GetDeclaredSymbol(declarator, cancellationToken); return null; diff --git a/src/Common/CSharp/Analysis/ConvertLambdaExpressionBodyToExpressionBodyAnalysis.cs b/src/Common/CSharp/Analysis/ConvertLambdaExpressionBodyToExpressionBodyAnalysis.cs index abe6607ab2..4ffc60be4d 100644 --- a/src/Common/CSharp/Analysis/ConvertLambdaExpressionBodyToExpressionBodyAnalysis.cs +++ b/src/Common/CSharp/Analysis/ConvertLambdaExpressionBodyToExpressionBodyAnalysis.cs @@ -21,7 +21,7 @@ public static bool IsFixable(LambdaExpressionSyntax lambda) StatementSyntax statement = block.Statements.SingleOrDefault(shouldThrow: false); - if (statement == null) + if (statement is null) return false; ExpressionSyntax expression = GetExpression(statement); diff --git a/src/Common/CSharp/Analysis/ConvertMethodGroupToAnonymousFunctionAnalysis.cs b/src/Common/CSharp/Analysis/ConvertMethodGroupToAnonymousFunctionAnalysis.cs index 125b4f18a2..17b33ed8af 100644 --- a/src/Common/CSharp/Analysis/ConvertMethodGroupToAnonymousFunctionAnalysis.cs +++ b/src/Common/CSharp/Analysis/ConvertMethodGroupToAnonymousFunctionAnalysis.cs @@ -15,7 +15,7 @@ public static bool IsFixable(IdentifierNameSyntax identifierName, SemanticModel { IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(identifierName, cancellationToken); - if (methodSymbol != null) + if (methodSymbol is not null) return true; } @@ -28,7 +28,7 @@ public static bool IsFixable(MemberAccessExpressionSyntax memberAccessExpression { IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(memberAccessExpression, cancellationToken); - if (methodSymbol != null) + if (methodSymbol is not null) return true; } diff --git a/src/Common/CSharp/Analysis/ExpandExpressionBodyAnalysis.cs b/src/Common/CSharp/Analysis/ExpandExpressionBodyAnalysis.cs index 9238370608..35510dbe2f 100644 --- a/src/Common/CSharp/Analysis/ExpandExpressionBodyAnalysis.cs +++ b/src/Common/CSharp/Analysis/ExpandExpressionBodyAnalysis.cs @@ -12,7 +12,7 @@ public static bool IsFixable(ArrowExpressionClauseSyntax arrowExpressionClause) { SyntaxNode parent = arrowExpressionClause.Parent; - return parent != null + return parent is not null && CSharpFacts.CanHaveExpressionBody(parent.Kind()); } } diff --git a/src/Common/CSharp/Analysis/GenerateBaseConstructorsAnalysis.cs b/src/Common/CSharp/Analysis/GenerateBaseConstructorsAnalysis.cs index 1ca238a7e5..032baa8505 100644 --- a/src/Common/CSharp/Analysis/GenerateBaseConstructorsAnalysis.cs +++ b/src/Common/CSharp/Analysis/GenerateBaseConstructorsAnalysis.cs @@ -114,10 +114,10 @@ public override bool Equals(IMethodSymbol x, IMethodSymbol y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; ImmutableArray parameters1 = x.Parameters; diff --git a/src/Common/CSharp/Analysis/If/IfAnalysis.cs b/src/Common/CSharp/Analysis/If/IfAnalysis.cs index d68d650fb8..b7af98017a 100644 --- a/src/Common/CSharp/Analysis/If/IfAnalysis.cs +++ b/src/Common/CSharp/Analysis/If/IfAnalysis.cs @@ -49,19 +49,19 @@ protected IfAnalysis(IfStatementSyntax ifStatement, SemanticModel semanticModel) ExpressionSyntax condition = ifStatement.Condition?.WalkDownParentheses(); - if (condition == null) + if (condition is null) return Empty; ElseClauseSyntax elseClause = ifStatement.Else; - if (elseClause != null) + if (elseClause is not null) { if (!CheckDirectivesAndComments(ifStatement, options)) return Empty; StatementSyntax statement1 = ifStatement.SingleNonBlockStatementOrDefault(); - if (statement1 == null) + if (statement1 is null) return Empty; SyntaxKind kind1 = statement1.Kind(); @@ -181,7 +181,7 @@ protected IfAnalysis(IfStatementSyntax ifStatement, SemanticModel semanticModel) semanticModel, cancellationToken); - if (refactoring != null) + if (refactoring is not null) return refactoring.ToImmutableArray(); } } @@ -306,7 +306,7 @@ IfAnalysis CreateIfToReturnStatement(bool isNullable) semanticModel, cancellationToken); - if (refactoring != null) + if (refactoring is not null) return refactoring.ToImmutableArray(); } } @@ -423,7 +423,7 @@ IfAnalysis CreateIfToAssignment(bool isNullable) .Variables .SingleOrDefault(shouldThrow: false); - if (declarator == null) + if (declarator is null) return Empty; ElseClauseSyntax elseClause = ifStatement.Else; @@ -489,7 +489,7 @@ IfAnalysis CreateIfToAssignment(bool isNullable) ExpressionSyntax whenFalse; - if (elseClause != null) + if (elseClause is not null) { if (elseClause.Statement.IsKind(SyntaxKind.IfStatement)) return Empty; @@ -571,9 +571,9 @@ private ImmutableArray ToImmutableArray() private static ImmutableArray ToImmutableArray(IfAnalysis refactoring1, IfAnalysis refactoring2) { - if (refactoring1 != null) + if (refactoring1 is not null) { - if (refactoring2 != null) + if (refactoring2 is not null) { return ImmutableArray.Create(refactoring1, refactoring2); } @@ -582,7 +582,7 @@ private static ImmutableArray ToImmutableArray(IfAnalysis refactorin return refactoring1.ToImmutableArray(); } } - else if (refactoring2 != null) + else if (refactoring2 is not null) { return refactoring2.ToImmutableArray(); } diff --git a/src/Common/CSharp/Analysis/ReduceIfNesting/ReduceIfNestingAnalysis.cs b/src/Common/CSharp/Analysis/ReduceIfNesting/ReduceIfNestingAnalysis.cs index c04e74d5a6..948e1f9d10 100644 --- a/src/Common/CSharp/Analysis/ReduceIfNesting/ReduceIfNestingAnalysis.cs +++ b/src/Common/CSharp/Analysis/ReduceIfNesting/ReduceIfNestingAnalysis.cs @@ -227,7 +227,7 @@ private static ReduceIfNestingAnalysisResult Fail(SyntaxNode topNode) if (ifStatement.IsParentKind(SyntaxKind.ElseClause)) { - if (ifStatement.Else != null) + if (ifStatement.Else is not null) return Fail(parent); if (!options.AllowIfInsideIfElse()) @@ -264,7 +264,7 @@ private static bool IsNestedFix(SyntaxNode node, SemanticModel semanticModel, Re { options |= ReduceIfNestingOptions.AllowNestedFix; - while (node != null) + while (node is not null) { if (node is IfStatementSyntax ifStatement) { @@ -357,7 +357,7 @@ internal static SyntaxKind GetJumpKind(StatementSyntax statement) { ExpressionSyntax expression = returnStatement.Expression; - if (expression == null) + if (expression is null) return SyntaxKind.ReturnStatement; SyntaxKind kind = expression.Kind(); @@ -377,7 +377,7 @@ internal static SyntaxKind GetJumpKind(StatementSyntax statement) { ExpressionSyntax expression = throwStatement.Expression; - if (expression == null) + if (expression is null) return SyntaxKind.ThrowStatement; return SyntaxKind.None; @@ -411,7 +411,7 @@ internal static bool IsFixableRecursively(IfStatementSyntax ifStatement, SyntaxK internal static bool IsFixable(IfStatementSyntax ifStatement) { - if (ifStatement == null) + if (ifStatement is null) return false; if (!ifStatement.IsSimpleIf()) diff --git a/src/Common/CSharp/Analysis/RemoveAsyncAwaitAnalysis.cs b/src/Common/CSharp/Analysis/RemoveAsyncAwaitAnalysis.cs index d078ae5f73..233cb0e71c 100644 --- a/src/Common/CSharp/Analysis/RemoveAsyncAwaitAnalysis.cs +++ b/src/Common/CSharp/Analysis/RemoveAsyncAwaitAnalysis.cs @@ -28,7 +28,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) Walker = null; } - public bool Success => AwaitExpression != null || Walker?.AwaitExpressions.Count > 0; + public bool Success => AwaitExpression is not null || Walker?.AwaitExpressions.Count > 0; public AwaitExpressionSyntax AwaitExpression { get; } @@ -41,7 +41,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) { BlockSyntax body = methodDeclaration.Body; - if (body != null) + if (body is not null) { return AnalyzeMethodBody(methodDeclaration, body, semanticModel, cancellationToken); } @@ -49,7 +49,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) { ArrowExpressionClauseSyntax expressionBody = methodDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) return AnalyzeExpressionBody(methodDeclaration, expressionBody, semanticModel, cancellationToken); } @@ -63,7 +63,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) { BlockSyntax body = localFunction.Body; - if (body != null) + if (body is not null) { return AnalyzeMethodBody(localFunction, body, semanticModel, cancellationToken); } @@ -71,7 +71,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) { ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) return AnalyzeExpressionBody(localFunction, expressionBody, semanticModel, cancellationToken); } @@ -85,7 +85,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) { BlockSyntax block = anonymousMethod.Block; - if (block == null) + if (block is null) return default; return AnalyzeMethodBody(anonymousMethod, block, semanticModel, cancellationToken); @@ -120,7 +120,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) { CSharpSyntaxNode body = lambda.Body; - if (body == null) + if (body is null) return default; switch (body.Kind()) @@ -170,7 +170,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) } } - if (statement == null) + if (statement is null) return default; switch (statement.Kind()) @@ -181,7 +181,7 @@ private RemoveAsyncAwaitAnalysis(AwaitExpressionSyntax awaitExpression) AwaitExpressionSyntax awaitExpression = GetAwaitExpression(returnStatement); - if (awaitExpression == null) + if (awaitExpression is null) return default; AwaitExpressionWalker walker = VisitStatements(); @@ -284,7 +284,7 @@ AwaitExpressionWalker VisitStatements() AwaitExpressionSyntax awaitExpression = GetAwaitExpression(ifOrElse.Statement); - if (awaitExpression == null) + if (awaitExpression is null) return false; count++; @@ -309,7 +309,7 @@ AwaitExpressionWalker VisitStatements() AwaitExpressionSyntax awaitExpression = GetAwaitExpression(section.Statements.LastOrDefault()); - if (awaitExpression == null) + if (awaitExpression is null) return false; count++; @@ -320,7 +320,7 @@ AwaitExpressionWalker VisitStatements() private static AwaitExpressionSyntax GetAwaitExpression(StatementSyntax statement) { - if (statement == null) + if (statement is null) return null; SyntaxKind kind = statement.Kind(); @@ -360,7 +360,7 @@ private static AwaitExpressionSyntax GetAwaitExpression(ReturnStatementSyntax re { IMethodSymbol methodSymbol = GetMethodSymbol(node, semanticModel, cancellationToken); - if (methodSymbol == null) + if (methodSymbol is null) return false; ITypeSymbol returnType = methodSymbol.ReturnType; @@ -370,7 +370,7 @@ private static AwaitExpressionSyntax GetAwaitExpression(ReturnStatementSyntax re ITypeSymbol typeArgument = ((INamedTypeSymbol)returnType).TypeArguments.SingleOrDefault(shouldThrow: false); - if (typeArgument == null) + if (typeArgument is null) return false; foreach (AwaitExpressionSyntax awaitExpression in awaitExpressions) @@ -390,7 +390,7 @@ private static AwaitExpressionSyntax GetAwaitExpression(ReturnStatementSyntax re { IMethodSymbol methodSymbol = GetMethodSymbol(node, semanticModel, cancellationToken); - if (methodSymbol == null) + if (methodSymbol is null) return false; ITypeSymbol returnType = methodSymbol.ReturnType; @@ -400,7 +400,7 @@ private static AwaitExpressionSyntax GetAwaitExpression(ReturnStatementSyntax re ITypeSymbol typeArgument = ((INamedTypeSymbol)returnType).TypeArguments.SingleOrDefault(shouldThrow: false); - if (typeArgument == null) + if (typeArgument is null) return false; return VerifyAwaitType(awaitExpression, typeArgument, semanticModel, cancellationToken); @@ -415,7 +415,7 @@ private static bool VerifyAwaitType(AwaitExpressionSyntax awaitExpression, IType ITypeSymbol expressionTypeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (expressionTypeSymbol == null) + if (expressionTypeSymbol is null) return false; if (expressionTypeSymbol.OriginalDefinition.EqualsOrInheritsFrom(MetadataNames.System_Threading_Tasks_Task_T)) @@ -450,7 +450,7 @@ private static bool VerifyAwaitType(AwaitExpressionSyntax awaitExpression, IType public void Dispose() { - if (Walker != null) + if (Walker is not null) { AwaitExpressionWalker.Free(Walker); } diff --git a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantReturnStatementAnalysis.cs b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantReturnStatementAnalysis.cs index 304de36a8c..2096d0d365 100644 --- a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantReturnStatementAnalysis.cs +++ b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantReturnStatementAnalysis.cs @@ -18,7 +18,7 @@ public override bool IsFixable(ReturnStatementSyntax statement) { ExpressionSyntax expression = statement.Expression; - if (expression == null) + if (expression is null) return base.IsFixable(statement); if (expression.IsKind( @@ -69,7 +69,7 @@ protected override bool IsFixable(StatementSyntax statement, StatementSyntax con case SyntaxKind.AnonymousMethodExpression: { return statement is ReturnStatementSyntax returnStatement - && returnStatement.Expression == null; + && returnStatement.Expression is null; } default: { diff --git a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantStatementAnalysis`1.cs b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantStatementAnalysis`1.cs index e9879f32ef..9667b68ab3 100644 --- a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantStatementAnalysis`1.cs +++ b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantStatementAnalysis`1.cs @@ -22,7 +22,7 @@ public virtual bool IsFixable(TStatement statement) while (true) { - if (parent == null) + if (parent is null) return false; SyntaxKind kind = parent.Kind(); @@ -35,7 +35,7 @@ public virtual bool IsFixable(TStatement statement) block = containingStatement.Parent as BlockSyntax; - if (block == null) + if (block is null) return false; if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) @@ -55,7 +55,7 @@ public virtual bool IsFixable(TStatement statement) block = containingStatement.Parent as BlockSyntax; - if (block == null) + if (block is null) return false; if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) @@ -85,7 +85,7 @@ internal bool IsFixable(StatementSyntax statement, BlockSyntax block) while (true) { - if (parent == null) + if (parent is null) return false; SyntaxKind kind = parent.Kind(); @@ -98,7 +98,7 @@ internal bool IsFixable(StatementSyntax statement, BlockSyntax block) block = containingStatement.Parent as BlockSyntax; - if (block == null) + if (block is null) return false; if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) @@ -118,7 +118,7 @@ internal bool IsFixable(StatementSyntax statement, BlockSyntax block) block = containingStatement.Parent as BlockSyntax; - if (block == null) + if (block is null) return false; if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) diff --git a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantYieldBreakStatementAnalysis.cs b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantYieldBreakStatementAnalysis.cs index 51d0e0e979..3c5460babe 100644 --- a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantYieldBreakStatementAnalysis.cs +++ b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantYieldBreakStatementAnalysis.cs @@ -39,7 +39,7 @@ protected override bool IsFixable(StatementSyntax statement, StatementSyntax con { walker.VisitStatement(statements[i]); - success = walker.YieldStatement != null; + success = walker.YieldStatement is not null; if (success) break; diff --git a/src/Common/CSharp/Analysis/ReplaceAsWithCastAnalysis.cs b/src/Common/CSharp/Analysis/ReplaceAsWithCastAnalysis.cs index f3f1e7ca37..a591d9760a 100644 --- a/src/Common/CSharp/Analysis/ReplaceAsWithCastAnalysis.cs +++ b/src/Common/CSharp/Analysis/ReplaceAsWithCastAnalysis.cs @@ -21,7 +21,7 @@ internal static class ReplaceAsWithCastAnalysis ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(info.Type, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return false; if (!semanticModel.IsExplicitConversion(info.Expression, typeSymbol)) diff --git a/src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs b/src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs index eef3e12392..8ac531f525 100644 --- a/src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs +++ b/src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs @@ -64,7 +64,7 @@ internal static class UseConstantInsteadOfFieldAnalysis var fieldSymbol = (IFieldSymbol)semanticModel.GetDeclaredSymbol(firstDeclarator, cancellationToken); - if (fieldSymbol == null) + if (fieldSymbol is null) return false; if (!fieldSymbol.Type.SupportsConstantValue()) @@ -74,7 +74,7 @@ internal static class UseConstantInsteadOfFieldAnalysis { ExpressionSyntax value = declarator.Initializer?.Value; - if (value == null) + if (value is null) return false; if (value.WalkDownParentheses().IsKind(SyntaxKind.InterpolatedStringExpression)) @@ -95,7 +95,7 @@ internal static class UseConstantInsteadOfFieldAnalysis BlockSyntax body = constructorDeclaration.Body; - if (body != null) + if (body is not null) { bool canBeConvertedToConstant; UseConstantInsteadOfFieldWalker walker = null; @@ -114,7 +114,7 @@ internal static class UseConstantInsteadOfFieldAnalysis } finally { - if (walker != null) + if (walker is not null) UseConstantInsteadOfFieldWalker.Free(walker); } @@ -194,10 +194,10 @@ public static UseConstantInsteadOfFieldWalker GetInstance() { UseConstantInsteadOfFieldWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { - Debug.Assert(walker.FieldSymbol == null); - Debug.Assert(walker.SemanticModel == null); + Debug.Assert(walker.FieldSymbol is null); + Debug.Assert(walker.SemanticModel is null); Debug.Assert(walker.CancellationToken == default); _cachedInstance = null; diff --git a/src/Common/CSharp/Analysis/UseElementAccessAnalysis.cs b/src/Common/CSharp/Analysis/UseElementAccessAnalysis.cs index 04b7a4beb0..48189718c4 100644 --- a/src/Common/CSharp/Analysis/UseElementAccessAnalysis.cs +++ b/src/Common/CSharp/Analysis/UseElementAccessAnalysis.cs @@ -23,7 +23,7 @@ internal static class UseElementAccessAnalysis IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return false; if (!IsLinqElementAt(methodSymbol, allowImmutableArrayExtension: true)) @@ -55,7 +55,7 @@ internal static class UseElementAccessAnalysis IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationInfo.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return false; if (!IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "First", allowImmutableArrayExtension: true)) @@ -76,7 +76,7 @@ internal static class UseElementAccessAnalysis IMethodSymbol methodSymbol = semanticModel.GetReducedExtensionMethodInfo(invocationInfo.InvocationExpression, cancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return false; if (!IsLinqExtensionOfIEnumerableOfTWithoutParameters(methodSymbol, "Last", allowImmutableArrayExtension: true)) @@ -95,7 +95,7 @@ internal static class UseElementAccessAnalysis { ISymbol symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); - if (symbol != null) + if (symbol is not null) { IPropertySymbol propertySymbol = null; diff --git a/src/Common/CSharp/Analysis/UseMethodChaining/MethodChainingWithAssignmentAnalysis.cs b/src/Common/CSharp/Analysis/UseMethodChaining/MethodChainingWithAssignmentAnalysis.cs index 07ec40d649..d8de3f45ee 100644 --- a/src/Common/CSharp/Analysis/UseMethodChaining/MethodChainingWithAssignmentAnalysis.cs +++ b/src/Common/CSharp/Analysis/UseMethodChaining/MethodChainingWithAssignmentAnalysis.cs @@ -43,7 +43,7 @@ internal class MethodChainingWithAssignmentAnalysis : UseMethodChainingAnalysis IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationInfo.InvocationExpression, cancellationToken); - if (methodSymbol == null) + if (methodSymbol is null) return false; if (!SymbolEqualityComparer.Default.Equals(methodSymbol.ReturnType, typeSymbol)) @@ -70,7 +70,7 @@ internal class MethodChainingWithAssignmentAnalysis : UseMethodChainingAnalysis && identifierName != identifierName2 && name == identifierName2.Identifier.ValueText) { - if (symbol == null) + if (symbol is null) symbol = semanticModel.GetSymbol(identifierName, cancellationToken); if (SymbolEqualityComparer.Default.Equals(semanticModel.GetSymbol(identifierName2, cancellationToken), symbol)) diff --git a/src/Common/CSharp/Analysis/UseMethodChaining/UseMethodChainingAnalysis.cs b/src/Common/CSharp/Analysis/UseMethodChaining/UseMethodChainingAnalysis.cs index 3df03307a0..70234a4ecb 100644 --- a/src/Common/CSharp/Analysis/UseMethodChaining/UseMethodChainingAnalysis.cs +++ b/src/Common/CSharp/Analysis/UseMethodChaining/UseMethodChainingAnalysis.cs @@ -83,7 +83,7 @@ internal abstract class UseMethodChainingAnalysis IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol(invocationInfo.InvocationExpression, cancellationToken); - if (methodSymbol == null) + if (methodSymbol is null) return false; ITypeSymbol returnType = methodSymbol.ReturnType; diff --git a/src/Common/CSharp/CodeStyle/BodyStyle.cs b/src/Common/CSharp/CodeStyle/BodyStyle.cs index 520e3b05d6..86ae197cce 100644 --- a/src/Common/CSharp/CodeStyle/BodyStyle.cs +++ b/src/Common/CSharp/CodeStyle/BodyStyle.cs @@ -16,7 +16,7 @@ private BodyStyle(BodyStyleOption option, bool? useBlockWhenDeclarationIsMultiLi UseBlockWhenExpressionIsMultiLine = useBlockWhenExpressionIsMultiLine; } - public bool IsDefault => _option == BodyStyleOption.None && UseBlockWhenDeclarationIsMultiLine == null && UseBlockWhenExpressionIsMultiLine == null; + public bool IsDefault => _option == BodyStyleOption.None && UseBlockWhenDeclarationIsMultiLine is null && UseBlockWhenExpressionIsMultiLine is null; public bool UseExpression => _option == BodyStyleOption.Expression; diff --git a/src/Common/CSharp/Extensions/CodeStyleExtensions.cs b/src/Common/CSharp/Extensions/CodeStyleExtensions.cs index 1cbf76a43f..e06730a91f 100644 --- a/src/Common/CSharp/Extensions/CodeStyleExtensions.cs +++ b/src/Common/CSharp/Extensions/CodeStyleExtensions.cs @@ -14,7 +14,7 @@ public static bool GetPrefixFieldIdentifierWithUnderscore(this AnalyzerConfigOpt if (configOptions.TryGetValueAsBool(ConfigOptions.PrefixFieldIdentifierWithUnderscore, out bool value)) return value; - if (CodeAnalysisConfig.Instance.PrefixFieldIdentifierWithUnderscore != null) + if (CodeAnalysisConfig.Instance.PrefixFieldIdentifierWithUnderscore is not null) return CodeAnalysisConfig.Instance.PrefixFieldIdentifierWithUnderscore.Value; if (configOptions.TryGetValueAsBool(LegacyConfigOptions.PrefixFieldIdentifierWithUnderscore, out value)) @@ -31,7 +31,7 @@ public static int GetMaxLineLength(this AnalyzerConfigOptions configOptions) return value; } - if (CodeAnalysisConfig.Instance.MaxLineLength != null) + if (CodeAnalysisConfig.Instance.MaxLineLength is not null) return CodeAnalysisConfig.Instance.MaxLineLength.Value; if (configOptions.TryGetValue(LegacyConfigOptions.MaxLineLength.Key, out rawValue) diff --git a/src/Common/CSharp/SyntaxWalkers/AwaitExpressionWalker.cs b/src/Common/CSharp/SyntaxWalkers/AwaitExpressionWalker.cs index be17c28a00..1ce4a1cefc 100644 --- a/src/Common/CSharp/SyntaxWalkers/AwaitExpressionWalker.cs +++ b/src/Common/CSharp/SyntaxWalkers/AwaitExpressionWalker.cs @@ -112,7 +112,7 @@ public static AwaitExpressionWalker GetInstance() { AwaitExpressionWalker walker = _cachedInstance; - if (walker != null) + if (walker is not null) { Debug.Assert(walker.AwaitExpressions.Count == 0); diff --git a/src/Common/ConfigOptions.cs b/src/Common/ConfigOptions.cs index b1b4274786..9e26afe379 100644 --- a/src/Common/ConfigOptions.cs +++ b/src/Common/ConfigOptions.cs @@ -36,7 +36,7 @@ public static bool TryGetValue(AnalyzerConfigOptions configOptions, ConfigOption ?? CodeAnalysisConfig.Instance.EditorConfig.Options.GetValueOrDefault(option.Key) ?? option.DefaultValue; - return value != null; + return value is not null; } public static string GetValue(AnalyzerConfigOptions configOptions, ConfigOptionDescriptor option, string defaultValue = null) @@ -62,7 +62,7 @@ public static bool TryGetValueAsBool(AnalyzerConfigOptions configOptions, Config ?? CodeAnalysisConfig.Instance.GetOptionAsBool(option.Key) ?? option.DefaultValueAsBool; - if (maybeValue != null) + if (maybeValue is not null) { value = maybeValue.Value; return true; diff --git a/src/Common/Configuration/CodeAnalysisConfig.cs b/src/Common/Configuration/CodeAnalysisConfig.cs index 8d138439c5..89c600361f 100644 --- a/src/Common/Configuration/CodeAnalysisConfig.cs +++ b/src/Common/Configuration/CodeAnalysisConfig.cs @@ -20,7 +20,7 @@ public sealed class CodeAnalysisConfig EditorConfigCodeAnalysisConfig editorConfig = null, VisualStudioCodeAnalysisConfig visualStudioConfig = null) { - if (xmlConfig != null) + if (xmlConfig is not null) { XmlConfig = xmlConfig; } @@ -33,7 +33,7 @@ public sealed class CodeAnalysisConfig : XmlCodeAnalysisConfig.Empty; } - if (editorConfig != null) + if (editorConfig is not null) { EditorConfig = editorConfig; } @@ -60,7 +60,7 @@ public sealed class CodeAnalysisConfig return default; }) - .Where(f => f.key != null) + .Where(f => f.key is not null) .ToImmutableDictionary(f => f.key, f => f.value); VisualStudioConfig = visualStudioConfig ?? VisualStudioCodeAnalysisConfig.Empty; @@ -73,7 +73,7 @@ public sealed class CodeAnalysisConfig PrefixFieldIdentifierWithUnderscore = XmlConfig.PrefixFieldIdentifierWithUnderscore; - if (EditorConfig.PrefixFieldIdentifierWithUnderscore != null) + if (EditorConfig.PrefixFieldIdentifierWithUnderscore is not null) PrefixFieldIdentifierWithUnderscore = EditorConfig.PrefixFieldIdentifierWithUnderscore; if (VisualStudioConfig.PrefixFieldIdentifierWithUnderscore != ConfigOptionDefaultValues.PrefixFieldIdentifierWithUnderscore) @@ -81,7 +81,7 @@ public sealed class CodeAnalysisConfig MaxLineLength = XmlConfig.MaxLineLength; - if (EditorConfig.MaxLineLength != null) + if (EditorConfig.MaxLineLength is not null) MaxLineLength = EditorConfig.MaxLineLength; var refactorings = new Dictionary(); diff --git a/src/Common/Configuration/ConfigMigrator.cs b/src/Common/Configuration/ConfigMigrator.cs index 7ffb17d3ac..cf8abdc5f0 100644 --- a/src/Common/Configuration/ConfigMigrator.cs +++ b/src/Common/Configuration/ConfigMigrator.cs @@ -47,13 +47,13 @@ private static void Migrate(string path) writer.WriteGlobalDirective(); writer.WriteLine(); - if (config.MaxLineLength != null) + if (config.MaxLineLength is not null) writer.WriteEntry(ConfigOptionKeys.MaxLineLength, config.MaxLineLength.ToString()); - if (config.PrefixFieldIdentifierWithUnderscore != null) + if (config.PrefixFieldIdentifierWithUnderscore is not null) writer.WriteEntry(ConfigOptionKeys.PrefixFieldIdentifierWithUnderscore, config.PrefixFieldIdentifierWithUnderscore.Value); - writer.WriteLineIf(config.MaxLineLength != null || config.PrefixFieldIdentifierWithUnderscore != null); + writer.WriteLineIf(config.MaxLineLength is not null || config.PrefixFieldIdentifierWithUnderscore is not null); writer.WriteRefactorings(config.Refactorings.OrderBy(f => f.Key)); writer.WriteLineIf(config.Refactorings.Count > 0); @@ -79,9 +79,9 @@ private static void Migrate(string path) { } - if (ruleSet != null) + if (ruleSet is not null) { - if (writer == null) + if (writer is null) { writer = new EditorConfigWriter(new StringWriter()); @@ -105,11 +105,11 @@ private static void Migrate(string path) { (string key, string value) = MapRuleSetOptionToEditorConfigOption(kvp); - return (key != null) + return (key is not null) ? new KeyValuePair(key, value) : default; }) - .Where(f => f.Key != null) + .Where(f => f.Key is not null) .OrderBy(f => f.Key)) { writer.WriteEntry(kvp); @@ -126,7 +126,7 @@ private static void Migrate(string path) } } - if (writer != null) + if (writer is not null) { File.WriteAllText(editorConfigPath, writer.ToString()); diff --git a/src/Common/Configuration/EditorConfigCodeAnalysisConfigLoader.cs b/src/Common/Configuration/EditorConfigCodeAnalysisConfigLoader.cs index 5fa833942b..fcd486c59a 100644 --- a/src/Common/Configuration/EditorConfigCodeAnalysisConfigLoader.cs +++ b/src/Common/Configuration/EditorConfigCodeAnalysisConfigLoader.cs @@ -88,7 +88,7 @@ private static EditorConfigCodeAnalysisConfig LoadInternal(IEnumerable p { ReportDiagnostic? reportDiagnostic = ParseReportDiagnostic(option.Value); - if (reportDiagnostic != null) + if (reportDiagnostic is not null) { string category = match.Groups["category"].Value; (categories ??= new Dictionary()).Add(category, reportDiagnostic.Value); diff --git a/src/Common/Configuration/XmlCodeAnalysisConfigLoader.cs b/src/Common/Configuration/XmlCodeAnalysisConfigLoader.cs index 02b8015e01..7951a6e8fd 100644 --- a/src/Common/Configuration/XmlCodeAnalysisConfigLoader.cs +++ b/src/Common/Configuration/XmlCodeAnalysisConfigLoader.cs @@ -45,7 +45,7 @@ internal static XmlCodeAnalysisConfig Load(string path, XmlConfigLoadOptions opt ImmutableArray includes = queue?.ToImmutableArray() ?? ImmutableArray.Empty; - if (queue != null + if (queue is not null && (options & XmlConfigLoadOptions.SkipIncludes) == 0) { var loadedIncludes = new HashSet(FileSystemHelpers.Comparer) { path }; @@ -75,7 +75,7 @@ internal static XmlCodeAnalysisConfig Load(string path, XmlConfigLoadOptions opt while (queue.Count > 0); } - if (builder == null) + if (builder is null) return null; return new XmlCodeAnalysisConfig( @@ -107,7 +107,7 @@ internal static XmlCodeAnalysisConfig Load(string path, XmlConfigLoadOptions opt { if (element.HasName("Settings")) { - if (builder == null) + if (builder is null) builder = new Builder(); LoadSettings(element, builder, uri); @@ -122,7 +122,7 @@ internal static XmlCodeAnalysisConfig Load(string path, XmlConfigLoadOptions opt string path = LoadPath(attribute, directoryPath); - if (path != null) + if (path is not null) (includes ??= new Queue()).Enqueue(path); } else @@ -261,7 +261,7 @@ private static void LoadRefactorings(XElement element, Builder builder) } if (!string.IsNullOrEmpty(id) - && isEnabled != null) + && isEnabled is not null) { builder.Refactorings[id] = isEnabled.Value; } @@ -299,7 +299,7 @@ private static void LoadCodeFixes(XElement element, Builder builder) } if (!string.IsNullOrEmpty(id) - && isEnabled != null) + && isEnabled is not null) { builder.CodeFixes[id] = isEnabled.Value; } diff --git a/src/Common/DiagnosticProperties.cs b/src/Common/DiagnosticProperties.cs index e792bf8214..d7b66c71c6 100644 --- a/src/Common/DiagnosticProperties.cs +++ b/src/Common/DiagnosticProperties.cs @@ -20,7 +20,7 @@ internal static class DiagnosticProperties { get { - if (_analyzerOption_Invert == null) + if (_analyzerOption_Invert is null) { Interlocked.CompareExchange( ref _analyzerOption_Invert, diff --git a/src/Common/EquivalenceKey.cs b/src/Common/EquivalenceKey.cs index 13c7cf6921..ecc61ededb 100644 --- a/src/Common/EquivalenceKey.cs +++ b/src/Common/EquivalenceKey.cs @@ -25,9 +25,9 @@ public static string Create(string key, string additionalKey1 = null, string add { Debug.Assert(!string.IsNullOrEmpty(key)); - if (additionalKey1 != null) + if (additionalKey1 is not null) { - if (additionalKey2 != null) + if (additionalKey2 is not null) { return Prefix + key + Separator + additionalKey1 + Separator + additionalKey2; } @@ -36,7 +36,7 @@ public static string Create(string key, string additionalKey1 = null, string add return Prefix + key + Separator + additionalKey1; } } - else if (additionalKey2 != null) + else if (additionalKey2 is not null) { return Prefix + key + Separator + additionalKey2; } @@ -48,9 +48,9 @@ public static string Create(string key, string additionalKey1 = null, string add internal static string Join(string value1, string value2) { - if (value1 != null) + if (value1 is not null) { - if (value2 != null) + if (value2 is not null) { return value1 + Separator + value2; } @@ -59,7 +59,7 @@ internal static string Join(string value1, string value2) return value1; } } - else if (value2 != null) + else if (value2 is not null) { return value2; } diff --git a/src/Common/RuleSetLoader.cs b/src/Common/RuleSetLoader.cs index 08bd66b357..c018cb09ba 100644 --- a/src/Common/RuleSetLoader.cs +++ b/src/Common/RuleSetLoader.cs @@ -19,7 +19,7 @@ public static RuleSet EmptyRuleSet { get { - if (_emptyRuleSet == null) + if (_emptyRuleSet is null) Interlocked.CompareExchange(ref _emptyRuleSet, CreateEmptyRuleSet(), null); return _emptyRuleSet; @@ -81,7 +81,7 @@ private static RuleSet Load(string path) #endif } - if (ruleSet != null) + if (ruleSet is not null) { sw?.WriteLine($"{DateTime.Now.ToString()} rule set loaded"); sw?.WriteLine($"{DateTime.Now.ToString()} default action is {ruleSet.GeneralDiagnosticOption}"); @@ -107,10 +107,10 @@ private static RuleSet Load(string path) public static RuleSet Combine(RuleSet ruleSet, RuleSet parent) { - if (ruleSet == null) + if (ruleSet is null) return parent; - if (parent == null) + if (parent is null) return ruleSet; ReportDiagnostic newGeneralOption = (IsStricterThan(ruleSet.GeneralDiagnosticOption, parent.GeneralDiagnosticOption)) diff --git a/src/Core/CreateNameFromTypeSymbolHelper.cs b/src/Core/CreateNameFromTypeSymbolHelper.cs index b3c483a748..0c07ad3f9d 100644 --- a/src/Core/CreateNameFromTypeSymbolHelper.cs +++ b/src/Core/CreateNameFromTypeSymbolHelper.cs @@ -11,7 +11,7 @@ internal static class CreateNameFromTypeSymbolHelper { public static string CreateName(ITypeSymbol typeSymbol) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); if (typeSymbol.IsKind(SymbolKind.ErrorType, SymbolKind.DynamicType)) diff --git a/src/Core/DiagnosticComparer.cs b/src/Core/DiagnosticComparer.cs index 3756f6d86f..d6401c2bd6 100644 --- a/src/Core/DiagnosticComparer.cs +++ b/src/Core/DiagnosticComparer.cs @@ -26,10 +26,10 @@ public int Compare(object x, object y) if (x == y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is Diagnostic a @@ -46,10 +46,10 @@ public int Compare(object x, object y) if (x == y) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x is Diagnostic a @@ -63,7 +63,7 @@ public int Compare(object x, object y) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) return 0; if (obj is Diagnostic diagnostic) @@ -79,10 +79,10 @@ public override int Compare(Diagnostic x, Diagnostic y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; return string.CompareOrdinal(x.Id, y.Id); @@ -93,10 +93,10 @@ public override bool Equals(Diagnostic x, Diagnostic y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return string.Equals(x.Id, y.Id, StringComparison.Ordinal); @@ -104,7 +104,7 @@ public override bool Equals(Diagnostic x, Diagnostic y) public override int GetHashCode(Diagnostic obj) { - if (obj == null) + if (obj is null) return 0; return StringComparer.Ordinal.GetHashCode(obj.Id); @@ -118,10 +118,10 @@ public override int Compare(Diagnostic x, Diagnostic y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; return x.Location.SourceSpan.Start.CompareTo(y.Location.SourceSpan.Start); @@ -132,10 +132,10 @@ public override bool Equals(Diagnostic x, Diagnostic y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return x.Location.SourceSpan.Start == y.Location.SourceSpan.Start; @@ -143,7 +143,7 @@ public override bool Equals(Diagnostic x, Diagnostic y) public override int GetHashCode(Diagnostic obj) { - if (obj == null) + if (obj is null) return 0; return obj.Location.SourceSpan.Start.GetHashCode(); @@ -157,10 +157,10 @@ public override int Compare(Diagnostic x, Diagnostic y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; int result = x.Id.CompareTo(y.Id); @@ -181,10 +181,10 @@ public override bool Equals(Diagnostic x, Diagnostic y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return x.Id == y.Id @@ -194,7 +194,7 @@ public override bool Equals(Diagnostic x, Diagnostic y) public override int GetHashCode(Diagnostic obj) { - if (obj == null) + if (obj is null) return 0; return Hash.Combine( diff --git a/src/Core/DiagnosticDeepEqualityComparer.cs b/src/Core/DiagnosticDeepEqualityComparer.cs index c8fac79bb9..f88a634f24 100644 --- a/src/Core/DiagnosticDeepEqualityComparer.cs +++ b/src/Core/DiagnosticDeepEqualityComparer.cs @@ -26,10 +26,10 @@ public bool Equals(Diagnostic x, Diagnostic y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (!x.Descriptor.Equals(y.Descriptor)) @@ -49,7 +49,7 @@ public bool Equals(Diagnostic x, Diagnostic y) public int GetHashCode(Diagnostic obj) { - if (obj == null) + if (obj is null) return 0; return Hash.Combine( diff --git a/src/Core/DiagnosticDescriptorComparer.cs b/src/Core/DiagnosticDescriptorComparer.cs index 917a42d613..c6eba73aee 100644 --- a/src/Core/DiagnosticDescriptorComparer.cs +++ b/src/Core/DiagnosticDescriptorComparer.cs @@ -24,10 +24,10 @@ public int Compare(object x, object y) if (x == y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is DiagnosticDescriptor a @@ -44,10 +44,10 @@ public int Compare(object x, object y) if (x == y) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x is DiagnosticDescriptor a @@ -61,7 +61,7 @@ public int Compare(object x, object y) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) return 0; if (obj is DiagnosticDescriptor descriptor) @@ -77,10 +77,10 @@ public override int Compare(DiagnosticDescriptor x, DiagnosticDescriptor y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; return string.CompareOrdinal(x.Id, y.Id); @@ -91,10 +91,10 @@ public override bool Equals(DiagnosticDescriptor x, DiagnosticDescriptor y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return string.Equals(x.Id, y.Id, StringComparison.Ordinal); @@ -102,7 +102,7 @@ public override bool Equals(DiagnosticDescriptor x, DiagnosticDescriptor y) public override int GetHashCode(DiagnosticDescriptor obj) { - if (obj == null) + if (obj is null) return 0; return StringComparer.Ordinal.GetHashCode(obj.Id); diff --git a/src/Core/DiagnosticIdComparer.cs b/src/Core/DiagnosticIdComparer.cs index 97afddd92f..4821bb86a0 100644 --- a/src/Core/DiagnosticIdComparer.cs +++ b/src/Core/DiagnosticIdComparer.cs @@ -21,10 +21,10 @@ public int Compare(object x, object y) if (x == y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is string a @@ -41,10 +41,10 @@ public int Compare(object x, object y) if (x == y) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x is string a @@ -58,7 +58,7 @@ public int Compare(object x, object y) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) return 0; if (obj is string descriptor) @@ -74,10 +74,10 @@ public override int Compare(string x, string y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; int length1 = DiagnosticIdPrefix.GetPrefixLength(x); @@ -101,10 +101,10 @@ public override bool Equals(string x, string y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; int length1 = DiagnosticIdPrefix.GetPrefixLength(x); @@ -116,7 +116,7 @@ public override bool Equals(string x, string y) public override int GetHashCode(string obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); int length = DiagnosticIdPrefix.GetPrefixLength(obj); diff --git a/src/Core/Documentation/DocumentationCommentGeneratorSettings.cs b/src/Core/Documentation/DocumentationCommentGeneratorSettings.cs index c1ebd2bd1a..45963dd1d6 100644 --- a/src/Core/Documentation/DocumentationCommentGeneratorSettings.cs +++ b/src/Core/Documentation/DocumentationCommentGeneratorSettings.cs @@ -13,7 +13,7 @@ internal class DocumentationCommentGeneratorSettings string indentation = null, bool singleLineSummary = false) { - Summary = (summary != null) ? ImmutableArray.CreateRange(summary) : ImmutableArray.Empty; + Summary = (summary is not null) ? ImmutableArray.CreateRange(summary) : ImmutableArray.Empty; IgnoredTags = ignoredTags?.ToImmutableArray() ?? ImmutableArray.Empty; Indentation = indentation ?? ""; SingleLineSummary = singleLineSummary; diff --git a/src/Core/EnumFieldSymbolInfo.cs b/src/Core/EnumFieldSymbolInfo.cs index d8343188a1..f59e6537ac 100644 --- a/src/Core/EnumFieldSymbolInfo.cs +++ b/src/Core/EnumFieldSymbolInfo.cs @@ -24,7 +24,7 @@ public EnumFieldSymbolInfo(IFieldSymbol symbol, ulong value) public static EnumFieldSymbolInfo Create(IFieldSymbol fieldSymbol) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (!TryCreate(fieldSymbol, out EnumFieldSymbolInfo fieldInfo)) @@ -35,7 +35,7 @@ public static EnumFieldSymbolInfo Create(IFieldSymbol fieldSymbol) public static bool TryCreate(IFieldSymbol fieldSymbol, out EnumFieldSymbolInfo fieldInfo) { - if (fieldSymbol == null) + if (fieldSymbol is null) { fieldInfo = default; return false; diff --git a/src/Core/EnumSymbolInfo.cs b/src/Core/EnumSymbolInfo.cs index 0bbd232737..7e2f463663 100644 --- a/src/Core/EnumSymbolInfo.cs +++ b/src/Core/EnumSymbolInfo.cs @@ -74,7 +74,7 @@ public List Decompose(ulong value) public static EnumSymbolInfo Create(INamedTypeSymbol symbol) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); if (!TryCreate(symbol, out EnumSymbolInfo enumInfo)) diff --git a/src/Core/EnumUtility.cs b/src/Core/EnumUtility.cs index 87dc1e996c..326964a589 100644 --- a/src/Core/EnumUtility.cs +++ b/src/Core/EnumUtility.cs @@ -38,7 +38,7 @@ public static OneOrMany GetConstituentFields(ulong value, i if (val != 0 && (result & val) == val) { - if (builder == null) + if (builder is null) { if (result == val) return OneOrMany.Create(fields[i]); @@ -56,7 +56,7 @@ public static OneOrMany GetConstituentFields(ulong value, i } if (result == 0 - && builder != null) + && builder is not null) { builder.Reverse(); @@ -105,7 +105,7 @@ public static ImmutableArray GetMinimalConstituentFields(ul } if (result == 0 - && builder != null) + && builder is not null) { Debug.Assert(builder.Count > 1); diff --git a/src/Core/EnumValueComparer.cs b/src/Core/EnumValueComparer.cs index c2b64f3838..7a909d2ec0 100644 --- a/src/Core/EnumValueComparer.cs +++ b/src/Core/EnumValueComparer.cs @@ -46,10 +46,10 @@ public int Compare(object x, object y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is sbyte xvalue @@ -75,10 +75,10 @@ public int Compare(object x, object y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is byte xvalue @@ -104,10 +104,10 @@ public int Compare(object x, object y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is short xvalue @@ -133,10 +133,10 @@ public int Compare(object x, object y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is ushort xvalue @@ -162,10 +162,10 @@ public int Compare(object x, object y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is int xvalue @@ -191,10 +191,10 @@ public int Compare(object x, object y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is uint xvalue @@ -220,10 +220,10 @@ public int Compare(object x, object y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is long xvalue @@ -249,10 +249,10 @@ public int Compare(object x, object y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is ulong xvalue diff --git a/src/Core/ExtensionMethodSymbolInfo.cs b/src/Core/ExtensionMethodSymbolInfo.cs index 5d6849a63a..68a92c1f8a 100644 --- a/src/Core/ExtensionMethodSymbolInfo.cs +++ b/src/Core/ExtensionMethodSymbolInfo.cs @@ -42,7 +42,7 @@ public IMethodSymbol ReducedSymbolOrSymbol /// public bool IsReduced { - get { return Symbol != null && !object.ReferenceEquals(ReducedSymbol, Symbol); } + get { return Symbol is not null && !object.ReferenceEquals(ReducedSymbol, Symbol); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -50,7 +50,7 @@ private string DebuggerDisplay { get { - return (Symbol != null) + return (Symbol is not null) ? $"{Symbol.MethodKind} {Symbol.ToDisplayString(SymbolDisplayFormats.Test)}" : "Uninitialized"; } diff --git a/src/Core/Extensions/DiagnosticsExtensions.cs b/src/Core/Extensions/DiagnosticsExtensions.cs index 7dd9481d18..2809cd6540 100644 --- a/src/Core/Extensions/DiagnosticsExtensions.cs +++ b/src/Core/Extensions/DiagnosticsExtensions.cs @@ -28,7 +28,7 @@ public static class DiagnosticsExtensions SyntaxNode node, params object[] messageArgs) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); ReportDiagnostic( @@ -181,7 +181,7 @@ public static class DiagnosticsExtensions SyntaxNode node, params object[] messageArgs) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); ReportDiagnostic( @@ -334,7 +334,7 @@ public static class DiagnosticsExtensions SyntaxNode node, params object[] messageArgs) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); ReportDiagnostic( diff --git a/src/Core/Extensions/EnumerableExtensions.cs b/src/Core/Extensions/EnumerableExtensions.cs index 22a5d44b1c..a3f8621440 100644 --- a/src/Core/Extensions/EnumerableExtensions.cs +++ b/src/Core/Extensions/EnumerableExtensions.cs @@ -36,10 +36,10 @@ public static bool IsSorted(this IEnumerable enumerable, IComparer comp int count, Func selector) { - if (enumerable == null) + if (enumerable is null) throw new ArgumentNullException(nameof(enumerable)); - if (selector == null) + if (selector is null) throw new ArgumentNullException(nameof(selector)); if (startIndex < 0) diff --git a/src/Core/Extensions/ListExtensions.cs b/src/Core/Extensions/ListExtensions.cs index 754dccd448..ebe0fac36e 100644 --- a/src/Core/Extensions/ListExtensions.cs +++ b/src/Core/Extensions/ListExtensions.cs @@ -10,7 +10,7 @@ internal static class ListExtensions { public static T SingleOrDefault(this IReadOnlyList list, bool shouldThrow) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); if (shouldThrow) @@ -25,7 +25,7 @@ public static T SingleOrDefault(this IReadOnlyList list, bool shouldThrow) public static T SingleOrDefault(this IReadOnlyList list, Func predicate, bool shouldThrow) { - if (list == null) + if (list is null) throw new ArgumentNullException(nameof(list)); if (shouldThrow) diff --git a/src/Core/Extensions/SemanticModelExtensions.cs b/src/Core/Extensions/SemanticModelExtensions.cs index 47c08d42cf..9874699850 100644 --- a/src/Core/Extensions/SemanticModelExtensions.cs +++ b/src/Core/Extensions/SemanticModelExtensions.cs @@ -20,7 +20,7 @@ public static class SemanticModelExtensions TextSpan? span = null, CancellationToken cancellationToken = default) { - if (semanticModel == null) + if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); ImmutableArray diagnostics = semanticModel.GetDiagnostics(span, cancellationToken); @@ -60,12 +60,12 @@ public static class SemanticModelExtensions int position, CancellationToken cancellationToken = default) where TSymbol : ISymbol { - if (semanticModel == null) + if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); ISymbol symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); - while (symbol != null) + while (symbol is not null) { if (symbol is TSymbol tsymbol) return tsymbol; @@ -111,7 +111,7 @@ public static class SemanticModelExtensions /// public static INamedTypeSymbol GetTypeByMetadataName(this SemanticModel semanticModel, string fullyQualifiedMetadataName) { - if (semanticModel == null) + if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); return semanticModel @@ -141,7 +141,7 @@ public static INamedTypeSymbol GetTypeByMetadataName(this SemanticModel semantic { SyntaxNode node = GetEnclosingSymbolSyntax(semanticModel, position, cancellationToken); - if (node != null) + if (node is not null) return GetDeclaredSymbols(semanticModel, node, excludeAnonymousTypeProperty, cancellationToken); return ImmutableArray.Empty; @@ -189,7 +189,7 @@ public static INamedTypeSymbol GetTypeByMetadataName(this SemanticModel semantic { ISymbol symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); - if (symbol != null) + if (symbol is not null) { if (!excludeAnonymousTypeProperty || !symbol.IsPropertyOfAnonymousType()) diff --git a/src/Core/Extensions/SymbolExtensions.cs b/src/Core/Extensions/SymbolExtensions.cs index 51ce1cd6f2..a927f1cd4d 100644 --- a/src/Core/Extensions/SymbolExtensions.cs +++ b/src/Core/Extensions/SymbolExtensions.cs @@ -20,7 +20,7 @@ public static class SymbolExtensions #region ISymbol internal static IEnumerable FindImplementedInterfaceMembers(this ISymbol symbol, bool allInterfaces = false) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); return Iterator(); @@ -29,7 +29,7 @@ IEnumerable Iterator() { INamedTypeSymbol containingType = symbol.ContainingType; - if (containingType != null) + if (containingType is not null) { ImmutableArray interfaces = containingType.GetInterfaces(allInterfaces); @@ -51,7 +51,7 @@ IEnumerable Iterator() internal static ISymbol FindFirstImplementedInterfaceMember(this ISymbol symbol, bool allInterfaces = false) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); return FindFirstImplementedInterfaceMemberImpl(symbol, null, allInterfaces); @@ -59,10 +59,10 @@ internal static ISymbol FindFirstImplementedInterfaceMember(this ISymbol symbol, internal static ISymbol FindImplementedInterfaceMember(this ISymbol symbol, INamedTypeSymbol interfaceSymbol, bool allInterfaces = false) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); - if (interfaceSymbol == null) + if (interfaceSymbol is null) throw new ArgumentNullException(nameof(interfaceSymbol)); return FindFirstImplementedInterfaceMemberImpl(symbol, interfaceSymbol, allInterfaces); @@ -72,13 +72,13 @@ private static ISymbol FindFirstImplementedInterfaceMemberImpl(this ISymbol symb { INamedTypeSymbol containingType = symbol.ContainingType; - if (containingType != null) + if (containingType is not null) { ImmutableArray interfaces = containingType.GetInterfaces(allInterfaces); for (int i = 0; i < interfaces.Length; i++) { - if (interfaceSymbol == null + if (interfaceSymbol is null || SymbolEqualityComparer.Default.Equals(interfaces[i], interfaceSymbol)) { ImmutableArray members = interfaces[i].GetMembers(); @@ -102,7 +102,7 @@ private static ISymbol FindFirstImplementedInterfaceMemberImpl(this ISymbol symb /// If true, use , otherwise use . public static bool ImplementsInterfaceMember(this ISymbol symbol, bool allInterfaces = false) { - return FindFirstImplementedInterfaceMember(symbol, allInterfaces) != null; + return FindFirstImplementedInterfaceMember(symbol, allInterfaces) is not null; } /// @@ -113,12 +113,12 @@ public static bool ImplementsInterfaceMember(this ISymbol symbol, bool allInterf /// If true, use , otherwise use . public static bool ImplementsInterfaceMember(this ISymbol symbol, INamedTypeSymbol interfaceSymbol, bool allInterfaces = false) { - return FindImplementedInterfaceMember(symbol, interfaceSymbol, allInterfaces) != null; + return FindImplementedInterfaceMember(symbol, interfaceSymbol, allInterfaces) is not null; } internal static TSymbol FindFirstImplementedInterfaceMember(this ISymbol symbol, bool allInterfaces = false) where TSymbol : ISymbol { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); return FindFirstImplementedInterfaceMemberImpl(symbol, null, allInterfaces); @@ -126,10 +126,10 @@ public static bool ImplementsInterfaceMember(this ISymbol symbol, INamedTypeSymb internal static TSymbol FindFirstImplementedInterfaceMember(this ISymbol symbol, INamedTypeSymbol interfaceSymbol, bool allInterfaces = false) where TSymbol : ISymbol { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); - if (interfaceSymbol == null) + if (interfaceSymbol is null) throw new ArgumentNullException(nameof(interfaceSymbol)); return FindFirstImplementedInterfaceMemberImpl(symbol, interfaceSymbol, allInterfaces); @@ -139,13 +139,13 @@ public static bool ImplementsInterfaceMember(this ISymbol symbol, INamedTypeSymb { INamedTypeSymbol containingType = symbol.ContainingType; - if (containingType != null) + if (containingType is not null) { ImmutableArray interfaces = containingType.GetInterfaces(allInterfaces); for (int i = 0; i < interfaces.Length; i++) { - if (interfaceSymbol == null + if (interfaceSymbol is null || SymbolEqualityComparer.Default.Equals(interfaces[i], interfaceSymbol)) { ImmutableArray members = interfaces[i].GetMembers(); @@ -210,7 +210,7 @@ public static bool IsKind(this ISymbol symbol, SymbolKind kind) /// public static bool IsKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind2) { - if (symbol == null) + if (symbol is null) return false; SymbolKind kind = symbol.Kind; @@ -228,7 +228,7 @@ public static bool IsKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind /// public static bool IsKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind2, SymbolKind kind3) { - if (symbol == null) + if (symbol is null) return false; SymbolKind kind = symbol.Kind; @@ -248,7 +248,7 @@ public static bool IsKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind /// public static bool IsKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind2, SymbolKind kind3, SymbolKind kind4) { - if (symbol == null) + if (symbol is null) return false; SymbolKind kind = symbol.Kind; @@ -270,7 +270,7 @@ public static bool IsKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind /// public static bool IsKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind2, SymbolKind kind3, SymbolKind kind4, SymbolKind kind5) { - if (symbol == null) + if (symbol is null) return false; SymbolKind kind = symbol.Kind; @@ -336,10 +336,10 @@ internal static SyntaxNode GetSyntaxOrDefault(this ISymbol symbol, CancellationT /// public static AttributeData GetAttribute(this ISymbol symbol, INamedTypeSymbol attributeClass) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); - if (attributeClass != null) + if (attributeClass is not null) { ImmutableArray attributes = symbol.GetAttributes(); @@ -360,7 +360,7 @@ public static AttributeData GetAttribute(this ISymbol symbol, INamedTypeSymbol a /// public static AttributeData GetAttribute(this ISymbol symbol, in MetadataName attributeName) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); foreach (AttributeData attributeData in symbol.GetAttributes()) @@ -379,7 +379,7 @@ public static AttributeData GetAttribute(this ISymbol symbol, in MetadataName at /// public static bool HasAttribute(this ISymbol symbol, INamedTypeSymbol attributeClass) { - return GetAttribute(symbol, attributeClass) != null; + return GetAttribute(symbol, attributeClass) is not null; } /// @@ -402,7 +402,7 @@ public static bool HasAttribute(this ITypeSymbol typeSymbol, INamedTypeSymbol at t = t.BaseType; } - while (t != null + while (t is not null && t.SpecialType != SpecialType.System_Object); return false; @@ -415,7 +415,7 @@ public static bool HasAttribute(this ITypeSymbol typeSymbol, INamedTypeSymbol at /// public static bool HasAttribute(this ISymbol symbol, in MetadataName attributeName) { - return GetAttribute(symbol, attributeName) != null; + return GetAttribute(symbol, attributeName) is not null; } /// @@ -438,7 +438,7 @@ public static bool HasAttribute(this ITypeSymbol typeSymbol, in MetadataName att t = t.BaseType; } - while (t != null + while (t is not null && t.SpecialType != SpecialType.System_Object); return false; @@ -446,7 +446,7 @@ public static bool HasAttribute(this ITypeSymbol typeSymbol, in MetadataName att internal static ImmutableArray ParametersOrDefault(this ISymbol symbol) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); switch (symbol.Kind) @@ -477,7 +477,7 @@ internal static ISymbol OverriddenSymbol(this ISymbol symbol) internal static ISymbol BaseOverriddenSymbol(this ISymbol symbol) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); switch (symbol.Kind) @@ -514,7 +514,7 @@ internal static bool IsContainingType(this ISymbol symbol, SpecialType specialTy /// public static bool IsPubliclyVisible(this ISymbol symbol) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); do @@ -529,7 +529,7 @@ public static bool IsPubliclyVisible(this ISymbol symbol) symbol = symbol.ContainingType; } - while (symbol != null); + while (symbol is not null); return true; } @@ -547,7 +547,7 @@ internal static bool IsPubliclyOrInternallyVisible(this ISymbol symbol) symbol = symbol.ContainingType; } - while (symbol != null); + while (symbol is not null); return true; } @@ -617,7 +617,7 @@ internal static Visibility GetVisibility(this ISymbol symbol) } } } - while (symbol != null); + while (symbol is not null); return visibility; } @@ -714,7 +714,7 @@ internal static ImmutableArray GetTypes(this IAssemblySymbol a void GetTypes(INamespaceOrTypeSymbol namespaceOrTypeSymbol) { if (namespaceOrTypeSymbol is INamedTypeSymbol namedTypeSymbol - && (predicate == null || predicate(namedTypeSymbol))) + && (predicate is null || predicate(namedTypeSymbol))) { builder.Add(namedTypeSymbol); } @@ -739,7 +739,7 @@ internal static ImmutableArray GetNamespaces(this IAssemblySym void GetNamespaces(INamespaceSymbol namespaceSymbol) { - if (predicate == null || predicate(namespaceSymbol)) + if (predicate is null || predicate(namespaceSymbol)) builder.Add(namespaceSymbol); foreach (INamespaceSymbol namespaceSymbol2 in namespaceSymbol.GetNamespaceMembers()) @@ -751,19 +751,19 @@ void GetNamespaces(INamespaceSymbol namespaceSymbol) #region IEventSymbol internal static IEventSymbol BaseOverriddenEvent(this IEventSymbol eventSymbol) { - if (eventSymbol == null) + if (eventSymbol is null) throw new ArgumentNullException(nameof(eventSymbol)); IEventSymbol overriddenEvent = eventSymbol.OverriddenEvent; - if (overriddenEvent == null) + if (overriddenEvent is null) return null; while (true) { IEventSymbol symbol = overriddenEvent.OverriddenEvent; - if (symbol == null) + if (symbol is null) return overriddenEvent; overriddenEvent = symbol; @@ -779,7 +779,7 @@ internal static IEventSymbol BaseOverriddenEvent(this IEventSymbol eventSymbol) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, bool value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -800,7 +800,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, bool value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, char value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -821,7 +821,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, char value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, sbyte value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -842,7 +842,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, sbyte value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, byte value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -863,7 +863,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, byte value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, short value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -884,7 +884,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, short value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, ushort value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -905,7 +905,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, ushort value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, int value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -926,7 +926,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, int value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, uint value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -947,7 +947,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, uint value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, long value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -968,7 +968,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, long value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, ulong value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -989,7 +989,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, ulong value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, decimal value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -1010,7 +1010,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, decimal value /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, float value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -1031,7 +1031,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, float value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, double value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -1052,7 +1052,7 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, double value) /// public static bool HasConstantValue(this IFieldSymbol fieldSymbol, string value) { - if (fieldSymbol == null) + if (fieldSymbol is null) throw new ArgumentNullException(nameof(fieldSymbol)); if (fieldSymbol.HasConstantValue) @@ -1070,19 +1070,19 @@ public static bool HasConstantValue(this IFieldSymbol fieldSymbol, string value) #region IMethodSymbol internal static IMethodSymbol BaseOverriddenMethod(this IMethodSymbol methodSymbol) { - if (methodSymbol == null) + if (methodSymbol is null) throw new ArgumentNullException(nameof(methodSymbol)); IMethodSymbol overriddenMethod = methodSymbol.OverriddenMethod; - if (overriddenMethod == null) + if (overriddenMethod is null) return null; while (true) { IMethodSymbol symbol = overriddenMethod.OverriddenMethod; - if (symbol == null) + if (symbol is null) return overriddenMethod; overriddenMethod = symbol; @@ -1201,7 +1201,7 @@ public static bool IsParameterArrayOf(this IParameterSymbol parameterSymbol, Spe /// public static bool IsRefOrOut(this IParameterSymbol parameterSymbol) { - if (parameterSymbol == null) + if (parameterSymbol is null) throw new ArgumentNullException(nameof(parameterSymbol)); RefKind refKind = parameterSymbol.RefKind; @@ -1214,19 +1214,19 @@ public static bool IsRefOrOut(this IParameterSymbol parameterSymbol) #region IPropertySymbol internal static IPropertySymbol BaseOverriddenProperty(this IPropertySymbol propertySymbol) { - if (propertySymbol == null) + if (propertySymbol is null) throw new ArgumentNullException(nameof(propertySymbol)); IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty == null) + if (overriddenProperty is null) return null; while (true) { IPropertySymbol symbol = overriddenProperty.OverriddenProperty; - if (symbol == null) + if (symbol is null) return overriddenProperty; overriddenProperty = symbol; @@ -1269,10 +1269,10 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb Func predicate, bool includeBaseTypes = false) where TSymbol : ISymbol { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); return FindMemberImpl(typeSymbol, name: null, predicate, includeBaseTypes); @@ -1292,7 +1292,7 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb Func predicate = null, bool includeBaseTypes = false) where TSymbol : ISymbol { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); return FindMemberImpl(typeSymbol, name, predicate, includeBaseTypes); @@ -1308,13 +1308,13 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb do { - members = (name != null) + members = (name is not null) ? typeSymbol.GetMembers(name) : typeSymbol.GetMembers(); TSymbol symbol = FindMemberImpl(members, predicate); - if (symbol != null) + if (symbol is not null) return symbol; if (!includeBaseTypes) @@ -1322,7 +1322,7 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb typeSymbol = typeSymbol.BaseType; } - while (typeSymbol != null); + while (typeSymbol is not null); return default; } @@ -1338,10 +1338,10 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb Func predicate, bool includeBaseTypes = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); return FindTypeMemberImpl(typeSymbol, name: null, arity: null, predicate, includeBaseTypes); @@ -1360,10 +1360,10 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb Func predicate = null, bool includeBaseTypes = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); return FindTypeMemberImpl(typeSymbol, name, arity: null, predicate, includeBaseTypes); @@ -1384,10 +1384,10 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb Func predicate = null, bool includeBaseTypes = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); - if (name == null) + if (name is null) throw new ArgumentNullException(nameof(name)); return FindTypeMemberImpl(typeSymbol, name, arity, predicate, includeBaseTypes); @@ -1404,9 +1404,9 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb do { - if (name != null) + if (name is not null) { - if (arity != null) + if (arity is not null) { members = typeSymbol.GetTypeMembers(name, arity.Value); } @@ -1422,7 +1422,7 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb INamedTypeSymbol symbol = FindMemberImpl(members, predicate); - if (symbol != null) + if (symbol is not null) return symbol; if (!includeBaseTypes) @@ -1430,7 +1430,7 @@ public static bool IsNullableOf(this INamedTypeSymbol namedTypeSymbol, ITypeSymb typeSymbol = typeSymbol.BaseType; } - while (typeSymbol != null); + while (typeSymbol is not null); return null; } @@ -1490,7 +1490,7 @@ public static bool IsObject(this ITypeSymbol typeSymbol) /// public static IEnumerable BaseTypes(this ITypeSymbol type) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); return BaseTypesIterator(); @@ -1499,7 +1499,7 @@ IEnumerable BaseTypesIterator() { INamedTypeSymbol baseType = type.BaseType; - while (baseType != null) + while (baseType is not null) { yield return baseType; baseType = baseType.BaseType; @@ -1513,7 +1513,7 @@ IEnumerable BaseTypesIterator() /// public static IEnumerable BaseTypesAndSelf(this ITypeSymbol typeSymbol) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); return BaseTypesAndSelfIterator(); @@ -1522,7 +1522,7 @@ IEnumerable BaseTypesAndSelfIterator() { ITypeSymbol current = typeSymbol; - while (current != null) + while (current is not null) { yield return current; current = current.BaseType; @@ -1538,7 +1538,7 @@ IEnumerable BaseTypesAndSelfIterator() /// If true, use , otherwise use . public static bool Implements(this ITypeSymbol typeSymbol, SpecialType interfaceType, bool allInterfaces = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); ImmutableArray interfaces = typeSymbol.GetInterfaces(allInterfaces); @@ -1554,7 +1554,7 @@ public static bool Implements(this ITypeSymbol typeSymbol, SpecialType interface internal static bool IsOrImplements(this ITypeSymbol typeSymbol, SpecialType interfaceType, bool allInterfaces = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); return typeSymbol.SpecialType == interfaceType @@ -1570,7 +1570,7 @@ internal static bool IsOrImplements(this ITypeSymbol typeSymbol, SpecialType int /// If true, use , otherwise use . public static bool ImplementsAny(this ITypeSymbol typeSymbol, SpecialType interfaceType1, SpecialType interfaceType2, bool allInterfaces = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); ImmutableArray interfaces = typeSymbol.GetInterfaces(allInterfaces); @@ -1594,7 +1594,7 @@ public static bool ImplementsAny(this ITypeSymbol typeSymbol, SpecialType interf /// If true, use , otherwise use . public static bool ImplementsAny(this ITypeSymbol typeSymbol, SpecialType interfaceType1, SpecialType interfaceType2, SpecialType interfaceType3, bool allInterfaces = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); ImmutableArray interfaces = typeSymbol.GetInterfaces(allInterfaces); @@ -1616,10 +1616,10 @@ public static bool ImplementsAny(this ITypeSymbol typeSymbol, SpecialType interf /// If true, use , otherwise use . public static bool Implements(this ITypeSymbol typeSymbol, INamedTypeSymbol interfaceSymbol, bool allInterfaces = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); - if (interfaceSymbol != null) + if (interfaceSymbol is not null) { ImmutableArray interfaces = typeSymbol.GetInterfaces(allInterfaces); @@ -1641,7 +1641,7 @@ public static bool Implements(this ITypeSymbol typeSymbol, INamedTypeSymbol inte /// public static bool Implements(this ITypeSymbol typeSymbol, in MetadataName interfaceName, bool allInterfaces = false) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.GetInterfaces(allInterfaces)) @@ -1659,7 +1659,7 @@ public static bool Implements(this ITypeSymbol typeSymbol, in MetadataName inter /// public static bool SupportsExplicitDeclaration(this ITypeSymbol typeSymbol) { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); if (typeSymbol.IsAnonymousType) @@ -1734,15 +1734,15 @@ static bool SupportsExplicitDeclaration2(ImmutableArray typeSymbols /// public static bool InheritsFrom(this ITypeSymbol type, ITypeSymbol baseType, bool includeInterfaces = false) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); - if (baseType == null) + if (baseType is null) return false; INamedTypeSymbol t = type.BaseType; - while (t != null) + while (t is not null) { Debug.Assert(t.TypeKind.Is(TypeKind.Class, TypeKind.Error), t.TypeKind.ToString()); @@ -1773,12 +1773,12 @@ public static bool InheritsFrom(this ITypeSymbol type, ITypeSymbol baseType, boo /// public static bool InheritsFrom(this ITypeSymbol type, in MetadataName baseTypeName, bool includeInterfaces = false) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); INamedTypeSymbol baseType = type.BaseType; - while (baseType != null) + while (baseType is not null) { if (baseType.HasMetadataName(baseTypeName)) return true; @@ -1806,7 +1806,7 @@ public static bool InheritsFrom(this ITypeSymbol type, in MetadataName baseTypeN /// public static bool EqualsOrInheritsFrom(this ITypeSymbol type, ITypeSymbol baseType, bool includeInterfaces = false) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); return SymbolEqualityComparer.Default.Equals(type, baseType) @@ -1821,7 +1821,7 @@ public static bool EqualsOrInheritsFrom(this ITypeSymbol type, ITypeSymbol baseT /// public static bool EqualsOrInheritsFrom(this ITypeSymbol type, in MetadataName baseTypeName, bool includeInterfaces = false) { - if (type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); return type.HasMetadataName(baseTypeName) @@ -1836,7 +1836,7 @@ public static bool EqualsOrInheritsFrom(this ITypeSymbol type, in MetadataName b /// public static TSymbol FindMember(this ITypeSymbol typeSymbol, Func predicate = null) where TSymbol : ISymbol { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); return FindMemberImpl(typeSymbol.GetMembers(), predicate); @@ -1851,7 +1851,7 @@ public static bool EqualsOrInheritsFrom(this ITypeSymbol type, in MetadataName b /// public static TSymbol FindMember(this ITypeSymbol typeSymbol, string name, Func predicate = null) where TSymbol : ISymbol { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); return FindMemberImpl(typeSymbol.GetMembers(name), predicate); @@ -1861,7 +1861,7 @@ public static bool EqualsOrInheritsFrom(this ITypeSymbol type, in MetadataName b where TSymbol : ISymbol where TMemberSymbol : ISymbol { - if (predicate != null) + if (predicate is not null) { foreach (TMemberSymbol symbol in members) { @@ -1892,10 +1892,10 @@ public static bool EqualsOrInheritsFrom(this ITypeSymbol type, in MetadataName b /// internal static bool ContainsMember(this ITypeSymbol typeSymbol, Func predicate = null) where TSymbol : ISymbol { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); - return FindMember(typeSymbol, predicate) != null; + return FindMember(typeSymbol, predicate) is not null; } /// @@ -1907,10 +1907,10 @@ public static bool EqualsOrInheritsFrom(this ITypeSymbol type, in MetadataName b /// internal static bool ContainsMember(this ITypeSymbol typeSymbol, string name, Func predicate = null) where TSymbol : ISymbol { - if (typeSymbol == null) + if (typeSymbol is null) throw new ArgumentNullException(nameof(typeSymbol)); - return FindMember(typeSymbol, name, predicate) != null; + return FindMember(typeSymbol, name, predicate) is not null; } internal static bool EqualsOrInheritsFromTaskOfT(this ITypeSymbol typeSymbol) diff --git a/src/Core/Extensions/SyntaxExtensions.cs b/src/Core/Extensions/SyntaxExtensions.cs index f15cc5eb51..22c510f9f7 100644 --- a/src/Core/Extensions/SyntaxExtensions.cs +++ b/src/Core/Extensions/SyntaxExtensions.cs @@ -59,7 +59,7 @@ public static class SyntaxExtensions /// public static bool Any(this SeparatedSyntaxList list, Func predicate) where TNode : SyntaxNode { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) @@ -79,7 +79,7 @@ public static class SyntaxExtensions /// public static bool All(this SeparatedSyntaxList list, Func predicate) where TNode : SyntaxNode { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) @@ -152,7 +152,7 @@ public static class SyntaxExtensions /// public static SeparatedSyntaxList WithTriviaFrom(this SeparatedSyntaxList list, SyntaxNode node) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); int count = list.Count; @@ -309,7 +309,7 @@ public static class SyntaxExtensions /// public static bool Any(this SyntaxList list, Func predicate) where TNode : SyntaxNode { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) @@ -329,7 +329,7 @@ public static class SyntaxExtensions /// public static bool All(this SyntaxList list, Func predicate) where TNode : SyntaxNode { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) @@ -422,7 +422,7 @@ public static class SyntaxExtensions /// public static SyntaxList WithTriviaFrom(this SyntaxList list, SyntaxNode node) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); int count = list.Count; @@ -515,7 +515,7 @@ public static class SyntaxExtensions /// public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); SyntaxTriviaList leadingTrivia = node.GetLeadingTrivia(); @@ -543,10 +543,10 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static TNode PrependToLeadingTrivia(this TNode node, IEnumerable trivia) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); - if (trivia == null) + if (trivia is null) throw new ArgumentNullException(nameof(trivia)); return node.WithLeadingTrivia(node.GetLeadingTrivia().InsertRange(0, trivia)); @@ -560,7 +560,7 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static TNode PrependToLeadingTrivia(this TNode node, SyntaxTrivia trivia) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node.WithLeadingTrivia(node.GetLeadingTrivia().Insert(0, trivia)); @@ -574,10 +574,10 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static TNode PrependToTrailingTrivia(this TNode node, IEnumerable trivia) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); - if (trivia == null) + if (trivia is null) throw new ArgumentNullException(nameof(trivia)); return node.WithTrailingTrivia(node.GetTrailingTrivia().InsertRange(0, trivia)); @@ -591,7 +591,7 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static TNode PrependToTrailingTrivia(this TNode node, SyntaxTrivia trivia) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node.WithTrailingTrivia(node.GetTrailingTrivia().Insert(0, trivia)); @@ -605,10 +605,10 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static TNode AppendToLeadingTrivia(this TNode node, IEnumerable trivia) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); - if (trivia == null) + if (trivia is null) throw new ArgumentNullException(nameof(trivia)); return node.WithLeadingTrivia(node.GetLeadingTrivia().AddRange(trivia)); @@ -622,7 +622,7 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static TNode AppendToLeadingTrivia(this TNode node, SyntaxTrivia trivia) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node.WithLeadingTrivia(node.GetLeadingTrivia().Add(trivia)); @@ -636,10 +636,10 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static TNode AppendToTrailingTrivia(this TNode node, IEnumerable trivia) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); - if (trivia == null) + if (trivia is null) throw new ArgumentNullException(nameof(trivia)); return node.WithTrailingTrivia(node.GetTrailingTrivia().AddRange(trivia)); @@ -653,7 +653,7 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static TNode AppendToTrailingTrivia(this TNode node, SyntaxTrivia trivia) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node.WithTrailingTrivia(node.GetTrailingTrivia().Add(trivia)); @@ -665,7 +665,7 @@ public static SyntaxTriviaList GetLeadingAndTrailingTrivia(this SyntaxNode node) /// public static bool SpanContainsDirectives(this SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node.ContainsDirectives @@ -675,7 +675,7 @@ public static bool SpanContainsDirectives(this SyntaxNode node) internal static bool SpanOrLeadingTriviaContainsDirectives(this SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node.ContainsDirectives @@ -684,7 +684,7 @@ internal static bool SpanOrLeadingTriviaContainsDirectives(this SyntaxNode node) internal static bool SpanOrTrailingTriviaContainsDirectives(this SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node.ContainsDirectives @@ -698,7 +698,7 @@ internal static bool SpanOrTrailingTriviaContainsDirectives(this SyntaxNode node /// public static bool ContainsDirectives(this SyntaxNode node, TextSpan span) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node.ContainsDirectives @@ -713,7 +713,7 @@ public static bool ContainsDirectives(this SyntaxNode node, TextSpan span) /// public static TNode WithTriviaFrom(this TNode node, SyntaxToken token) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return node @@ -753,7 +753,7 @@ internal static int GetFullSpanEndLine(this SyntaxNode node, CancellationToken c Func predicate = null, bool ascendOutOfTrivia = true) where TNode : SyntaxNode { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return GetParent(node, ascendOutOfTrivia: ascendOutOfTrivia)?.FirstAncestorOrSelf(predicate, ascendOutOfTrivia: ascendOutOfTrivia); @@ -761,7 +761,7 @@ internal static int GetFullSpanEndLine(this SyntaxNode node, CancellationToken c internal static string ToString(this SyntaxNode node, TextSpan span) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); TextSpan nodeFullSpan = node.FullSpan; @@ -789,7 +789,7 @@ internal static string ToString(this SyntaxNode node, TextSpan span) internal static TextSpan LeadingTriviaSpan(this SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return TextSpan.FromBounds(node.FullSpan.Start, node.SpanStart); @@ -797,7 +797,7 @@ internal static TextSpan LeadingTriviaSpan(this SyntaxNode node) internal static TextSpan TrailingTriviaSpan(this SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return TextSpan.FromBounds(node.Span.End, node.FullSpan.End); @@ -895,7 +895,7 @@ internal static SyntaxNode GetParent(this SyntaxNode node, bool ascendOutOfTrivi { SyntaxNode parent = node.Parent; - if (parent == null + if (parent is null && ascendOutOfTrivia && (node is IStructuredTriviaSyntax structuredTrivia)) { @@ -911,7 +911,7 @@ internal static SyntaxNode WalkUp(this SyntaxNode node, Func p { SyntaxNode parent = node.Parent; - if (parent != null + if (parent is not null && predicate(parent)) { node = parent; @@ -984,7 +984,7 @@ public static SyntaxNodeOrToken WithoutTrailingTrivia(this SyntaxNodeOrToken nod /// public static SyntaxToken PrependToLeadingTrivia(this SyntaxToken token, IEnumerable trivia) { - if (trivia == null) + if (trivia is null) throw new ArgumentNullException(nameof(trivia)); return token.WithLeadingTrivia(token.LeadingTrivia.InsertRange(0, trivia)); @@ -1007,7 +1007,7 @@ public static SyntaxToken PrependToLeadingTrivia(this SyntaxToken token, SyntaxT /// public static SyntaxToken PrependToTrailingTrivia(this SyntaxToken token, IEnumerable trivia) { - if (trivia == null) + if (trivia is null) throw new ArgumentNullException(nameof(trivia)); return token.WithTrailingTrivia(token.TrailingTrivia.InsertRange(0, trivia)); @@ -1030,7 +1030,7 @@ public static SyntaxToken PrependToTrailingTrivia(this SyntaxToken token, Syntax /// public static SyntaxToken AppendToTrailingTrivia(this SyntaxToken token, IEnumerable trivia) { - if (trivia == null) + if (trivia is null) throw new ArgumentNullException(nameof(trivia)); return token.WithTrailingTrivia(token.TrailingTrivia.AddRange(trivia)); @@ -1053,7 +1053,7 @@ public static SyntaxToken AppendToTrailingTrivia(this SyntaxToken token, SyntaxT /// public static SyntaxToken AppendToLeadingTrivia(this SyntaxToken token, IEnumerable trivia) { - if (trivia == null) + if (trivia is null) throw new ArgumentNullException(nameof(trivia)); return token.WithLeadingTrivia(token.LeadingTrivia.AddRange(trivia)); @@ -1137,7 +1137,7 @@ public static SyntaxToken WithoutTrailingTrivia(this SyntaxToken token) /// public static SyntaxToken WithTriviaFrom(this SyntaxToken token, SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return token @@ -1200,7 +1200,7 @@ public static SyntaxTokenList ReplaceAt(this SyntaxTokenList tokenList, int inde /// public static bool Any(this SyntaxTokenList list, Func predicate) { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) @@ -1219,7 +1219,7 @@ public static bool Any(this SyntaxTokenList list, Func predic /// public static bool All(this SyntaxTokenList list, Func predicate) { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) @@ -1248,7 +1248,7 @@ public static bool Contains(this SyntaxTokenList tokens, SyntaxToken token) /// public static int IndexOf(this SyntaxTokenList tokens, Func predicate) { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); int index = 0; @@ -1377,7 +1377,7 @@ public static SyntaxTriviaList ReplaceAt(this SyntaxTriviaList triviaList, int i /// public static bool Any(this SyntaxTriviaList list, Func predicate) { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) @@ -1396,7 +1396,7 @@ public static bool Any(this SyntaxTriviaList list, Func pred /// public static bool All(this SyntaxTriviaList list, Func predicate) { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); for (int i = 0; i < list.Count; i++) @@ -1415,7 +1415,7 @@ public static bool All(this SyntaxTriviaList list, Func pred /// public static int IndexOf(this SyntaxTriviaList triviaList, Func predicate) { - if (predicate == null) + if (predicate is null) throw new ArgumentNullException(nameof(predicate)); int index = 0; diff --git a/src/Core/Extensions/SyntaxTreeExtensions.cs b/src/Core/Extensions/SyntaxTreeExtensions.cs index 416c6a067b..18893bbf08 100644 --- a/src/Core/Extensions/SyntaxTreeExtensions.cs +++ b/src/Core/Extensions/SyntaxTreeExtensions.cs @@ -23,7 +23,7 @@ public static class SyntaxTreeExtensions TextSpan span, CancellationToken cancellationToken = default) { - if (syntaxTree == null) + if (syntaxTree is null) throw new ArgumentNullException(nameof(syntaxTree)); return syntaxTree.GetLineSpan(span, cancellationToken).StartLine(); @@ -40,7 +40,7 @@ public static class SyntaxTreeExtensions TextSpan span, CancellationToken cancellationToken = default) { - if (syntaxTree == null) + if (syntaxTree is null) throw new ArgumentNullException(nameof(syntaxTree)); return syntaxTree.GetLineSpan(span, cancellationToken).EndLine(); @@ -57,7 +57,7 @@ public static class SyntaxTreeExtensions TextSpan span, CancellationToken cancellationToken = default) { - if (syntaxTree == null) + if (syntaxTree is null) throw new ArgumentNullException(nameof(syntaxTree)); return syntaxTree.GetLineSpan(span, cancellationToken).IsMultiLine(); @@ -74,7 +74,7 @@ public static class SyntaxTreeExtensions TextSpan span, CancellationToken cancellationToken = default) { - if (syntaxTree == null) + if (syntaxTree is null) throw new ArgumentNullException(nameof(syntaxTree)); return syntaxTree.GetLineSpan(span, cancellationToken).IsSingleLine(); @@ -85,7 +85,7 @@ public static class SyntaxTreeExtensions TextSpan span, CancellationToken cancellationToken = default) { - if (syntaxTree == null) + if (syntaxTree is null) throw new ArgumentNullException(nameof(syntaxTree)); return syntaxTree.GetLineSpan(span, cancellationToken).GetLineCount(); diff --git a/src/Core/Extensions/TextSpanExtensions.cs b/src/Core/Extensions/TextSpanExtensions.cs index b0a5e88c00..bfec4f791c 100644 --- a/src/Core/Extensions/TextSpanExtensions.cs +++ b/src/Core/Extensions/TextSpanExtensions.cs @@ -36,7 +36,7 @@ public static bool IsContainedInSpan(this TextSpan span, SyntaxToken token1, Syn public static bool IsBetweenSpans(this TextSpan span, SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return span.IsBetweenSpans(node.Span, node.FullSpan); @@ -67,7 +67,7 @@ private static bool IsBetweenSpans(this TextSpan span, TextSpan innerSpan, TextS public static bool IsContainedInSpanOrBetweenSpans(this TextSpan span, SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); TextSpan innerSpan = node.Span; @@ -98,7 +98,7 @@ public static bool IsContainedInSpanOrBetweenSpans(this TextSpan span, SyntaxTok public static bool IsEmptyAndContainedInSpanOrBetweenSpans(this TextSpan span, SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return IsEmptyAndContainedInSpanOrBetweenSpans(span, node.Span, node.FullSpan); @@ -133,7 +133,7 @@ private static bool IsEmptyAndContainedInSpanOrBetweenSpans(this TextSpan span, public static bool IsEmptyAndContainedInSpan(this TextSpan span, SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); return span.IsEmpty diff --git a/src/Core/FileSystemHelpers.cs b/src/Core/FileSystemHelpers.cs index 8d9393b00f..7f4c9a61d3 100644 --- a/src/Core/FileSystemHelpers.cs +++ b/src/Core/FileSystemHelpers.cs @@ -46,7 +46,7 @@ public static bool TryGetNormalizedFullPath(string path, string basePath, out st { try { - if (basePath != null + if (basePath is not null && !Path.IsPathRooted(path)) { path = Path.Combine(basePath, path); diff --git a/src/Core/FlagsUtility`1.cs b/src/Core/FlagsUtility`1.cs index 7e9bbdb5f9..98d9a85c5e 100644 --- a/src/Core/FlagsUtility`1.cs +++ b/src/Core/FlagsUtility`1.cs @@ -98,7 +98,7 @@ private class SByteFlagsUtility : FlagsUtility internal override Optional GetUniquePowerOfTwo(IEnumerable reservedValues, bool startFromHighestExistingValue = false) { - if (reservedValues == null) + if (reservedValues is null) throw new ArgumentNullException(nameof(reservedValues)); sbyte[] values = reservedValues.Where(f => f >= 0 && IsZeroOrPowerOfTwo(f)).ToArray(); @@ -190,7 +190,7 @@ private class ByteFlagsUtility : FlagsUtility internal override Optional GetUniquePowerOfTwo(IEnumerable reservedValues, bool startFromHighestExistingValue = false) { - if (reservedValues == null) + if (reservedValues is null) throw new ArgumentNullException(nameof(reservedValues)); byte[] values = reservedValues.Where(f => IsZeroOrPowerOfTwo(f)).ToArray(); @@ -282,7 +282,7 @@ private class ShortFlagsUtility : FlagsUtility internal override Optional GetUniquePowerOfTwo(IEnumerable reservedValues, bool startFromHighestExistingValue = false) { - if (reservedValues == null) + if (reservedValues is null) throw new ArgumentNullException(nameof(reservedValues)); short[] values = reservedValues.Where(f => f >= 0 && IsZeroOrPowerOfTwo(f)).ToArray(); @@ -374,7 +374,7 @@ private class UShortFlagsUtility : FlagsUtility internal override Optional GetUniquePowerOfTwo(IEnumerable reservedValues, bool startFromHighestExistingValue = false) { - if (reservedValues == null) + if (reservedValues is null) throw new ArgumentNullException(nameof(reservedValues)); ushort[] values = reservedValues.Where(f => IsZeroOrPowerOfTwo(f)).ToArray(); @@ -466,7 +466,7 @@ private class IntFlagsUtility : FlagsUtility internal override Optional GetUniquePowerOfTwo(IEnumerable reservedValues, bool startFromHighestExistingValue = false) { - if (reservedValues == null) + if (reservedValues is null) throw new ArgumentNullException(nameof(reservedValues)); int[] values = reservedValues.Where(f => f >= 0 && IsZeroOrPowerOfTwo(f)).ToArray(); @@ -558,7 +558,7 @@ private class UIntFlagsUtility : FlagsUtility internal override Optional GetUniquePowerOfTwo(IEnumerable reservedValues, bool startFromHighestExistingValue = false) { - if (reservedValues == null) + if (reservedValues is null) throw new ArgumentNullException(nameof(reservedValues)); uint[] values = reservedValues.Where(f => IsZeroOrPowerOfTwo(f)).ToArray(); @@ -650,7 +650,7 @@ private class LongFlagsUtility : FlagsUtility internal override Optional GetUniquePowerOfTwo(IEnumerable reservedValues, bool startFromHighestExistingValue = false) { - if (reservedValues == null) + if (reservedValues is null) throw new ArgumentNullException(nameof(reservedValues)); long[] values = reservedValues.Where(f => f >= 0 && IsZeroOrPowerOfTwo(f)).ToArray(); @@ -742,7 +742,7 @@ private class ULongFlagsUtility : FlagsUtility internal override Optional GetUniquePowerOfTwo(IEnumerable reservedValues, bool startFromHighestExistingValue = false) { - if (reservedValues == null) + if (reservedValues is null) throw new ArgumentNullException(nameof(reservedValues)); ulong[] values = reservedValues.Where(f => IsZeroOrPowerOfTwo(f)).ToArray(); diff --git a/src/Core/GeneratedCodeUtility.cs b/src/Core/GeneratedCodeUtility.cs index f7e7c57d30..4287357ae0 100644 --- a/src/Core/GeneratedCodeUtility.cs +++ b/src/Core/GeneratedCodeUtility.cs @@ -34,7 +34,7 @@ public static bool IsGeneratedCode(SyntaxTree tree, Func isC SyntaxTree tree = node.SyntaxTree; - if (tree != null + if (tree is not null && IsGeneratedCode(tree, isComment, cancellationToken)) { return true; @@ -113,7 +113,7 @@ internal static bool BeginsWithAutoGeneratedComment(SyntaxNode root, Func(IEnumerable values, IEqualityComparer comparer = null, int maxItemsToHash = int.MaxValue) { - if (values == null) + if (values is null) return 0; - if (comparer == null) + if (comparer is null) comparer = EqualityComparer.Default; int hash = 0; @@ -73,10 +73,10 @@ public static int CombineValues(IEnumerable values, IEqualityComparer c public static int CombineValues(T[] values, IEqualityComparer comparer = null, int maxItemsToHash = int.MaxValue) { - if (values == null) + if (values is null) return 0; - if (comparer == null) + if (comparer is null) comparer = EqualityComparer.Default; int hash = 0; @@ -99,7 +99,7 @@ public static int CombineValues(ImmutableArray values, IEqualityComparer.Default; int hash = 0; @@ -122,7 +122,7 @@ public static int CombineValues(ImmutableArray values, IEqualityComparer(ImmutableArray values, IEqualityComparer= maxItemsToHash) break; - if (value != null) + if (value is not null) hash = Combine(stringComparer.GetHashCode(value), hash); count++; @@ -147,7 +147,7 @@ public static int CombineValues(ImmutableArray values, IEqualityComparer(ImmutableArray values, IEqualityComparer(ImmutableArray values, IEqualityComparer containingNamespaces, string name) : this(containingNamespaces, Array.Empty(), name) { - if (containingNamespaces == null) + if (containingNamespaces is null) throw new ArgumentNullException(nameof(containingNamespaces)); Name = name ?? throw new ArgumentNullException(nameof(name)); @@ -43,10 +43,10 @@ public MetadataName(IEnumerable containingNamespaces, string name) /// public MetadataName(IEnumerable containingNamespaces, IEnumerable containingTypes, string name) { - if (containingNamespaces == null) + if (containingNamespaces is null) throw new ArgumentNullException(nameof(containingNamespaces)); - if (containingTypes == null) + if (containingTypes is null) throw new ArgumentNullException(nameof(containingTypes)); Name = name ?? throw new ArgumentNullException(nameof(name)); @@ -103,7 +103,7 @@ public MetadataName(ImmutableArray containingNamespaces, ImmutableArray< /// public bool IsDefault { - get { return Name == null; } + get { return Name is null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] @@ -178,7 +178,7 @@ public override bool Equals(object obj) internal bool Equals(ISymbol symbol) { - if (symbol == null) + if (symbol is null) return false; if (!string.Equals(Name, symbol.MetadataName, StringComparison.Ordinal)) @@ -188,7 +188,7 @@ internal bool Equals(ISymbol symbol) for (int i = ContainingTypes.Length - 1; i >= 0; i--) { - if (containingType == null) + if (containingType is null) return false; if (!string.Equals(containingType.MetadataName, ContainingTypes[i], StringComparison.Ordinal)) @@ -197,7 +197,7 @@ internal bool Equals(ISymbol symbol) containingType = containingType.ContainingType; } - if (containingType != null) + if (containingType is not null) return false; INamespaceSymbol containingNamespace = symbol.ContainingNamespace; @@ -328,7 +328,7 @@ public static bool TryParse(string name, out MetadataName metadataName) private static MetadataName Parse(string name, bool shouldThrow) { - if (name == null) + if (name is null) { if (shouldThrow) throw new ArgumentNullException(nameof(name)); @@ -413,7 +413,7 @@ private static MetadataName Parse(string name, bool shouldThrow) { string n = name.Substring(prevIndex, i - prevIndex); - if (containingTypes != null) + if (containingTypes is not null) { containingTypes.Add(n); } @@ -428,7 +428,7 @@ private static MetadataName Parse(string name, bool shouldThrow) return new MetadataName( containingNamespaces?.MoveToImmutable() ?? ImmutableArray.Empty, - (containingType != null) + (containingType is not null) ? ImmutableArray.Create(containingType) : containingTypes?.MoveToImmutable() ?? ImmutableArray.Empty, name.Substring(prevIndex, length - prevIndex)); diff --git a/src/Core/MetadataNameEqualityComparer`1.cs b/src/Core/MetadataNameEqualityComparer`1.cs index 6b564d1def..090b9f7818 100644 --- a/src/Core/MetadataNameEqualityComparer`1.cs +++ b/src/Core/MetadataNameEqualityComparer`1.cs @@ -126,10 +126,10 @@ public override bool Equals(TSymbol x, TSymbol y) while (!object.ReferenceEquals(t1, t2)) { - if (t1 == null) + if (t1 is null) return false; - if (t2 == null) + if (t2 is null) return false; if (!StringComparer.Ordinal.Equals(t1.MetadataName, t2.MetadataName)) @@ -144,10 +144,10 @@ public override bool Equals(TSymbol x, TSymbol y) while (!object.ReferenceEquals(n1, n2)) { - if (n1 == null) + if (n1 is null) return false; - if (n2 == null) + if (n2 is null) return false; if (!StringComparer.Ordinal.Equals(n1.MetadataName, n2.MetadataName)) @@ -168,7 +168,7 @@ public override bool Equals(TSymbol x, TSymbol y) /// is null. public override int GetHashCode(TSymbol obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); if (Default.Equals(obj, default(TSymbol))) @@ -178,13 +178,13 @@ public override int GetHashCode(TSymbol obj) INamedTypeSymbol t = obj.ContainingType; - if (t != null) + if (t is not null) { hashCode = Combine(t); t = t.ContainingType; - while (t != null) + while (t is not null) { hashCode = Hash.Combine(MetadataName.PlusHashCode, hashCode); @@ -196,13 +196,13 @@ public override int GetHashCode(TSymbol obj) INamespaceSymbol n = obj.ContainingNamespace; - if (n != null) + if (n is not null) { hashCode = Combine(n); n = n.ContainingNamespace; - while (n != null) + while (n is not null) { hashCode = Hash.Combine(MetadataName.DotHashCode, hashCode); diff --git a/src/Core/NameGenerator.cs b/src/Core/NameGenerator.cs index 7aa4569a59..e19b2049d1 100644 --- a/src/Core/NameGenerator.cs +++ b/src/Core/NameGenerator.cs @@ -57,7 +57,7 @@ public static NameGenerator Default int position, bool isCaseSensitive = true) { - if (semanticModel == null) + if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); return EnsureUniqueName(baseName, semanticModel.LookupSymbols(position), isCaseSensitive); @@ -74,7 +74,7 @@ public static NameGenerator Default INamedTypeSymbol enumType, bool isCaseSensitive = true) { - if (enumType == null) + if (enumType is null) throw new ArgumentNullException(nameof(enumType)); if (enumType.TypeKind != TypeKind.Enum) @@ -98,7 +98,7 @@ public static NameGenerator Default bool isCaseSensitive = true, CancellationToken cancellationToken = default) { - if (semanticModel == null) + if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); ImmutableArray symbols = GetSymbolsForUniqueLocalName(semanticModel, position, cancellationToken); @@ -123,7 +123,7 @@ public static NameGenerator Default bool isCaseSensitive = true, CancellationToken cancellationToken = default) { - if (semanticModel == null) + if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); if (count < 1) @@ -179,10 +179,10 @@ public static NameGenerator Default bool isCaseSensitive = true, CancellationToken cancellationToken = default) { - if (containingSymbol == null) + if (containingSymbol is null) throw new ArgumentNullException(nameof(containingSymbol)); - if (semanticModel == null) + if (semanticModel is null) throw new ArgumentNullException(nameof(semanticModel)); if (containingSymbol.Kind == SymbolKind.Method) @@ -248,7 +248,7 @@ public static string CreateName(ITypeSymbol typeSymbol, bool firstCharToLower = { string name = CreateNameFromTypeSymbolHelper.CreateName(typeSymbol); - if (name != null + if (name is not null && firstCharToLower) { return StringUtility.FirstCharToLower(name); @@ -264,11 +264,11 @@ public static string CreateName(ITypeSymbol typeSymbol, bool firstCharToLower = bool isCaseSensitive = true, CancellationToken cancellationToken = default) { - if (typeSymbol != null) + if (typeSymbol is not null) { string name = CreateName(typeSymbol, firstCharToLower: true); - if (name != null) + if (name is not null) return EnsureUniqueLocalName(name, semanticModel, position, isCaseSensitive, cancellationToken); } @@ -285,7 +285,7 @@ public static string CreateName(ITypeSymbol typeSymbol, bool firstCharToLower = { string newName = CreateName(typeSymbol, firstCharToLower: true); - if (newName != null + if (newName is not null && !string.Equals(oldName, newName, StringComparison.Ordinal)) { string uniqueName = EnsureUniqueLocalName(newName, semanticModel, position, isCaseSensitive, cancellationToken); @@ -306,7 +306,7 @@ public static string CreateName(ITypeSymbol typeSymbol, bool firstCharToLower = { string newName = CreateName(parameterSymbol.Type, firstCharToLower: true); - if (newName != null + if (newName is not null && !string.Equals(oldName, newName, StringComparison.Ordinal)) { string uniqueName = EnsureUniqueParameterName(newName, parameterSymbol.ContainingSymbol, semanticModel, isCaseSensitive, cancellationToken); diff --git a/src/Core/OneOrMany.cs b/src/Core/OneOrMany.cs index b892b8ec53..61251f48b1 100644 --- a/src/Core/OneOrMany.cs +++ b/src/Core/OneOrMany.cs @@ -15,7 +15,7 @@ public static OneOrMany Create(T value) public static OneOrMany Create(IEnumerable values) { - if (values == null) + if (values is null) throw new ArgumentNullException(nameof(values)); return Create(values.ToImmutableArray()); diff --git a/src/Core/OverriddenSymbolInfo.cs b/src/Core/OverriddenSymbolInfo.cs index e15322317f..0f2aa71817 100644 --- a/src/Core/OverriddenSymbolInfo.cs +++ b/src/Core/OverriddenSymbolInfo.cs @@ -22,7 +22,7 @@ public OverriddenSymbolInfo(ISymbol symbol, ISymbol overriddenSymbol) public bool Success { - get { return Symbol != null; } + get { return Symbol is not null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] diff --git a/src/Core/SeparatedSyntaxListSelection`1.cs b/src/Core/SeparatedSyntaxListSelection`1.cs index c420613315..f249ae3b3c 100644 --- a/src/Core/SeparatedSyntaxListSelection`1.cs +++ b/src/Core/SeparatedSyntaxListSelection`1.cs @@ -136,19 +136,19 @@ public static SeparatedSyntaxListSelection Create(SeparatedSyntaxList list, TextSpan span, out SeparatedSyntaxListSelection selection) { selection = Create(list, span, 1, int.MaxValue); - return selection != null; + return selection is not null; } internal static bool TryCreate(SeparatedSyntaxList list, TextSpan span, int minCount, out SeparatedSyntaxListSelection selection) { selection = Create(list, span, minCount, int.MaxValue); - return selection != null; + return selection is not null; } internal static bool TryCreate(SeparatedSyntaxList list, TextSpan span, int minCount, int maxCount, out SeparatedSyntaxListSelection selection) { selection = Create(list, span, minCount, maxCount); - return selection != null; + return selection is not null; } private static SeparatedSyntaxListSelection Create(SeparatedSyntaxList list, TextSpan span, int minCount, int maxCount) diff --git a/src/Core/StringUtility.cs b/src/Core/StringUtility.cs index 9708d48d24..3cf83a424d 100644 --- a/src/Core/StringUtility.cs +++ b/src/Core/StringUtility.cs @@ -10,7 +10,7 @@ internal static class StringUtility { internal static bool IsNullOrEquals(string s, string value) { - return s == null + return s is null || Equals(s, value); } @@ -27,7 +27,7 @@ internal static bool Equals(string s, string value) public static string FirstCharToLower(string value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.Length > 0) @@ -42,7 +42,7 @@ public static string FirstCharToLower(string value) public static string FirstCharToUpper(string value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); if (value.Length > 0) @@ -68,7 +68,7 @@ public static bool IsEmptyOrWhitespace(string value) public static string GetLeadingWhitespaceExceptNewLine(string value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); for (int i = 0; i < value.Length; i++) @@ -100,7 +100,7 @@ public static string EscapeQuote(string value) public static string ToCamelCase(string value, bool prefixWithUnderscore = false) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); string prefix = (prefixWithUnderscore) ? "_" : ""; @@ -143,10 +143,10 @@ public static string ToCamelCase(string value, bool prefixWithUnderscore = false public static bool HasPrefix(string value, string prefix, StringComparison comparison = StringComparison.Ordinal) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (prefix == null) + if (prefix is null) throw new ArgumentNullException(nameof(prefix)); return prefix.Length > 0 @@ -157,10 +157,10 @@ public static bool HasPrefix(string value, string prefix, StringComparison compa public static bool HasSuffix(string value, string suffix, StringComparison comparison = StringComparison.Ordinal) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (suffix == null) + if (suffix is null) throw new ArgumentNullException(nameof(suffix)); return suffix.Length > 0 @@ -258,7 +258,7 @@ public static bool TryRemoveSuffix(string value, string suffix, StringComparison public static bool IsOneOrManyUnderscores(string value) { - if (value == null) + if (value is null) return false; int length = value.Length; diff --git a/src/Core/SymbolUtility.cs b/src/Core/SymbolUtility.cs index f0b9362516..d530941df7 100644 --- a/src/Core/SymbolUtility.cs +++ b/src/Core/SymbolUtility.cs @@ -95,7 +95,7 @@ public static bool IsEventHandlerMethod(IMethodSymbol methodSymbol) SemanticModel semanticModel, int position) { - if (typeSymbol == null) + if (typeSymbol is null) return false; SymbolKind symbolKind = typeSymbol.Kind; @@ -108,7 +108,7 @@ public static bool IsEventHandlerMethod(IMethodSymbol methodSymbol) bool? hasIndexer = HasIndexer(typeSymbol.SpecialType); - if (hasIndexer != null) + if (hasIndexer is not null) return hasIndexer.Value; ITypeSymbol originalDefinition = typeSymbol.OriginalDefinition; @@ -117,7 +117,7 @@ public static bool IsEventHandlerMethod(IMethodSymbol methodSymbol) { hasIndexer = HasIndexer(originalDefinition.SpecialType); - if (hasIndexer != null) + if (hasIndexer is not null) return hasIndexer.Value; } @@ -170,7 +170,7 @@ public static bool IsEventHandlerMethod(IMethodSymbol methodSymbol) string propertyName = GetCountOrLengthPropertyName(typeSymbol.SpecialType); - if (propertyName != null) + if (propertyName is not null) return (propertyName.Length > 0) ? propertyName : null; ITypeSymbol originalDefinition = typeSymbol.OriginalDefinition; @@ -179,7 +179,7 @@ public static bool IsEventHandlerMethod(IMethodSymbol methodSymbol) { propertyName = GetCountOrLengthPropertyName(originalDefinition.SpecialType); - if (propertyName != null) + if (propertyName is not null) return (propertyName.Length > 0) ? propertyName : null; } @@ -340,7 +340,7 @@ internal static bool IsLinqSelect(IMethodSymbol methodSymbol, bool allowImmutabl INamedTypeSymbol containingType = methodSymbol.ContainingType; - if (containingType == null) + if (containingType is null) return false; if (containingType.HasMetadataName(MetadataNames.System_Linq_Enumerable)) @@ -417,7 +417,7 @@ internal static bool IsLinqOfType(IMethodSymbol methodSymbol) INamedTypeSymbol containingType = methodSymbol.ContainingType; - if (containingType == null) + if (containingType is null) return false; if (containingType.HasMetadataName(MetadataNames.System_Linq_Enumerable)) @@ -461,7 +461,7 @@ internal static bool IsLinqOfType(IMethodSymbol methodSymbol) INamedTypeSymbol containingType = methodSymbol.ContainingType; - if (containingType == null) + if (containingType is null) return false; if (containingType.HasMetadataName(MetadataNames.System_Linq_Enumerable)) @@ -586,12 +586,12 @@ public static IMethodSymbol FindMethodThatRaisePropertyChanged(INamedTypeSymbol IMethodSymbol methodSymbol = FindMethod(typeSymbol.GetMembers("RaisePropertyChanged")) ?? FindMethod(typeSymbol.GetMembers("OnPropertyChanged")); - if (methodSymbol != null) + if (methodSymbol is not null) return methodSymbol; typeSymbol = typeSymbol.BaseType; } - while (typeSymbol != null + while (typeSymbol is not null && typeSymbol.SpecialType != SpecialType.System_Object); return null; @@ -620,7 +620,7 @@ public static bool IsAwaitable(ITypeSymbol typeSymbol, bool shouldCheckWindowsRu { INamedTypeSymbol namedTypeSymbol = GetPossiblyAwaitableType(typeSymbol); - if (namedTypeSymbol == null) + if (namedTypeSymbol is null) return false; INamedTypeSymbol originalDefinition = namedTypeSymbol.OriginalDefinition; @@ -673,7 +673,7 @@ internal static INamedTypeSymbol GetPossiblyAwaitableType(ITypeSymbol typeSymbol typeSymbol = typeParameterSymbol.ConstraintTypes.SingleOrDefault(f => f.TypeKind == TypeKind.Class, shouldThrow: false); - if (typeSymbol == null) + if (typeSymbol is null) return null; } diff --git a/src/Core/SyntaxListSelection`1.cs b/src/Core/SyntaxListSelection`1.cs index 13b66b1968..eb7ae99a36 100644 --- a/src/Core/SyntaxListSelection`1.cs +++ b/src/Core/SyntaxListSelection`1.cs @@ -136,19 +136,19 @@ public static SyntaxListSelection Create(SyntaxList list, TextSpan public static bool TryCreate(SyntaxList list, TextSpan span, out SyntaxListSelection selection) { selection = Create(list, span, 1, int.MaxValue); - return selection != null; + return selection is not null; } internal static bool TryCreate(SyntaxList list, TextSpan span, int minCount, out SyntaxListSelection selection) { selection = Create(list, span, minCount, int.MaxValue); - return selection != null; + return selection is not null; } internal static bool TryCreate(SyntaxList list, TextSpan span, int minCount, int maxCount, out SyntaxListSelection selection) { selection = Create(list, span, minCount, maxCount); - return selection != null; + return selection is not null; } private static SyntaxListSelection Create(SyntaxList list, TextSpan span, int minCount, int maxCount) diff --git a/src/Core/SyntaxUtility.cs b/src/Core/SyntaxUtility.cs index 81bfb42ba1..f72612fc82 100644 --- a/src/Core/SyntaxUtility.cs +++ b/src/Core/SyntaxUtility.cs @@ -25,7 +25,7 @@ internal static class SyntaxUtility { var enumTypeSymbol = (INamedTypeSymbol)semanticModel.GetTypeSymbol(node, cancellationToken); - if (enumTypeSymbol.EnumUnderlyingType != null) + if (enumTypeSymbol.EnumUnderlyingType is not null) { Optional constantValue = semanticModel.GetConstantValue(node, cancellationToken); diff --git a/src/Core/Text/StringBuilderCache.cs b/src/Core/Text/StringBuilderCache.cs index 7a4b91dbb1..0e72d8fc8a 100644 --- a/src/Core/Text/StringBuilderCache.cs +++ b/src/Core/Text/StringBuilderCache.cs @@ -19,7 +19,7 @@ public static StringBuilder GetInstance(int capacity = DefaultCapacity) { StringBuilder sb = _cachedInstance; - if (sb != null + if (sb is not null && capacity <= sb.Capacity) { _cachedInstance = null; diff --git a/src/Core/Text/TextLineCollectionSelection.cs b/src/Core/Text/TextLineCollectionSelection.cs index fe38ad56ac..445f16948d 100644 --- a/src/Core/Text/TextLineCollectionSelection.cs +++ b/src/Core/Text/TextLineCollectionSelection.cs @@ -116,7 +116,7 @@ public TextLine Last() /// public static TextLineCollectionSelection Create(TextLineCollection lines, TextSpan span) { - if (lines == null) + if (lines is null) throw new ArgumentNullException(nameof(lines)); SelectionResult result = SelectionResult.Create(lines, span); @@ -134,24 +134,24 @@ public static TextLineCollectionSelection Create(TextLineCollection lines, TextS public static bool TryCreate(TextLineCollection lines, TextSpan span, out TextLineCollectionSelection selectedLines) { selectedLines = Create(lines, span, 1, int.MaxValue); - return selectedLines != null; + return selectedLines is not null; } internal static bool TryCreate(TextLineCollection lines, TextSpan span, int minCount, out TextLineCollectionSelection selectedLines) { selectedLines = Create(lines, span, minCount, int.MaxValue); - return selectedLines != null; + return selectedLines is not null; } internal static bool TryCreate(TextLineCollection lines, TextSpan span, int minCount, int maxCount, out TextLineCollectionSelection selectedLines) { selectedLines = Create(lines, span, minCount, maxCount); - return selectedLines != null; + return selectedLines is not null; } private static TextLineCollectionSelection Create(TextLineCollection lines, TextSpan span, int minCount, int maxCount) { - if (lines == null) + if (lines is null) return null; SelectionResult result = SelectionResult.Create(lines, span, minCount, maxCount); diff --git a/src/Documentation/AbstractSymbolDefinitionTextWriter.cs b/src/Documentation/AbstractSymbolDefinitionTextWriter.cs index 8abf0c25c8..317c9b98b4 100644 --- a/src/Documentation/AbstractSymbolDefinitionTextWriter.cs +++ b/src/Documentation/AbstractSymbolDefinitionTextWriter.cs @@ -98,7 +98,7 @@ public override void WriteStartType(INamedTypeSymbol typeSymbol) public override void WriteTypeDefinition(INamedTypeSymbol typeSymbol, SymbolDisplayFormat format = null) { - if (typeSymbol != null) + if (typeSymbol is not null) { WriteDocumentationComment(typeSymbol); WriteDefinition(typeSymbol, format); diff --git a/src/Documentation/DocumentationGenerator.cs b/src/Documentation/DocumentationGenerator.cs index 1ec2d55e22..d9ad3a8ed2 100644 --- a/src/Documentation/DocumentationGenerator.cs +++ b/src/Documentation/DocumentationGenerator.cs @@ -373,14 +373,14 @@ private DocumentationGeneratorResult GenerateNamespace(INamespaceSymbol namespac } case NamespaceDocumentationParts.Examples: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteExamples(namespaceSymbol, xmlDocumentation); break; } case NamespaceDocumentationParts.Remarks: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteRemarks(namespaceSymbol, xmlDocumentation); break; @@ -428,7 +428,7 @@ private DocumentationGeneratorResult GenerateNamespace(INamespaceSymbol namespac } case NamespaceDocumentationParts.SeeAlso: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteSeeAlso(namespaceSymbol, xmlDocumentation); break; @@ -625,7 +625,7 @@ private DocumentationGeneratorResult GenerateType(TypeDocumentationModel typeMod { INamespaceSymbol containingNamespace = typeModel.ContainingNamespace; - if (containingNamespace != null) + if (containingNamespace is not null) writer.WriteContainingNamespace(containingNamespace, Resources.NamespaceTitle); break; @@ -644,7 +644,7 @@ private DocumentationGeneratorResult GenerateType(TypeDocumentationModel typeMod } case TypeDocumentationParts.Summary: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteSummary(typeSymbol, xmlDocumentation); break; @@ -666,7 +666,7 @@ private DocumentationGeneratorResult GenerateType(TypeDocumentationModel typeMod } case TypeDocumentationParts.ReturnValue: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteReturnType(typeSymbol, xmlDocumentation); break; @@ -695,14 +695,14 @@ private DocumentationGeneratorResult GenerateType(TypeDocumentationModel typeMod } case TypeDocumentationParts.Examples: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteExamples(typeSymbol, xmlDocumentation); break; } case TypeDocumentationParts.Remarks: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteRemarks(typeSymbol, xmlDocumentation); break; @@ -787,14 +787,14 @@ private DocumentationGeneratorResult GenerateType(TypeDocumentationModel typeMod } case TypeDocumentationParts.AppliesTo: { - if (SourceReferenceProvider != null) + if (SourceReferenceProvider is not null) writer.WriteAppliesTo(typeSymbol, SourceReferenceProvider.GetSourceReferences(typeSymbol)); break; } case TypeDocumentationParts.SeeAlso: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteSeeAlso(typeSymbol, xmlDocumentation); break; @@ -1015,7 +1015,7 @@ void GenerateMemberContent(DocumentationWriter writer, ISymbol symbol, int headi } case MemberDocumentationParts.Summary: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteSummary(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); break; @@ -1052,28 +1052,28 @@ void GenerateMemberContent(DocumentationWriter writer, ISymbol symbol, int headi } case MemberDocumentationParts.Exceptions: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteExceptions(symbol, xmlDocumentation); break; } case MemberDocumentationParts.Examples: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteExamples(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); break; } case MemberDocumentationParts.Remarks: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteRemarks(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); break; } case MemberDocumentationParts.AppliesTo: { - if (SourceReferenceProvider == null) + if (SourceReferenceProvider is null) break; writer.WriteAppliesTo(symbol, SourceReferenceProvider.GetSourceReferences(symbol), headingLevelBase: headingLevelBase); @@ -1082,7 +1082,7 @@ void GenerateMemberContent(DocumentationWriter writer, ISymbol symbol, int headi } case MemberDocumentationParts.SeeAlso: { - if (xmlDocumentation != null) + if (xmlDocumentation is not null) writer.WriteSeeAlso(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); break; diff --git a/src/Documentation/DocumentationModel.cs b/src/Documentation/DocumentationModel.cs index a2a7b44bee..7d5614bcc0 100644 --- a/src/Documentation/DocumentationModel.cs +++ b/src/Documentation/DocumentationModel.cs @@ -39,7 +39,7 @@ public sealed class DocumentationModel _symbolData = new Dictionary(); _xmlDocumentations = new Dictionary(); - if (additionalXmlDocumentationPaths != null) + if (additionalXmlDocumentationPaths is not null) _additionalXmlDocumentationPaths = additionalXmlDocumentationPaths.ToImmutableArray(); } @@ -55,7 +55,7 @@ public sealed class DocumentationModel _symbolData = new Dictionary(); _xmlDocumentations = new Dictionary(); - if (additionalXmlDocumentationPaths != null) + if (additionalXmlDocumentationPaths is not null) _additionalXmlDocumentationPaths = additionalXmlDocumentationPaths.ToImmutableArray(); } @@ -163,7 +163,7 @@ IEnumerable Iterator() { INamedTypeSymbol typeSymbol = GetExternalSymbol(methodSymbol); - if (typeSymbol != null) + if (typeSymbol is not null) yield return typeSymbol; } } @@ -172,7 +172,7 @@ INamedTypeSymbol GetExternalSymbol(IMethodSymbol methodSymbol) { INamedTypeSymbol type = GetExtendedType(methodSymbol); - if (type == null) + if (type is null) return null; foreach (IAssemblySymbol assembly in Assemblies) @@ -231,7 +231,7 @@ public bool IsExternal(ISymbol symbol) public TypeDocumentationModel GetTypeModel(INamedTypeSymbol typeSymbol) { if (_symbolData.TryGetValue(typeSymbol, out SymbolDocumentationData data) - && data.Model != null) + && data.Model is not null) { return (TypeDocumentationModel)data.Model; } @@ -252,7 +252,7 @@ internal ISymbol GetFirstSymbolForDeclarationId(string id) { ISymbol symbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(id, compilation); - if (symbol != null) + if (symbol is not null) return symbol; } @@ -268,7 +268,7 @@ internal ISymbol GetFirstSymbolForReferenceId(string id) { ISymbol symbol = DocumentationCommentId.GetFirstSymbolForReferenceId(id, compilation); - if (symbol != null) + if (symbol is not null) return symbol; } @@ -278,7 +278,7 @@ internal ISymbol GetFirstSymbolForReferenceId(string id) public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferredCultureName = null) { if (_symbolData.TryGetValue(symbol, out SymbolDocumentationData data) - && data.XmlDocumentation != null) + && data.XmlDocumentation is not null) { if (object.ReferenceEquals(data.XmlDocumentation, SymbolXmlDocumentation.Default)) return null; @@ -288,11 +288,11 @@ public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferr IAssemblySymbol assembly = FindAssembly(); - if (assembly != null) + if (assembly is not null) { SymbolXmlDocumentation xmlDocumentation = GetXmlDocumentation(assembly, preferredCultureName)?.GetXmlDocumentation(symbol); - if (xmlDocumentation != null) + if (xmlDocumentation is not null) { _symbolData[symbol] = data.WithXmlDocumentation(xmlDocumentation); return xmlDocumentation; @@ -300,7 +300,7 @@ public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferr CultureInfo preferredCulture = null; - if (preferredCultureName != null + if (preferredCultureName is not null && !_cultures.TryGetValue(preferredCultureName, out preferredCulture)) { preferredCulture = ImmutableInterlocked.GetOrAdd(ref _cultures, preferredCultureName, f => new CultureInfo(f)); @@ -350,7 +350,7 @@ public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferr { SymbolXmlDocumentation documentation = xmlDocumentation.GetXmlDocumentation(symbol, commentId); - if (documentation != null) + if (documentation is not null) { _symbolData[symbol] = data.WithXmlDocumentation(documentation); return documentation; @@ -365,7 +365,7 @@ IAssemblySymbol FindAssembly() { IAssemblySymbol containingAssembly = symbol.ContainingAssembly; - if (containingAssembly != null) + if (containingAssembly is not null) { AssemblyIdentity identity = containingAssembly.Identity; @@ -394,7 +394,7 @@ private XmlDocumentation GetXmlDocumentation(IAssemblySymbol assembly, string pr { string path = portableExecutableReference.FilePath; - if (preferredCultureName != null) + if (preferredCultureName is not null) { path = Path.GetDirectoryName(path); @@ -411,7 +411,7 @@ private XmlDocumentation GetXmlDocumentation(IAssemblySymbol assembly, string pr } } - if (xmlDocumentation == null) + if (xmlDocumentation is null) { path = Path.ChangeExtension(path, "xml"); @@ -432,7 +432,7 @@ private Compilation FindCompilation(IAssemblySymbol assembly) if (Compilations.Length == 1) return Compilations[0]; - if (_compilationMap == null) + if (_compilationMap is null) Interlocked.CompareExchange(ref _compilationMap, Compilations.ToImmutableDictionary(f => f.Assembly, f => f), null); return _compilationMap[assembly]; diff --git a/src/Documentation/DocumentationOptions.cs b/src/Documentation/DocumentationOptions.cs index 8f61b94392..b5f7588c07 100644 --- a/src/Documentation/DocumentationOptions.cs +++ b/src/Documentation/DocumentationOptions.cs @@ -167,7 +167,7 @@ internal bool ShouldBeIgnored(INamedTypeSymbol typeSymbol) { INamespaceSymbol n = typeSymbol.ContainingNamespace; - while (n != null) + while (n is not null) { if (n.HasMetadataName(metadataName)) return true; diff --git a/src/Documentation/DocumentationUtility.cs b/src/Documentation/DocumentationUtility.cs index 365cb45a9b..e6acdc9115 100644 --- a/src/Documentation/DocumentationUtility.cs +++ b/src/Documentation/DocumentationUtility.cs @@ -62,7 +62,7 @@ public static string GetSymbolLabel(ISymbol symbol, DocumentationContext context { string label = symbol.ToDisplayString(TypeSymbolDisplayFormats.Name_TypeParameters); - if (symbol.ContainingType != null) + if (symbol.ContainingType is not null) { label = symbol.ContainingType.ToDisplayString(TypeSymbolDisplayFormats.Name_TypeParameters) + "." @@ -90,7 +90,7 @@ public static string GetSymbolLabel(ISymbol symbol, DocumentationContext context ISymbol explicitImplementation = symbol.GetFirstExplicitInterfaceImplementation(); - if (explicitImplementation != null) + if (explicitImplementation is not null) { label = explicitImplementation.ContainingType.ToDisplayString(TypeSymbolDisplayFormats.Name_TypeParameters) + "." @@ -155,7 +155,7 @@ public static string CreateLocalLink(ISymbol symbol, string prefix = null) { StringBuilder sb = StringBuilderCache.GetInstance(); - if (prefix != null) + if (prefix is not null) sb.Append(prefix); int count = 0; @@ -189,7 +189,7 @@ public static string CreateLocalLink(ISymbol symbol, string prefix = null) INamedTypeSymbol t = symbol.ContainingType; - while (t != null) + while (t is not null) { t = t.ContainingType; count++; diff --git a/src/Documentation/DocumentationWriter.cs b/src/Documentation/DocumentationWriter.cs index 8598f2bacc..095a293dcd 100644 --- a/src/Documentation/DocumentationWriter.cs +++ b/src/Documentation/DocumentationWriter.cs @@ -525,7 +525,7 @@ public virtual void WriteDefinition(ISymbol symbol) ImmutableArray definitionParts = SymbolDefinitionDisplay.GetDisplayParts( symbol, - (symbol.GetFirstExplicitInterfaceImplementation() != null) + (symbol.GetFirstExplicitInterfaceImplementation() is not null) ? DocumentationDisplayFormats.ExplicitImplementationFullDeclaration : DocumentationDisplayFormats.FullDeclaration, typeDeclarationOptions: SymbolDisplayTypeDeclarationOptions.IncludeAccessibility @@ -676,7 +676,7 @@ public virtual void WriteReturnType(ISymbol symbol, SymbolXmlDocumentation xmlDo IMethodSymbol methodSymbol = namedTypeSymbol.DelegateInvokeMethod; - if (methodSymbol != null) + if (methodSymbol is not null) { ITypeSymbol returnType = methodSymbol.ReturnType; @@ -766,7 +766,7 @@ public virtual void WriteInheritance(INamedTypeSymbol typeSymbol) } } - if (typeSymbol.BaseType == null) + if (typeSymbol.BaseType is null) return; WriteHeading(3, Resources.InheritanceTitle); @@ -956,7 +956,7 @@ public virtual void WriteExceptions(ISymbol symbol, SymbolXmlDocumentation xmlDo { string commentId = element.Attribute("cref")?.Value; - if (commentId != null + if (commentId is not null && DocumentationModel.GetFirstSymbolForReferenceId(commentId) is INamedTypeSymbol exceptionSymbol) { yield return (element, exceptionSymbol); @@ -1043,7 +1043,7 @@ public virtual void WriteEnumFields(IEnumerable fields, INamedType SymbolXmlDocumentation xmlDocumentation = DocumentationModel.GetXmlDocumentation(fieldSymbol, Options.PreferredCultureName); - if (xmlDocumentation != null) + if (xmlDocumentation is not null) { WriteStartTableCell(); xmlDocumentation?.GetElement(WellKnownXmlTags.Summary)?.WriteContentTo(this, inlineOnly: true); @@ -1160,11 +1160,11 @@ IEnumerable GetSymbols() { string commentId = element.Attribute("cref")?.Value; - if (commentId != null) + if (commentId is not null) { ISymbol s = DocumentationModel.GetFirstSymbolForReferenceId(commentId); - if (s != null) + if (s is not null) yield return s; } } @@ -1207,10 +1207,10 @@ public virtual void WriteAppliesTo(ISymbol symbol, ImmutableArray containingFolders = (CurrentSymbol != null) + ImmutableArray containingFolders = (CurrentSymbol is not null) ? UrlSegmentProvider.GetSegments(CurrentSymbol) : default; string target = GetLocalLinkTarget(); - if (target == null + if (target is null && Options.ScrollToContent) { target = WellKnownNames.TopFragmentName; @@ -2012,7 +2012,7 @@ string GetLocalLinkTarget() IEnumerable members = GetMembers(typeModel); - if (members != null) + if (members is not null) { using (IEnumerator en = members.Where(f => f.Name == symbol.Name).GetEnumerator()) { diff --git a/src/Documentation/Extensions/SymbolExtensions.cs b/src/Documentation/Extensions/SymbolExtensions.cs index 0d32787630..12634e28f5 100644 --- a/src/Documentation/Extensions/SymbolExtensions.cs +++ b/src/Documentation/Extensions/SymbolExtensions.cs @@ -48,7 +48,7 @@ public static ImmutableArray GetMembers(this INamedTypeSymbol typeSymbo return GetMembersIncludingInherited(); } } - else if (predicate != null) + else if (predicate is not null) { return typeSymbol .GetMembers() @@ -68,7 +68,7 @@ ImmutableArray GetMembersIncludingInherited() { ISymbol overriddenSymbol = symbol.OverriddenSymbol(); - if (overriddenSymbol != null) + if (overriddenSymbol is not null) { (overriddenSymbols ??= new HashSet()).Add(overriddenSymbol); } @@ -78,7 +78,7 @@ ImmutableArray GetMembersIncludingInherited() INamedTypeSymbol baseType = typeSymbol.BaseType; - while (baseType != null) + while (baseType is not null) { bool areInternalsVisible = typeSymbol.ContainingAssembly.Identity.Equals(baseType.ContainingAssembly.Identity) || baseType.ContainingAssembly.GivesAccessTo(typeSymbol.ContainingAssembly); @@ -86,7 +86,7 @@ ImmutableArray GetMembersIncludingInherited() foreach (ISymbol symbol in baseType.GetMembers()) { if (!symbol.IsStatic - && (predicate == null || predicate(symbol)) + && (predicate is null || predicate(symbol)) && (symbol.DeclaredAccessibility != Accessibility.Internal || areInternalsVisible)) { if (overriddenSymbols?.Remove(symbol) != true) @@ -94,7 +94,7 @@ ImmutableArray GetMembersIncludingInherited() ISymbol overriddenSymbol = symbol.OverriddenSymbol(); - if (overriddenSymbol != null) + if (overriddenSymbol is not null) { (overriddenSymbols ??= new HashSet()).Add(overriddenSymbol); } @@ -285,7 +285,7 @@ internal static ImmutableArray GetAttributesIncludingInherited(th foreach (AttributeData attributeData in namedType.GetAttributes()) { - if (predicate == null + if (predicate is null || predicate(namedType, attributeData)) { (attributes ??= new HashSet(AttributeInfo.AttributeClassComparer)).Add(new AttributeInfo(namedType, attributeData)); @@ -294,14 +294,14 @@ internal static ImmutableArray GetAttributesIncludingInherited(th INamedTypeSymbol baseType = namedType.BaseType; - while (baseType != null + while (baseType is not null && baseType.SpecialType != SpecialType.System_Object) { foreach (AttributeData attributeData in baseType.GetAttributes()) { AttributeData attributeUsage = attributeData.AttributeClass.GetAttribute(MetadataNames.System_AttributeUsageAttribute); - if (attributeUsage != null) + if (attributeUsage is not null) { TypedConstant typedConstant = attributeUsage.NamedArguments.FirstOrDefault(f => f.Key == "Inherited").Value; @@ -313,7 +313,7 @@ internal static ImmutableArray GetAttributesIncludingInherited(th } } - if (predicate == null + if (predicate is null || predicate(baseType, attributeData)) { (attributes ??= new HashSet(AttributeInfo.AttributeClassComparer)).Add(new AttributeInfo(baseType, attributeData)); @@ -323,7 +323,7 @@ internal static ImmutableArray GetAttributesIncludingInherited(th baseType = baseType.BaseType; } - return (attributes != null) + return (attributes is not null) ? attributes.ToImmutableArray() : ImmutableArray.Empty; } diff --git a/src/Documentation/Extensions/XmlExtensions.cs b/src/Documentation/Extensions/XmlExtensions.cs index 7306b678fc..d62bbe138b 100644 --- a/src/Documentation/Extensions/XmlExtensions.cs +++ b/src/Documentation/Extensions/XmlExtensions.cs @@ -109,7 +109,7 @@ public static void WriteContentTo(this XElement element, DocumentationWriter wri { string parameterName = e.Attribute("name")?.Value; - if (parameterName != null) + if (parameterName is not null) writer.WriteBold(parameterName); break; @@ -118,13 +118,13 @@ public static void WriteContentTo(this XElement element, DocumentationWriter wri { string commentId = e.Attribute("cref")?.Value; - if (commentId != null) + if (commentId is not null) { ISymbol symbol = writer.DocumentationModel.GetFirstSymbolForDeclarationId(commentId); //XTODO: repair roslyn documentation Debug.Assert( - symbol != null + symbol is not null || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxNode" || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxToken" || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxTrivia" @@ -133,7 +133,7 @@ public static void WriteContentTo(this XElement element, DocumentationWriter wri || commentId == "T:Microsoft.CodeAnalysis.VisualBasic.SyntaxTrivia", commentId); - if (symbol != null) + if (symbol is not null) { writer.WriteLink(symbol, TypeSymbolDisplayFormats.Name_ContainingTypes_TypeParameters, SymbolDisplayAdditionalMemberOptions.UseItemPropertyName | SymbolDisplayAdditionalMemberOptions.UseOperatorName); } @@ -149,7 +149,7 @@ public static void WriteContentTo(this XElement element, DocumentationWriter wri { string typeParameterName = e.Attribute("name")?.Value; - if (typeParameterName != null) + if (typeParameterName is not null) writer.WriteBold(typeParameterName); break; diff --git a/src/Documentation/InheritDocUtility.cs b/src/Documentation/InheritDocUtility.cs index 86c811bf15..ec4929a887 100644 --- a/src/Documentation/InheritDocUtility.cs +++ b/src/Documentation/InheritDocUtility.cs @@ -88,7 +88,7 @@ private static XElement FindInheritedDocumentationFromImplementedInterfaceMember { INamedTypeSymbol containingType = symbol.ContainingType; - if (containingType != null) + if (containingType is not null) { foreach (INamedTypeSymbol interfaceSymbol in containingType.Interfaces) { diff --git a/src/Documentation/Markdown/DocusaurusDocumentationWriter.cs b/src/Documentation/Markdown/DocusaurusDocumentationWriter.cs index bf73a236be..82dba6d807 100644 --- a/src/Documentation/Markdown/DocusaurusDocumentationWriter.cs +++ b/src/Documentation/Markdown/DocusaurusDocumentationWriter.cs @@ -19,7 +19,7 @@ public override void WriteStartDocument(ISymbol symbol, DocumentationFileKind fi { string label = null; - if (symbol != null) + if (symbol is not null) label = DocumentationUtility.GetSymbolLabel(symbol, Context); if (fileKind == DocumentationFileKind.Root) @@ -34,7 +34,7 @@ public override void WriteStartDocument(ISymbol symbol, DocumentationFileKind fi WriteLine(); } - if (label != null) + if (label is not null) { WriteRaw("sidebar_label: "); WriteRaw(label); diff --git a/src/Documentation/Markdown/SymbolDefinitionMarkdownWriter.cs b/src/Documentation/Markdown/SymbolDefinitionMarkdownWriter.cs index bb18bc611f..e160d25dfb 100644 --- a/src/Documentation/Markdown/SymbolDefinitionMarkdownWriter.cs +++ b/src/Documentation/Markdown/SymbolDefinitionMarkdownWriter.cs @@ -91,7 +91,7 @@ protected override void WriteAttributeName(ISymbol symbol) public override void WriteTypeDefinition(INamedTypeSymbol typeSymbol, SymbolDisplayFormat format = null) { - if (typeSymbol != null) + if (typeSymbol is not null) { WriteDocumentationComment(typeSymbol); WriteDefinition(typeSymbol, format); @@ -109,7 +109,7 @@ protected override void WriteDefinitionName(ISymbol symbol, SymbolDisplayFormat { DocumentationUrlInfo urlInfo = _urlProvider.GetExternalUrl(symbol); - if (urlInfo.Url != null) + if (urlInfo.Url is not null) { WriteContainingNamespaceInTypeHierarchy(symbol); @@ -167,7 +167,7 @@ protected override void WriteSymbol(ISymbol symbol, SymbolDisplayFormat format = private void WriteName(ISymbol symbol, string text) { - if (TypeSymbols != null + if (TypeSymbols is not null && symbol is INamedTypeSymbol typeSymbol && TypeSymbols.Contains(typeSymbol)) { @@ -180,7 +180,7 @@ private void WriteName(ISymbol symbol, string text) { string url = _urlProvider.GetExternalUrl(symbol).Url; - if (url != null) + if (url is not null) { _writer.WriteLink( text, @@ -344,7 +344,7 @@ public override void WriteDocumentationComment(ISymbol symbol) public override void Close() { - if (_writer != null) + if (_writer is not null) { try { diff --git a/src/Documentation/MemberSymbolEqualityComparer.cs b/src/Documentation/MemberSymbolEqualityComparer.cs index 88fe3e80cf..a0133af0ac 100644 --- a/src/Documentation/MemberSymbolEqualityComparer.cs +++ b/src/Documentation/MemberSymbolEqualityComparer.cs @@ -16,10 +16,10 @@ public override bool Equals(ISymbol x, ISymbol y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (!string.Equals(x.Name, y.Name, StringComparison.Ordinal)) @@ -165,10 +165,10 @@ public override bool Equals(IParameterSymbol x, IParameterSymbol y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return x.RefKind == y.RefKind @@ -177,7 +177,7 @@ public override bool Equals(IParameterSymbol x, IParameterSymbol y) public override int GetHashCode(IParameterSymbol obj) { - if (obj == null) + if (obj is null) return 0; return Hash.Combine(obj.Type, (int)obj.RefKind); diff --git a/src/Documentation/SourceReferenceProvider.cs b/src/Documentation/SourceReferenceProvider.cs index 4a9869e44b..327273d22b 100644 --- a/src/Documentation/SourceReferenceProvider.cs +++ b/src/Documentation/SourceReferenceProvider.cs @@ -82,7 +82,7 @@ private static void Load(string uri, ref ImmutableDictionary interfaces = ImmutableArray.Empty; - if (typeSymbol != null + if (typeSymbol is not null && (typeDeclarationOptions & SymbolDisplayTypeDeclarationOptions.BaseList) != 0) { if ((typeDeclarationOptions & SymbolDisplayTypeDeclarationOptions.BaseType) != 0 @@ -67,7 +67,7 @@ internal static class SymbolDefinitionDisplay int baseListCount = interfaces.Length; - if (baseType != null) + if (baseType is not null) baseListCount++; int constraintCount = 0; @@ -101,7 +101,7 @@ internal static class SymbolDefinitionDisplay builder.AddPunctuation(":"); builder.AddSpace(); - if (baseType != null) + if (baseType is not null) { builder.AddDisplayParts(baseType, format, additionalOptions); @@ -187,7 +187,7 @@ internal static class SymbolDefinitionDisplay } } - if (builder == null + if (builder is null && attributes.Any()) { builder = ImmutableArray.CreateBuilder(parts.Length); @@ -206,7 +206,7 @@ internal static class SymbolDefinitionDisplay var propertySymbol = (IPropertySymbol)symbol; IMethodSymbol getMethod = propertySymbol.GetMethod; - if (getMethod != null) + if (getMethod is not null) { builder ??= parts.ToBuilder(); @@ -214,7 +214,7 @@ internal static class SymbolDefinitionDisplay } IMethodSymbol setMethod = propertySymbol.SetMethod; - if (setMethod != null) + if (setMethod is not null) { builder ??= parts.ToBuilder(); @@ -260,7 +260,7 @@ internal static class SymbolDefinitionDisplay if (ShouldAddTrailingSemicolon()) { - if (builder == null) + if (builder is null) { parts = parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ";")); } @@ -274,7 +274,7 @@ internal static class SymbolDefinitionDisplay void InitializeBuilder() { - if (builder == null) + if (builder is null) { builder = ImmutableArray.CreateBuilder(parts.Length); @@ -531,7 +531,7 @@ void AddConstantValue(TypedConstant typedConstant) } case TypedConstantKind.Type: { - if (typedConstant.Value == null) + if (typedConstant.Value is null) { parts.AddKeyword("null"); } @@ -1160,12 +1160,12 @@ private static bool HasOption(this SymbolDisplayAdditionalOptions options, Symbo private static IEnumerable GetAttributes(ISymbol symbol, Func predicate) { - if (symbol == null) + if (symbol is null) return ImmutableArray.Empty; ImmutableArray attributes = symbol.GetAttributes(); - if (predicate != null) + if (predicate is not null) return attributes.Where(f => predicate(symbol, f)); return attributes; diff --git a/src/Documentation/SymbolDefinitionTextWriter.cs b/src/Documentation/SymbolDefinitionTextWriter.cs index 35b3fe0a0b..b8c0208555 100644 --- a/src/Documentation/SymbolDefinitionTextWriter.cs +++ b/src/Documentation/SymbolDefinitionTextWriter.cs @@ -104,7 +104,7 @@ public override void WriteDocumentationComment(ISymbol symbol) { IEnumerable elements = DocumentationProvider?.GetXmlDocumentation(symbol)?.GetElementsAsText(skipEmptyElement: true, makeSingleLine: true); - if (elements == null) + if (elements is null) return; foreach (string element in elements) @@ -116,7 +116,7 @@ void WriteDocumentation(string element) { string line = null; - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) { WriteLine(line); WriteIndentation(); @@ -127,7 +127,7 @@ void WriteDocumentation(string element) public override void Close() { - if (_writer != null) + if (_writer is not null) { try { diff --git a/src/Documentation/SymbolDefinitionWriter.cs b/src/Documentation/SymbolDefinitionWriter.cs index d1b3ebe5f9..ca308cc07b 100644 --- a/src/Documentation/SymbolDefinitionWriter.cs +++ b/src/Documentation/SymbolDefinitionWriter.cs @@ -68,7 +68,7 @@ public SymbolDisplayFormat DefinitionFormat { get { - if (_definitionFormat == null) + if (_definitionFormat is null) { var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, @@ -340,7 +340,7 @@ private void WriteNamespaces(in OneOrMany assemblies, Cancellat else { typesByNamespace = assemblies - .SelectMany(a => a.GetTypes(t => t.ContainingType == null && Filter.IsMatch(t))) + .SelectMany(a => a.GetTypes(t => t.ContainingType is null && Filter.IsMatch(t))) .GroupBy(t => t.ContainingNamespace, MetadataNameEqualityComparer.Instance) .Where(g => Filter.IsMatch(g.Key)) .OrderBy(g => g.Key, Comparer.NamespaceComparer) @@ -774,7 +774,7 @@ public virtual void WriteAttribute(AttributeData attribute) { INamedTypeSymbol attributeSymbol = attribute.AttributeClass; - if (attributeSymbol.ContainingType != null + if (attributeSymbol.ContainingType is not null || (Format.Includes(SymbolDefinitionPartFilter.ContainingNamespace) && !attributeSymbol.ContainingNamespace.IsGlobalNamespace)) { @@ -909,7 +909,7 @@ void AddConstantValue(TypedConstant typedConstant) } case TypedConstantKind.Type: { - if (typedConstant.Value == null) + if (typedConstant.Value is null) { Write("null"); } @@ -995,11 +995,11 @@ public virtual void WriteDefinition(ISymbol symbol, ImmutableArray parameters) bool IsMatch(ISymbol s) { - if (s != null) + if (s is not null) { foreach (AttributeData attribute in s.GetAttributes()) { @@ -161,7 +161,7 @@ public static ImmutableArray GetParameters(INamedTypeSymbol ty { IMethodSymbol delegateInvokeMethod = typeSymbol.DelegateInvokeMethod; - if (delegateInvokeMethod != null) + if (delegateInvokeMethod is not null) return delegateInvokeMethod.Parameters; } diff --git a/src/Documentation/SymbolDocumentationProvider.cs b/src/Documentation/SymbolDocumentationProvider.cs index 8801afafb6..5945af9f7d 100644 --- a/src/Documentation/SymbolDocumentationProvider.cs +++ b/src/Documentation/SymbolDocumentationProvider.cs @@ -35,7 +35,7 @@ public sealed class SymbolDocumentationProvider _symbolData = new Dictionary(); _xmlDocumentations = new Dictionary(); - if (additionalXmlDocumentationPaths != null) + if (additionalXmlDocumentationPaths is not null) _additionalXmlDocumentationPaths = additionalXmlDocumentationPaths.ToImmutableArray(); } @@ -52,7 +52,7 @@ internal ISymbol GetFirstSymbolForDeclarationId(string id) { ISymbol symbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(id, compilation); - if (symbol != null) + if (symbol is not null) return symbol; } @@ -68,7 +68,7 @@ internal ISymbol GetFirstSymbolForReferenceId(string id) { ISymbol symbol = DocumentationCommentId.GetFirstSymbolForReferenceId(id, compilation); - if (symbol != null) + if (symbol is not null) return symbol; } @@ -78,7 +78,7 @@ internal ISymbol GetFirstSymbolForReferenceId(string id) public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferredCultureName = null) { if (_symbolData.TryGetValue(symbol, out SymbolDocumentationData data) - && data.XmlDocumentation != null) + && data.XmlDocumentation is not null) { if (object.ReferenceEquals(data.XmlDocumentation, SymbolXmlDocumentation.Default)) return null; @@ -88,11 +88,11 @@ public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferr IAssemblySymbol assembly = symbol.ContainingAssembly; - if (assembly != null) + if (assembly is not null) { SymbolXmlDocumentation xmlDocumentation = GetXmlDocumentation(assembly, preferredCultureName)?.GetXmlDocumentation(symbol); - if (xmlDocumentation != null) + if (xmlDocumentation is not null) { _symbolData[symbol] = data.WithXmlDocumentation(xmlDocumentation); return xmlDocumentation; @@ -100,7 +100,7 @@ public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferr CultureInfo preferredCulture = null; - if (preferredCultureName != null + if (preferredCultureName is not null && !_cultures.TryGetValue(preferredCultureName, out preferredCulture)) { preferredCulture = ImmutableInterlocked.GetOrAdd(ref _cultures, preferredCultureName, f => new CultureInfo(f)); @@ -139,7 +139,7 @@ public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string preferr { SymbolXmlDocumentation documentation = xmlDocumentation.GetXmlDocumentation(symbol, commentId); - if (documentation != null) + if (documentation is not null) { _symbolData[symbol] = data.WithXmlDocumentation(documentation); return documentation; @@ -161,7 +161,7 @@ private XmlDocumentation GetXmlDocumentation(IAssemblySymbol assembly, string pr { string path = portableExecutableReference.FilePath; - if (preferredCultureName != null) + if (preferredCultureName is not null) { path = Path.GetDirectoryName(path); @@ -178,7 +178,7 @@ private XmlDocumentation GetXmlDocumentation(IAssemblySymbol assembly, string pr } } - if (xmlDocumentation == null) + if (xmlDocumentation is null) { path = Path.ChangeExtension(path, "xml"); @@ -195,7 +195,7 @@ private XmlDocumentation GetXmlDocumentation(IAssemblySymbol assembly, string pr private MetadataReference FindMetadataReference(IAssemblySymbol assembly) { - if (_assemblyToReferenceMap == null) + if (_assemblyToReferenceMap is null) Interlocked.CompareExchange(ref _assemblyToReferenceMap, Compilations.ToImmutableDictionary(f => f.Assembly, f => f.GetMetadataReference(f.Assembly)), null); if (_assemblyToReferenceMap.TryGetValue(assembly, out MetadataReference metadataReference)) diff --git a/src/Documentation/SymbolXmlDocumentation.cs b/src/Documentation/SymbolXmlDocumentation.cs index b682ae6a0d..5f41fe0c04 100644 --- a/src/Documentation/SymbolXmlDocumentation.cs +++ b/src/Documentation/SymbolXmlDocumentation.cs @@ -75,7 +75,7 @@ public IEnumerable GetElements(string name) public bool HasElement(string name) { - return GetElement(name) != null; + return GetElement(name) is not null; } public IEnumerable GetElementsAsText(bool skipEmptyElement = false, bool makeSingleLine = false) diff --git a/src/Documentation/TypeHierarchy.cs b/src/Documentation/TypeHierarchy.cs index 99c4782311..0820960275 100644 --- a/src/Documentation/TypeHierarchy.cs +++ b/src/Documentation/TypeHierarchy.cs @@ -30,7 +30,7 @@ public TypeHierarchyItem InterfaceRoot { get { - if (_interfaceRoot == null) + if (_interfaceRoot is null) Interlocked.CompareExchange(ref _interfaceRoot, LoadInterfaceHierarchy(), null); return _interfaceRoot; @@ -41,7 +41,7 @@ internal TypeHierarchyItem EnumRoot { get { - if (_enumRoot == null) + if (_enumRoot is null) Interlocked.CompareExchange(ref _enumRoot, GetEnumRoot(), null); return _enumRoot; @@ -65,7 +65,7 @@ internal TypeHierarchyItem ValueTypeRoot { get { - if (_valueTypeRoot == null) + if (_valueTypeRoot is null) Interlocked.CompareExchange(ref _valueTypeRoot, GetValueTypeRoot(), null); return _valueTypeRoot; @@ -159,7 +159,7 @@ TypeHierarchyItem FillHierarchyItem(TypeHierarchyItem item, TypeHierarchyItem pa { Func predicate = null; - if (filter != null) + if (filter is not null) predicate = t => filter.IsMatch(t); IEnumerable types = assemblies.SelectMany(a => a.GetTypes(predicate)); @@ -169,14 +169,14 @@ TypeHierarchyItem FillHierarchyItem(TypeHierarchyItem item, TypeHierarchyItem pa public static TypeHierarchy Create(IEnumerable types, INamedTypeSymbol root = null, IComparer comparer = null) { - if (comparer == null) + if (comparer is null) comparer = SymbolDefinitionComparer.SystemFirst.TypeComparer; - if (root == null) + if (root is null) { root = FindObjectType(); - if (root == null) + if (root is null) throw new InvalidOperationException("Object type not found."); } @@ -189,7 +189,7 @@ public static TypeHierarchy Create(IEnumerable types, INamedTy { INamedTypeSymbol t = type.BaseType; - while (t != null) + while (t is not null) { if (!allItems.ContainsKey(t.OriginalDefinition)) allItems[t.OriginalDefinition] = new TypeHierarchyItem(t.OriginalDefinition, isExternal: true); @@ -272,7 +272,7 @@ INamedTypeSymbol FindObjectType() t = t.BaseType; } - while (t != null); + while (t is not null); } return null; diff --git a/src/Documentation/TypeHierarchyItem.cs b/src/Documentation/TypeHierarchyItem.cs index aa870db975..6c316ee1cc 100644 --- a/src/Documentation/TypeHierarchyItem.cs +++ b/src/Documentation/TypeHierarchyItem.cs @@ -32,7 +32,7 @@ public int Depth TypeHierarchyItem parent = Parent; - while (parent != null) + while (parent is not null) { depth++; parent = parent.Parent; @@ -48,13 +48,13 @@ private string DebuggerDisplay get { return $"Depth = {Depth} {Symbol.ToDisplayString(Roslynator.SymbolDisplayFormats.Test)}"; } } - public bool HasChildren => content != null; + public bool HasChildren => content is not null; public IEnumerable Children() { TypeHierarchyItem e = content; - if (e != null) + if (e is not null) { do { @@ -79,7 +79,7 @@ internal IEnumerable GetAncestors(bool self) { TypeHierarchyItem c = ((self) ? this : Parent); - while (c != null) + while (c is not null) { yield return c; @@ -110,7 +110,7 @@ internal IEnumerable GetDescendants(bool self) { TypeHierarchyItem first = c?.content?.next; - if (first != null) + if (first is not null) { e = first; } @@ -128,7 +128,7 @@ internal IEnumerable GetDescendants(bool self) e = e.next; } - if (e != null) + if (e is not null) yield return e; c = e; diff --git a/src/Documentation/TypeKindComparer.cs b/src/Documentation/TypeKindComparer.cs index 381672d71b..355df08da4 100644 --- a/src/Documentation/TypeKindComparer.cs +++ b/src/Documentation/TypeKindComparer.cs @@ -17,10 +17,10 @@ public int Compare(object x, object y) if (x == y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is TypeKind a @@ -37,10 +37,10 @@ public int Compare(object x, object y) if (x == y) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x is TypeKind a @@ -54,7 +54,7 @@ public int Compare(object x, object y) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) return 0; if (obj is TypeKind symbol) diff --git a/src/Documentation/UrlProviders/CommonDocumentationUrlProvider.cs b/src/Documentation/UrlProviders/CommonDocumentationUrlProvider.cs index 9dd336e4eb..3e57448b99 100644 --- a/src/Documentation/UrlProviders/CommonDocumentationUrlProvider.cs +++ b/src/Documentation/UrlProviders/CommonDocumentationUrlProvider.cs @@ -20,7 +20,7 @@ private string LinkToSelf { get { - if (_linkToSelf == null) + if (_linkToSelf is null) _linkToSelf = "./" + IndexFileName; return _linkToSelf; @@ -137,7 +137,7 @@ static bool FoldersEqual(ImmutableArray folders1, ImmutableArray public override string GetFragment(string value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); value = _notWordCharOrHyphenOrSpaceRegex.Replace(value, ""); diff --git a/src/Documentation/UrlProviders/DefaultUrlSegmentProvider.cs b/src/Documentation/UrlProviders/DefaultUrlSegmentProvider.cs index 9aaa0de293..92adb69fa3 100644 --- a/src/Documentation/UrlProviders/DefaultUrlSegmentProvider.cs +++ b/src/Documentation/UrlProviders/DefaultUrlSegmentProvider.cs @@ -61,7 +61,7 @@ public override ImmutableArray GetSegments(ISymbol symbol) { ISymbol explicitImplementation = symbol.GetFirstExplicitInterfaceImplementation(); - if (explicitImplementation != null) + if (explicitImplementation is not null) { string name = explicitImplementation .ToDisplayParts(DocumentationDisplayFormats.ExplicitImplementationFullName, SymbolDisplayAdditionalMemberOptions.UseItemPropertyName) @@ -97,7 +97,7 @@ public override ImmutableArray GetSegments(ISymbol symbol) INamedTypeSymbol containingType = symbol.ContainingType; - while (containingType != null) + while (containingType is not null) { int arity = containingType.Arity; @@ -108,9 +108,9 @@ public override ImmutableArray GetSegments(ISymbol symbol) namespaceSymbol = (symbol as INamespaceSymbol) ?? symbol.ContainingNamespace; - Debug.Assert(namespaceSymbol != null, symbol.ToDisplayString(SymbolDisplayFormats.Test)); + Debug.Assert(namespaceSymbol is not null, symbol.ToDisplayString(SymbolDisplayFormats.Test)); - if (namespaceSymbol != null) + if (namespaceSymbol is not null) { if (namespaceSymbol.IsGlobalNamespace) { diff --git a/src/Documentation/UrlProviders/DocumentationUrlProvider.cs b/src/Documentation/UrlProviders/DocumentationUrlProvider.cs index 5180c00d52..1f6c6f9204 100644 --- a/src/Documentation/UrlProviders/DocumentationUrlProvider.cs +++ b/src/Documentation/UrlProviders/DocumentationUrlProvider.cs @@ -19,7 +19,7 @@ protected DocumentationUrlProvider(UrlSegmentProvider segmentProvider, IEnumerab { SegmentProvider = segmentProvider; - ExternalProviders = (externalProviders != null) + ExternalProviders = (externalProviders is not null) ? ImmutableArray.CreateRange(externalProviders) : ImmutableArray.Empty; } @@ -44,7 +44,7 @@ public DocumentationUrlInfo GetExternalUrl(ISymbol symbol) { DocumentationUrlInfo urlInfo = provider.CreateUrl(symbol); - if (urlInfo.Url != null) + if (urlInfo.Url is not null) return urlInfo; } diff --git a/src/Documentation/Xml/SymbolDefinitionXmlWriter.cs b/src/Documentation/Xml/SymbolDefinitionXmlWriter.cs index 0138e3d6ae..7a96098963 100644 --- a/src/Documentation/Xml/SymbolDefinitionXmlWriter.cs +++ b/src/Documentation/Xml/SymbolDefinitionXmlWriter.cs @@ -140,7 +140,7 @@ public override void WriteStartType(INamedTypeSymbol typeSymbol) public override void WriteTypeDefinition(INamedTypeSymbol typeSymbol, SymbolDisplayFormat format = null) { - if (typeSymbol != null) + if (typeSymbol is not null) { WriteStartAttribute("def"); WriteDefinition(typeSymbol, format); @@ -385,7 +385,7 @@ public override void WriteDocumentationComment(ISymbol symbol) { IEnumerable elements = DocumentationProvider?.GetXmlDocumentation(symbol)?.GetElementsAsText(skipEmptyElement: true, makeSingleLine: true); - if (elements == null) + if (elements is null) return; using (IEnumerator en = elements.GetEnumerator()) @@ -413,7 +413,7 @@ void WriteDocumentation(string element) using (var sr = new StringReader(element)) { string line = null; - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) { _writer.WriteWhitespace(_writer.Settings.NewLineChars); @@ -428,7 +428,7 @@ void WriteDocumentation(string element) public override void Close() { - if (_writer != null) + if (_writer is not null) { try { diff --git a/src/Documentation/XmlDocumentation.cs b/src/Documentation/XmlDocumentation.cs index 54006c1770..44a5fc4dd3 100644 --- a/src/Documentation/XmlDocumentation.cs +++ b/src/Documentation/XmlDocumentation.cs @@ -95,7 +95,7 @@ public SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol) internal SymbolXmlDocumentation GetXmlDocumentation(ISymbol symbol, string commentId) { - if (_elementsById == null) + if (_elementsById is null) { Interlocked.CompareExchange(ref _elementsById, LoadElements(), null); } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/CodeFixHelpers.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/CodeFixHelpers.cs index 5b30b42e55..837dbc7c33 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/CodeFixHelpers.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/CodeFixHelpers.cs @@ -1061,7 +1061,7 @@ void SetIndentation2(SyntaxNodeOrToken nodeOrToken, int endIndex) { LambdaBlock lambdaBlock = GetLambdaBlock(argument, lines ??= argument.SyntaxTree.GetText().Lines); - if (lambdaBlock.Block != null) + if (lambdaBlock.Block is not null) increasedIndentation = indentationAnalysis.Indentation.ToString(); } @@ -1099,7 +1099,7 @@ void SetIndentation2(SyntaxNodeOrToken nodeOrToken, int endIndex) if (indentationAdded && node is ArgumentSyntax argument - && (argument.Expression as AnonymousFunctionExpressionSyntax)?.Block != null) + && (argument.Expression as AnonymousFunctionExpressionSyntax)?.Block is not null) { indentationAdded = false; } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/LineIsTooLongCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/LineIsTooLongCodeFixProvider.cs index 2f99de955c..a355824a4e 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/LineIsTooLongCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/LineIsTooLongCodeFixProvider.cs @@ -48,7 +48,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) SyntaxNode nodeToFix = wrapLineNodeFinder.FindNodeToFix(root); - if (nodeToFix == null) + if (nodeToFix is null) return; CodeAction codeAction = CodeAction.Create( diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs index 3546e01db3..99d1b80a62 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs @@ -54,7 +54,7 @@ public SyntaxNode FindNodeToFix(SyntaxNode root) { SyntaxNode fixableNode = GetFixableNode(node); - if (fixableNode != null) + if (fixableNode is not null) (_nodes ??= new Dictionary())[syntaxGroup] = node; } @@ -65,7 +65,7 @@ public SyntaxNode FindNodeToFix(SyntaxNode root) position = Math.Min(position, token.FullSpan.Start) - 1; } - if (_nodes == null) + if (_nodes is null) return null; if (TryGetNode(SyntaxGroup.ArgumentList, out SyntaxNode argumentList) @@ -373,7 +373,7 @@ private SyntaxNode GetFixableNode(SyntaxNode node) } int end; - if (parentBinaryExpression != null) + if (parentBinaryExpression is not null) { end = (addNewLineAfter) ? parentBinaryExpression.OperatorToken.Span.End @@ -390,7 +390,7 @@ private SyntaxNode GetFixableNode(SyntaxNode node) longestLength = Math.Max(longestLength, end - start); - if (parentBinaryExpression == null) + if (parentBinaryExpression is null) break; binaryExpression = parentBinaryExpression; @@ -484,7 +484,7 @@ private static bool TryGetSyntaxGroup(SyntaxNode node, out SyntaxGroup syntaxGro private bool TryGetNode(SyntaxGroup syntaxGroup, out SyntaxNode node) { - if (_nodes != null) + if (_nodes is not null) { return _nodes.TryGetValue(syntaxGroup, out node); } @@ -513,7 +513,7 @@ private bool ShouldAnalyze(SyntaxNode node, SyntaxGroup syntaxGroup) } } - if (_nodes == null) + if (_nodes is null) return true; foreach (KeyValuePair kvp in _nodes) @@ -544,7 +544,7 @@ private bool ShouldAnalyze(SyntaxNode node, SyntaxGroup syntaxGroup) static bool IsInsideInterpolation(SyntaxNode node) { - for (SyntaxNode n = node; n != null; n = n.Parent) + for (SyntaxNode n = node; n is not null; n = n.Parent) { switch (n) { @@ -602,7 +602,7 @@ private bool CanWrap(MemberAccessExpressionSyntax memberAccessExpression) { ISymbol symbol = SemanticModel.GetSymbol(memberAccessExpression); - if (symbol != null) + if (symbol is not null) { if (symbol.IsKind(SymbolKind.Namespace)) return false; @@ -699,10 +699,10 @@ public int Compare(SyntaxNode x, SyntaxNode y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; return GetSyntaxGroup(x).CompareTo(GetSyntaxGroup(y)); diff --git a/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs index d71fa8e667..496645ec5f 100644 --- a/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs @@ -45,7 +45,7 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) SyntaxList accessors = accessorList.Accessors; - if (accessors.Any(f => f.BodyOrExpressionBody() != null)) + if (accessors.Any(f => f.BodyOrExpressionBody() is not null)) { if (DiagnosticRules.PutFullAccessorOnItsOwnLine.IsEffective(context)) { @@ -53,7 +53,7 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) foreach (AccessorDeclarationSyntax accessor in accessors) { - if (accessor.BodyOrExpressionBody() != null + if (accessor.BodyOrExpressionBody() is not null && accessor.SyntaxTree.IsSingleLineSpan(TextSpan.FromBounds(token.Span.End, accessor.SpanStart))) { DiagnosticHelpers.ReportDiagnostic( @@ -114,7 +114,7 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) BracketedParameterListSyntax parameterList = indexerDeclaration.ParameterList; - if (parameterList != null) + if (parameterList is not null) { SyntaxToken closeBracket = parameterList.CloseBracketToken; diff --git a/src/Formatting.Analyzers/CSharp/AddBlankLineAfterEmbeddedStatementAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddBlankLineAfterEmbeddedStatementAnalyzer.cs index 057fe56781..4c73ab91f6 100644 --- a/src/Formatting.Analyzers/CSharp/AddBlankLineAfterEmbeddedStatementAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddBlankLineAfterEmbeddedStatementAnalyzer.cs @@ -47,7 +47,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) { var ifStatement = (IfStatementSyntax)context.Node; - if (ifStatement.Else != null) + if (ifStatement.Else is not null) return; Analyze(context, ifStatement.GetTopmostIf(), ifStatement.CloseParenToken, ifStatement.Statement); @@ -107,7 +107,7 @@ private static void AnalyzeElseClause(SyntaxNodeAnalysisContext context) { IfStatementSyntax topmostIf = elseClause.GetTopmostIf(); - if (topmostIf != null) + if (topmostIf is not null) Analyze(context, topmostIf, elseKeyword, statement); } } @@ -136,7 +136,7 @@ private static void AnalyzeElseClause(SyntaxNodeAnalysisContext context) StatementSyntax nextStatement = containingStatement.NextStatement(); - if (nextStatement == null) + if (nextStatement is null) return; if (syntaxTree.GetLineCount(TextSpan.FromBounds(statement.Span.End, nextStatement.SpanStart)) > 2) diff --git a/src/Formatting.Analyzers/CSharp/AddBlankLineAfterTopCommentAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddBlankLineAfterTopCommentAnalyzer.cs index ced2184905..ee388079e9 100644 --- a/src/Formatting.Analyzers/CSharp/AddBlankLineAfterTopCommentAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddBlankLineAfterTopCommentAnalyzer.cs @@ -42,7 +42,7 @@ private static void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) ?? (SyntaxNode)compilationUnit.AttributeLists.FirstOrDefault() ?? compilationUnit.Members.FirstOrDefault(); - if (node == null) + if (node is null) return; SyntaxTriviaList.Enumerator en = node.GetLeadingTrivia().GetEnumerator(); diff --git a/src/Formatting.Analyzers/CSharp/AddBlankLineAfterUsingDirectiveListAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddBlankLineAfterUsingDirectiveListAnalyzer.cs index 2db1ae111b..8c23743b08 100644 --- a/src/Formatting.Analyzers/CSharp/AddBlankLineAfterUsingDirectiveListAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddBlankLineAfterUsingDirectiveListAnalyzer.cs @@ -40,7 +40,7 @@ private static void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) UsingDirectiveSyntax usingDirective = compilationUnit.Usings.LastOrDefault(); - if (usingDirective == null) + if (usingDirective is null) return; SyntaxToken nextToken = compilationUnit.AttributeLists.FirstOrDefault()?.OpenBracketToken @@ -59,7 +59,7 @@ private static void AnalyzeNamespaceDeclaration(SyntaxNodeAnalysisContext contex UsingDirectiveSyntax usingDirective = namespaceDeclaration.Usings.LastOrDefault(); - if (usingDirective == null) + if (usingDirective is null) return; SyntaxToken nextToken = namespaceDeclaration.Members.FirstOrDefault()?.GetFirstToken() ?? default; diff --git a/src/Formatting.Analyzers/CSharp/AddBlankLineBeforeTopDeclarationAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddBlankLineBeforeTopDeclarationAnalyzer.cs index a5b52c4d52..ab90aa681e 100644 --- a/src/Formatting.Analyzers/CSharp/AddBlankLineBeforeTopDeclarationAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddBlankLineBeforeTopDeclarationAnalyzer.cs @@ -39,7 +39,7 @@ private static void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) MemberDeclarationSyntax declaration = compilationUnit.Members.FirstOrDefault(); - if (declaration == null) + if (declaration is null) return; if (!SyntaxTriviaAnalysis.IsEmptyOrSingleWhitespaceTrivia(declaration.GetLeadingTrivia())) @@ -49,7 +49,7 @@ private static void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) ?? (SyntaxNode)compilationUnit.Usings.LastOrDefault() ?? compilationUnit.Externs.LastOrDefault(); - if (node == null) + if (node is null) return; if (!SyntaxTriviaAnalysis.IsOptionalWhitespaceThenOptionalSingleLineCommentThenEndOfLineTrivia(node.GetTrailingTrivia())) diff --git a/src/Formatting.Analyzers/CSharp/AddBlankLineBeforeUsingDirectiveListAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddBlankLineBeforeUsingDirectiveListAnalyzer.cs index b6959d622f..4c1b333d7f 100644 --- a/src/Formatting.Analyzers/CSharp/AddBlankLineBeforeUsingDirectiveListAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddBlankLineBeforeUsingDirectiveListAnalyzer.cs @@ -39,7 +39,7 @@ private static void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) UsingDirectiveSyntax usingDirective = compilationUnit.Usings.FirstOrDefault(); - if (usingDirective == null) + if (usingDirective is null) return; SyntaxTriviaList.Reversed.Enumerator en = usingDirective.GetLeadingTrivia().Reverse().GetEnumerator(); diff --git a/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenClosingBraceAndNextStatementAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenClosingBraceAndNextStatementAnalyzer.cs index f16701d7f8..8d123bc255 100644 --- a/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenClosingBraceAndNextStatementAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenClosingBraceAndNextStatementAnalyzer.cs @@ -67,7 +67,7 @@ private static void AnalyzeBlock(SyntaxNodeAnalysisContext context) { var ifStatement = (IfStatementSyntax)block.Parent; - if (ifStatement.Else == null) + if (ifStatement.Else is null) { blockOrStatement = ifStatement; break; @@ -99,7 +99,7 @@ private static void AnalyzeTryStatement(SyntaxNodeAnalysisContext context) BlockSyntax block = tryStatement.Finally?.Block ?? tryStatement.Catches.LastOrDefault()?.Block; - if (block == null) + if (block is null) return; SyntaxToken closeBrace = block.CloseBraceToken; @@ -128,7 +128,7 @@ private static void Analyze(SyntaxNodeAnalysisContext context, SyntaxToken close ? ifStatement.GetTopmostIf().NextStatement() : blockOrStatement.NextStatement(); - if (nextStatement != null + if (nextStatement is not null && closeBrace.SyntaxTree.GetLineCount(TextSpan.FromBounds(closeBrace.Span.End, nextStatement.SpanStart)) == 2) { SyntaxTrivia endOfLine = closeBrace diff --git a/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenSwitchSectionsAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenSwitchSectionsAnalyzer.cs index d5afe4d522..98ad910c66 100644 --- a/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenSwitchSectionsAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenSwitchSectionsAnalyzer.cs @@ -57,7 +57,7 @@ private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) if (SyntaxTriviaAnalysis.IsOptionalWhitespaceThenOptionalSingleLineCommentThenEndOfLineTrivia(trailingTrivia) && (context.GetBlankLineBetweenClosingBraceAndSwitchSection() != false - || previousBlock == null)) + || previousBlock is null)) { DiagnosticHelpers.ReportDiagnostic( context, diff --git a/src/Formatting.Analyzers/CSharp/AddNewLineAfterSwitchLabelAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddNewLineAfterSwitchLabelAnalyzer.cs index a11d81a413..9b7d8f8b73 100644 --- a/src/Formatting.Analyzers/CSharp/AddNewLineAfterSwitchLabelAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddNewLineAfterSwitchLabelAnalyzer.cs @@ -38,12 +38,12 @@ private static void AnalyzeSwitchSection(SyntaxNodeAnalysisContext context) SwitchLabelSyntax label = switchSection.Labels.LastOrDefault(); - if (label == null) + if (label is null) return; StatementSyntax statement = switchSection.Statements.FirstOrDefault(); - if (statement == null) + if (statement is null) return; if (!switchSection.SyntaxTree.IsSingleLineSpan(TextSpan.FromBounds(label.Span.End, statement.SpanStart))) diff --git a/src/Formatting.Analyzers/CSharp/BlankLineBetweenAccessorsAnalyzer.cs b/src/Formatting.Analyzers/CSharp/BlankLineBetweenAccessorsAnalyzer.cs index a417e358aa..290e11ae66 100644 --- a/src/Formatting.Analyzers/CSharp/BlankLineBetweenAccessorsAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/BlankLineBetweenAccessorsAnalyzer.cs @@ -53,12 +53,12 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) AccessorDeclarationSyntax accessor1 = accessors[0]; - if (accessor1.BodyOrExpressionBody() == null) + if (accessor1.BodyOrExpressionBody() is null) return; AccessorDeclarationSyntax accessor2 = accessors[1]; - if (accessor2.BodyOrExpressionBody() == null) + if (accessor2.BodyOrExpressionBody() is null) return; SyntaxTriviaList trailingTrivia = accessor1.GetTrailingTrivia(); diff --git a/src/Formatting.Analyzers/CSharp/BlankLineBetweenUsingDirectivesAnalyzer.cs b/src/Formatting.Analyzers/CSharp/BlankLineBetweenUsingDirectivesAnalyzer.cs index 2008cfa2fa..1ead401d47 100644 --- a/src/Formatting.Analyzers/CSharp/BlankLineBetweenUsingDirectivesAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/BlankLineBetweenUsingDirectivesAnalyzer.cs @@ -68,7 +68,7 @@ private static void AnalyzeUsings(SyntaxNodeAnalysisContext context, SyntaxList< if (usingDirective1.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)) return; - if (usingDirective1.Alias != null) + if (usingDirective1.Alias is not null) return; UsingDirectiveSyntax usingDirective2 = usings[i]; @@ -76,7 +76,7 @@ private static void AnalyzeUsings(SyntaxNodeAnalysisContext context, SyntaxList< if (usingDirective2.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)) return; - if (usingDirective2.Alias != null) + if (usingDirective2.Alias is not null) return; SyntaxTriviaList trailingTrivia = usingDirective1.GetTrailingTrivia(); @@ -86,12 +86,12 @@ private static void AnalyzeUsings(SyntaxNodeAnalysisContext context, SyntaxList< IdentifierNameSyntax rootNamespace1 = usingDirective1.GetRootNamespace(); - if (rootNamespace1 == null) + if (rootNamespace1 is null) continue; IdentifierNameSyntax rootNamespace2 = usingDirective2.GetRootNamespace(); - if (rootNamespace2 == null) + if (rootNamespace2 is null) continue; SyntaxTriviaList leadingTrivia = usingDirective2.GetLeadingTrivia(); diff --git a/src/Formatting.Analyzers/CSharp/FixFormattingOfCallChainAnalyzer.cs b/src/Formatting.Analyzers/CSharp/FixFormattingOfCallChainAnalyzer.cs index be9059a9e1..37c6604e28 100644 --- a/src/Formatting.Analyzers/CSharp/FixFormattingOfCallChainAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/FixFormattingOfCallChainAnalyzer.cs @@ -114,7 +114,7 @@ bool AnalyzeToken(SyntaxToken token) if (!en.MoveNext()) { - if (lines == null) + if (lines is null) { lines = expression.SyntaxTree.GetText().Lines; startLine = lines.IndexOf(expression.SpanStart); diff --git a/src/Formatting.Analyzers/CSharp/FixFormattingOfListAnalyzer.cs b/src/Formatting.Analyzers/CSharp/FixFormattingOfListAnalyzer.cs index fa1cdb8776..53355c5044 100644 --- a/src/Formatting.Analyzers/CSharp/FixFormattingOfListAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/FixFormattingOfListAnalyzer.cs @@ -145,7 +145,7 @@ private void AnalyzeInitializerExpression(SyntaxNodeAnalysisContext context) { TNode first = nodes.FirstOrDefault(); - if (first == null) + if (first is null) return; TextSpan span = nodes.GetSpan(includeExteriorTrivia: false); @@ -208,7 +208,7 @@ private void AnalyzeInitializerExpression(SyntaxNodeAnalysisContext context) LambdaBlock lambdaBlock = GetLambdaBlock(argument, lines ??= first.SyntaxTree.GetText().Lines); - if (lambdaBlock.Block != null) + if (lambdaBlock.Block is not null) { SyntaxToken token = lambdaBlock.Token; SyntaxTriviaList leading = token.LeadingTrivia; @@ -235,7 +235,7 @@ private void AnalyzeInitializerExpression(SyntaxNodeAnalysisContext context) } } - if (lines == null) + if (lines is null) lines = first.SyntaxTree.GetText().Lines; int lineIndex = lines.IndexOf(span.Start); @@ -374,7 +374,7 @@ internal static LambdaBlock GetLambdaBlock(SyntaxNode node, TextLineCollection l } } - if (block == null) + if (block is null) { startIndex = line.EndIncludingLineBreak; openBrace = node.FindToken(startIndex); @@ -391,7 +391,7 @@ internal static LambdaBlock GetLambdaBlock(SyntaxNode node, TextLineCollection l } } - if (block != null) + if (block is not null) { int endIndex = lines.GetLineFromPosition(node.Span.End).Start; SyntaxToken closeBrace = node.FindToken(endIndex); diff --git a/src/Formatting.Analyzers/CSharp/FormatAccessorBracesAnalyzer.cs b/src/Formatting.Analyzers/CSharp/FormatAccessorBracesAnalyzer.cs index 8272bb437b..e11dca58da 100644 --- a/src/Formatting.Analyzers/CSharp/FormatAccessorBracesAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/FormatAccessorBracesAnalyzer.cs @@ -52,7 +52,7 @@ private static void AnalyzeAccessorDeclaration(SyntaxNodeAnalysisContext context BlockSyntax block = accessor.Body; - if (block == null) + if (block is null) return; SyntaxToken openBrace = block.OpenBraceToken; diff --git a/src/Formatting.Analyzers/CSharp/NormalizeWhitespaceAtEndOfFileAnalyzer.cs b/src/Formatting.Analyzers/CSharp/NormalizeWhitespaceAtEndOfFileAnalyzer.cs index aca3c07de8..eb8588e08f 100644 --- a/src/Formatting.Analyzers/CSharp/NormalizeWhitespaceAtEndOfFileAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/NormalizeWhitespaceAtEndOfFileAnalyzer.cs @@ -45,7 +45,7 @@ private static void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) bool? preferNewLineAtEndOfFile = context.PreferNewLineAtEndOfFile(); - if (preferNewLineAtEndOfFile == null) + if (preferNewLineAtEndOfFile is null) return; if (preferNewLineAtEndOfFile == false) diff --git a/src/Formatting.Analyzers/CSharp/PutAttributeListOnItsOwnLineAnalyzer.cs b/src/Formatting.Analyzers/CSharp/PutAttributeListOnItsOwnLineAnalyzer.cs index 76c3f05f93..c7b1a059ac 100644 --- a/src/Formatting.Analyzers/CSharp/PutAttributeListOnItsOwnLineAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/PutAttributeListOnItsOwnLineAnalyzer.cs @@ -276,7 +276,7 @@ private void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) private void AnalyzeAccessorList(SyntaxNodeAnalysisContext context, AccessorListSyntax accessorList) { - if (accessorList == null) + if (accessorList is null) return; foreach (AccessorDeclarationSyntax accessor in accessorList.Accessors) @@ -295,7 +295,7 @@ private static void Analyze(SyntaxNodeAnalysisContext context, SyntaxList f != statement)) { context.RegisterRefactoring( @@ -69,7 +69,7 @@ private static IfStatementSyntax GetTopmostIf(StatementSyntax statement) { SyntaxNode parent = statement.Parent; - if (parent != null) + if (parent is not null) { if (parent.IsKind(SyntaxKind.ElseClause)) { diff --git a/src/Refactorings/CSharp/Refactorings/AddBracesToSwitchSectionsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddBracesToSwitchSectionsRefactoring.cs index 1af3802690..b1cf1058aa 100644 --- a/src/Refactorings/CSharp/Refactorings/AddBracesToSwitchSectionsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddBracesToSwitchSectionsRefactoring.cs @@ -26,7 +26,7 @@ internal static class AddBracesToSwitchSectionsRefactoring .Sections .Select(section => { - if ((sections == null || Array.IndexOf(sections, section) != -1) + if ((sections is null || Array.IndexOf(sections, section) != -1) && AddBracesToSwitchSectionAnalysis.CanAddBraces(section)) { return section.WithStatements(SingletonList(Block(section.Statements))); diff --git a/src/Refactorings/CSharp/Refactorings/AddDefaultValueToParameterRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddDefaultValueToParameterRefactoring.cs index 8128b3fd4d..8a4773385e 100644 --- a/src/Refactorings/CSharp/Refactorings/AddDefaultValueToParameterRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddDefaultValueToParameterRefactoring.cs @@ -15,7 +15,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Par { SyntaxNode parent = parameter.Parent as BaseParameterListSyntax; - if (parent == null) + if (parent is null) return; parent = parent.Parent; @@ -30,7 +30,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Par TypeSyntax type = parameter.Type; - if (type == null) + if (type is null) return; SyntaxToken identifier = parameter.Identifier; @@ -75,7 +75,7 @@ ParameterSyntax GetNewParameter() EqualsValueClauseSyntax @default = EqualsValueClause(value); - if (parameter.Default == null || parameter.IsMissing) + if (parameter.Default is null || parameter.IsMissing) { return parameter .WithIdentifier(parameter.Identifier.WithoutTrailingTrivia()) diff --git a/src/Refactorings/CSharp/Refactorings/AddGenericParameterToDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddGenericParameterToDeclarationRefactoring.cs index ea88969c88..8ef25aa957 100644 --- a/src/Refactorings/CSharp/Refactorings/AddGenericParameterToDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddGenericParameterToDeclarationRefactoring.cs @@ -18,7 +18,7 @@ public static void ComputeRefactoring(RefactoringContext context, ClassDeclarati { TypeParameterListSyntax typeParameterList = classDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { if (context.Span.IsEmptyAndContainedInSpan(typeParameterList)) RegisterRefactoring(context, classDeclaration); @@ -41,7 +41,7 @@ public static void ComputeRefactoring(RefactoringContext context, RecordDeclarat { TypeParameterListSyntax typeParameterList = recordDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { if (context.Span.IsEmptyAndContainedInSpan(typeParameterList)) RegisterRefactoring(context, recordDeclaration); @@ -64,7 +64,7 @@ public static void ComputeRefactoring(RefactoringContext context, StructDeclarat { TypeParameterListSyntax typeParameterList = structDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { if (context.Span.IsEmptyAndContainedInSpan(typeParameterList)) RegisterRefactoring(context, structDeclaration); @@ -89,7 +89,7 @@ public static void ComputeRefactoring(RefactoringContext context, InterfaceDecla { TypeParameterListSyntax typeParameterList = interfaceDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { if (context.Span.IsEmptyAndContainedInSpan(typeParameterList)) RegisterRefactoring(context, interfaceDeclaration); @@ -114,7 +114,7 @@ public static void ComputeRefactoring(RefactoringContext context, DelegateDeclar { TypeParameterListSyntax typeParameterList = delegateDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { if (context.Span.IsEmptyAndContainedInSpan(typeParameterList)) RegisterRefactoring(context, delegateDeclaration); @@ -131,7 +131,7 @@ public static void ComputeRefactoring(RefactoringContext context, DelegateDeclar { ParameterListSyntax parameterList = delegateDeclaration.ParameterList; - if (parameterList != null + if (parameterList is not null && span.End <= parameterList.SpanStart) { RegisterRefactoring(context, delegateDeclaration); @@ -144,7 +144,7 @@ public static void ComputeRefactoring(RefactoringContext context, MethodDeclarat { TypeParameterListSyntax typeParameterList = methodDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { if (context.Span.IsEmptyAndContainedInSpan(typeParameterList)) RegisterRefactoring(context, methodDeclaration); @@ -161,9 +161,9 @@ public static void ComputeRefactoring(RefactoringContext context, MethodDeclarat { ParameterListSyntax parameterList = methodDeclaration.ParameterList; - if (parameterList != null + if (parameterList is not null && span.End <= parameterList.SpanStart - && methodDeclaration.BodyOrExpressionBody() != null) + && methodDeclaration.BodyOrExpressionBody() is not null) { RegisterRefactoring(context, methodDeclaration); } @@ -175,7 +175,7 @@ internal static void ComputeRefactoring(RefactoringContext context, LocalFunctio { TypeParameterListSyntax typeParameterList = localFunctionStatement.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { if (context.Span.IsEmptyAndContainedInSpan(typeParameterList)) RegisterRefactoring(context, localFunctionStatement); @@ -192,7 +192,7 @@ internal static void ComputeRefactoring(RefactoringContext context, LocalFunctio { ParameterListSyntax parameterList = localFunctionStatement.ParameterList; - if (parameterList != null + if (parameterList is not null && span.End <= parameterList.SpanStart) { RegisterRefactoring(context, localFunctionStatement); @@ -300,7 +300,7 @@ private static void RegisterRefactoring(RefactoringContext context, SyntaxNode n MethodDeclarationSyntax newNode = methodDeclaration.AddTypeParameterListParameters(TypeParameter(Identifier(name).WithRenameAnnotation())); - if (constraint != null) + if (constraint is not null) newNode = newNode.AddConstraintClauses(TypeParameterConstraintClause(name, constraint)); return newNode; @@ -315,7 +315,7 @@ private static void RegisterRefactoring(RefactoringContext context, SyntaxNode n ClassDeclarationSyntax newNode = classDeclaration.AddTypeParameterListParameters(TypeParameter(Identifier(name).WithRenameAnnotation())); - if (constraint != null) + if (constraint is not null) newNode = newNode.AddConstraintClauses(TypeParameterConstraintClause(name, constraint)); return newNode; @@ -334,7 +334,7 @@ private static void RegisterRefactoring(RefactoringContext context, SyntaxNode n RecordDeclarationSyntax newNode = recordDeclaration.AddTypeParameterListParameters(TypeParameter(Identifier(name).WithRenameAnnotation())); - if (constraint != null) + if (constraint is not null) newNode = newNode.AddConstraintClauses(TypeParameterConstraintClause(name, constraint)); return newNode; @@ -349,7 +349,7 @@ private static void RegisterRefactoring(RefactoringContext context, SyntaxNode n StructDeclarationSyntax newNode = structDeclaration.AddTypeParameterListParameters(TypeParameter(Identifier(name).WithRenameAnnotation())); - if (typeParameterConstraint != null) + if (typeParameterConstraint is not null) newNode = newNode.AddConstraintClauses(TypeParameterConstraintClause(name, typeParameterConstraint)); return newNode; @@ -364,7 +364,7 @@ private static void RegisterRefactoring(RefactoringContext context, SyntaxNode n InterfaceDeclarationSyntax newNode = interfaceDeclaration.AddTypeParameterListParameters(TypeParameter(Identifier(name).WithRenameAnnotation())); - if (constraint != null) + if (constraint is not null) newNode = newNode.AddConstraintClauses(TypeParameterConstraintClause(name, constraint)); return newNode; @@ -377,7 +377,7 @@ private static void RegisterRefactoring(RefactoringContext context, SyntaxNode n { TypeParameterListSyntax typeParameterList = delegateDeclaration.TypeParameterList; - int position = (typeParameterList != null) + int position = (typeParameterList is not null) ? typeParameterList.SpanStart : delegateDeclaration.Identifier.SpanStart; @@ -385,7 +385,7 @@ private static void RegisterRefactoring(RefactoringContext context, SyntaxNode n DelegateDeclarationSyntax newNode = delegateDeclaration.AddTypeParameterListParameters(TypeParameter(Identifier(name).WithRenameAnnotation())); - if (constraint != null) + if (constraint is not null) newNode = newNode.AddConstraintClauses(TypeParameterConstraintClause(name, constraint)); return newNode; @@ -401,7 +401,7 @@ private static void RegisterRefactoring(RefactoringContext context, SyntaxNode n LocalFunctionStatementSyntax newNode = localFunctionStatement.AddTypeParameterListParameters(TypeParameter(Identifier(name).WithRenameAnnotation())); - if (constraint != null) + if (constraint is not null) newNode = newNode.AddConstraintClauses(TypeParameterConstraintClause(name, constraint)); return newNode; diff --git a/src/Refactorings/CSharp/Refactorings/AddMemberToInterfaceRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddMemberToInterfaceRefactoring.cs index e49af2dc47..85916c72ad 100644 --- a/src/Refactorings/CSharp/Refactorings/AddMemberToInterfaceRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddMemberToInterfaceRefactoring.cs @@ -56,7 +56,7 @@ internal static void ComputeRefactoring(RefactoringContext context, EventFieldDe BaseListSyntax baseList = GetBaseList(memberDeclaration.Parent); - if (baseList == null) + if (baseList is null) return; SeparatedSyntaxList types = baseList.Types; @@ -66,7 +66,7 @@ internal static void ComputeRefactoring(RefactoringContext context, EventFieldDe NameSyntax explicitInterfaceName = explicitInterfaceSpecifier?.Name; - ITypeSymbol explicitInterfaceSymbol = (explicitInterfaceName != null) + ITypeSymbol explicitInterfaceSymbol = (explicitInterfaceName is not null) ? semanticModel.GetTypeSymbol(explicitInterfaceName, context.CancellationToken)?.OriginalDefinition : null; @@ -74,7 +74,7 @@ internal static void ComputeRefactoring(RefactoringContext context, EventFieldDe ? semanticModel.GetDeclaredSymbol(eventFieldDeclaration.Declaration.Variables[0]) : semanticModel.GetDeclaredSymbol(memberDeclaration); - if (memberSymbol == null) + if (memberSymbol is null) return; int count = 0; @@ -101,7 +101,7 @@ internal static void ComputeRefactoring(RefactoringContext context, EventFieldDe { TypeSyntax type = baseType.Type; - if (type == null) + if (type is null) return false; var interfaceSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken) as INamedTypeSymbol; @@ -281,7 +281,7 @@ private static MemberDeclarationSyntax CreateInterfaceMemberDeclaration(MemberDe private static AccessorListSyntax CreateInterfaceAccessorList(AccessorListSyntax accessorList) { - if (accessorList != null) + if (accessorList is not null) { return AccessorList(accessorList .Accessors diff --git a/src/Refactorings/CSharp/Refactorings/AddOrRemoveParameterName/AddArgumentNameRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddOrRemoveParameterName/AddArgumentNameRefactoring.cs index 74b38ae22b..6e12491e92 100644 --- a/src/Refactorings/CSharp/Refactorings/AddOrRemoveParameterName/AddArgumentNameRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddOrRemoveParameterName/AddArgumentNameRefactoring.cs @@ -43,7 +43,7 @@ internal static class AddArgumentNameRefactoring allowParams: false, cancellationToken: cancellationToken); - if (parameterSymbol != null) + if (parameterSymbol is not null) return true; } } diff --git a/src/Refactorings/CSharp/Refactorings/AddOrRemoveParameterName/AddParameterNameRewriter.cs b/src/Refactorings/CSharp/Refactorings/AddOrRemoveParameterName/AddParameterNameRewriter.cs index ddb20c180e..96a883c75c 100644 --- a/src/Refactorings/CSharp/Refactorings/AddOrRemoveParameterName/AddParameterNameRewriter.cs +++ b/src/Refactorings/CSharp/Refactorings/AddOrRemoveParameterName/AddParameterNameRewriter.cs @@ -48,7 +48,7 @@ public override SyntaxNode VisitArgument(ArgumentSyntax node) allowParams: false, cancellationToken: cancellationToken); - if (parameterSymbol != null) + if (parameterSymbol is not null) { ArgumentSyntax newArgument = argument.WithoutLeadingTrivia(); diff --git a/src/Refactorings/CSharp/Refactorings/AddOrRenameParameterRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddOrRenameParameterRefactoring.cs index 77fd4743d2..c418d22a7a 100644 --- a/src/Refactorings/CSharp/Refactorings/AddOrRenameParameterRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddOrRenameParameterRefactoring.cs @@ -22,7 +22,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Pa IParameterSymbol parameterSymbol = semanticModel.GetDeclaredSymbol(parameter, context.CancellationToken); - if (parameterSymbol?.Type == null) + if (parameterSymbol?.Type is null) return; if (!parameter.Identifier.IsMissing @@ -37,7 +37,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Pa semanticModel, cancellationToken: context.CancellationToken); - if (newName != null) + if (newName is not null) { context.RegisterRefactoring( $"Rename '{oldName}' to '{newName}'", diff --git a/src/Refactorings/CSharp/Refactorings/AttributeArgumentParameterNameRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AttributeArgumentParameterNameRefactoring.cs index df3ecbd2bd..4ab3d2cca1 100644 --- a/src/Refactorings/CSharp/Refactorings/AttributeArgumentParameterNameRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AttributeArgumentParameterNameRefactoring.cs @@ -34,14 +34,14 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, At foreach (AttributeArgumentSyntax argument in argumentList.Arguments) { - if (argument.Expression != null + if (argument.Expression is not null && context.Span.Contains(argument.Expression.Span)) { (list ??= new List()).Add(argument); } } - if (list == null) + if (list is null) return; AttributeArgumentSyntax[] arguments = list.ToArray(); @@ -56,7 +56,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, At } if (context.IsRefactoringEnabled(RefactoringDescriptors.RemoveArgumentName) - && arguments.Any(f => f.NameColon != null)) + && arguments.Any(f => f.NameColon is not null)) { context.RegisterRefactoring( "Remove argument name", @@ -103,7 +103,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, At allowParams: false, cancellationToken: cancellationToken); - if (parameterSymbol != null) + if (parameterSymbol is not null) { return argument .WithNameColon( @@ -131,7 +131,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, At allowParams: false, cancellationToken: context.CancellationToken); - if (parameterSymbol != null) + if (parameterSymbol is not null) return true; } } @@ -180,7 +180,7 @@ private RemoveParameterNameSyntaxRewriter(AttributeArgumentSyntax[] arguments = public static AttributeArgumentListSyntax VisitNode(AttributeArgumentListSyntax argumentList, AttributeArgumentSyntax[] arguments = null) { - if (arguments == null) + if (arguments is null) { return (AttributeArgumentListSyntax)_instance.Visit(argumentList); } @@ -193,7 +193,7 @@ public static AttributeArgumentListSyntax VisitNode(AttributeArgumentListSyntax public override SyntaxNode VisitAttributeArgument(AttributeArgumentSyntax node) { - if (_arguments == null || Array.IndexOf(_arguments, node) != -1) + if (_arguments is null || Array.IndexOf(_arguments, node) != -1) { return node .WithNameColon(null) diff --git a/src/Refactorings/CSharp/Refactorings/AttributeListRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AttributeListRefactoring.cs index 6ee8a0e871..b88204b61e 100644 --- a/src/Refactorings/CSharp/Refactorings/AttributeListRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AttributeListRefactoring.cs @@ -96,7 +96,7 @@ public static void ComputeRefactorings(RefactoringContext context, MemberDeclara public static SyntaxList GetAttributeLists(this SyntaxNode node) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); switch (node.Kind()) @@ -157,7 +157,7 @@ public static SyntaxList GetAttributeLists(this SyntaxNode public static CSharpSyntaxNode WithAttributeLists(this CSharpSyntaxNode node, SyntaxList attributeLists) { - if (node == null) + if (node is null) throw new ArgumentNullException(nameof(node)); switch (node.Kind()) diff --git a/src/Refactorings/CSharp/Refactorings/ChangeMethodReturnTypeToVoidRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ChangeMethodReturnTypeToVoidRefactoring.cs index d6583f6250..b5e128485c 100644 --- a/src/Refactorings/CSharp/Refactorings/ChangeMethodReturnTypeToVoidRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ChangeMethodReturnTypeToVoidRefactoring.cs @@ -19,7 +19,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Met BlockSyntax body = methodDeclaration.Body; - if (body == null) + if (body is null) return; SyntaxList statements = body.Statements; @@ -49,7 +49,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Loc BlockSyntax body = localFunction.Body; - if (body == null) + if (body is null) return; SyntaxList statements = body.Statements; @@ -94,7 +94,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Loc if (!analysis.Succeeded) return; - if (!analysis.ReturnStatements.All(f => (f as ReturnStatementSyntax)?.Expression == null)) + if (!analysis.ReturnStatements.All(f => (f as ReturnStatementSyntax)?.Expression is null)) return; Document document = context.Document; diff --git a/src/Refactorings/CSharp/Refactorings/ChangeVariableDeclarationTypeRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ChangeVariableDeclarationTypeRefactoring.cs index a3063681ee..9b1e83888a 100644 --- a/src/Refactorings/CSharp/Refactorings/ChangeVariableDeclarationTypeRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ChangeVariableDeclarationTypeRefactoring.cs @@ -46,7 +46,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Va VariableDeclaratorSyntax variableDeclarator = variableDeclaration.Variables.SingleOrDefault(shouldThrow: false); - if (variableDeclarator?.Initializer?.Value != null) + if (variableDeclarator?.Initializer?.Value is not null) { if (typeSymbol.OriginalDefinition.EqualsOrInheritsFromTaskOfT()) { @@ -58,7 +58,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Va semanticModel, context.CancellationToken); - if (createChangedDocument != null) + if (createChangedDocument is not null) { context.RegisterRefactoring( "Use explicit type (and add 'await')", @@ -70,7 +70,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Va typeSymbol = semanticModel.GetTypeSymbol(variableDeclarator.Initializer.Value, context.CancellationToken); - if (typeSymbol != null) + if (typeSymbol is not null) { context.RegisterRefactoring(CodeActionFactory.UseExplicitType(context.Document, type, typeSymbol, semanticModel, equivalenceKey: EquivalenceKey.Create(RefactoringDescriptors.UseExplicitType))); } @@ -89,7 +89,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Va { ExpressionSyntax value = variableDeclarator.Initializer?.Value; - if (value == null) + if (value is null) return; Conversion conversion = semanticModel.ClassifyConversion(value, typeSymbol); @@ -103,7 +103,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Va ITypeSymbol newTypeSymbol = semanticModel.GetTypeSymbol(variableDeclaration.Variables[0].Initializer.Value, context.CancellationToken); - if (newTypeSymbol == null) + if (newTypeSymbol is null) return; context.RegisterRefactoring(CodeActionFactory.UseExplicitType(context.Document, variableDeclaration.Type, newTypeSymbol, semanticModel, equivalenceKey: EquivalenceKey.Create(RefactoringDescriptors.ChangeTypeAccordingToExpression))); diff --git a/src/Refactorings/CSharp/Refactorings/CheckExpressionForNullRefactoring.cs b/src/Refactorings/CSharp/Refactorings/CheckExpressionForNullRefactoring.cs index 24d4b40c13..9ff48e0bae 100644 --- a/src/Refactorings/CSharp/Refactorings/CheckExpressionForNullRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/CheckExpressionForNullRefactoring.cs @@ -59,7 +59,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Exp ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return false; return typeSymbol.IsReferenceTypeOrNullableType(); @@ -100,7 +100,7 @@ private static bool CanRefactor(in SingleLocalDeclarationStatementInfo localInfo ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(localInfo.Type, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return false; return typeSymbol.IsReferenceTypeOrNullableType(); @@ -359,13 +359,13 @@ private static IfStatementSyntax CreateNullCheck(ExpressionSyntax expression, Sy { VariableDeclarationSyntax declaration = localDeclaration.Declaration; - if (declaration != null) + if (declaration is not null) { foreach (VariableDeclaratorSyntax variable in declaration.Variables) { ISymbol symbol = semanticModel.GetDeclaredSymbol(variable, cancellationToken); - if (symbol != null) + if (symbol is not null) { int index = IncludeAllReferencesOfSymbol(symbol, SyntaxKind.IdentifierName, statements, i + 1, semanticModel, cancellationToken); diff --git a/src/Refactorings/CSharp/Refactorings/CheckParameterForNullRefactoring.cs b/src/Refactorings/CSharp/Refactorings/CheckParameterForNullRefactoring.cs index 5dc9ed2ae9..a097f799df 100644 --- a/src/Refactorings/CSharp/Refactorings/CheckParameterForNullRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/CheckParameterForNullRefactoring.cs @@ -42,13 +42,13 @@ public static void ComputeRefactoring(RefactoringContext context, SeparatedSynta if (IsValid(parameter, semanticModel, context.CancellationToken) && CanRefactor(parameter, semanticModel, context.CancellationToken)) { - if (singleParameter == null) + if (singleParameter is null) { singleParameter = parameter; } else { - if (builder == null) + if (builder is null) builder = ImmutableArray.CreateBuilder(selectedParameters.Count); builder.Add(singleParameter); @@ -57,11 +57,11 @@ public static void ComputeRefactoring(RefactoringContext context, SeparatedSynta } } - if (builder != null) + if (builder is not null) { RegisterRefactoring(context, builder.ToImmutableArray(), "parameters", semanticModel); } - else if (singleParameter != null) + else if (singleParameter is not null) { RegisterRefactoring(context, singleParameter, semanticModel); } @@ -95,7 +95,7 @@ private static void RegisterRefactoring(RefactoringContext context, ParameterSyn { BlockSyntax body = GetBody(parameter); - if (body == null) + if (body is null) return false; IParameterSymbol parameterSymbol = semanticModel.GetDeclaredSymbol(parameter, cancellationToken); @@ -209,9 +209,9 @@ private static BlockSyntax GetBody(ParameterSyntax parameter) parent = parent.Parent; - Debug.Assert(parent != null); + Debug.Assert(parent is not null); - if (parent == null) + if (parent is null) return null; switch (parent.Kind()) @@ -247,7 +247,7 @@ private static BlockSyntax GetBody(ParameterSyntax parameter) private static bool IsValid(ParameterSyntax parameter, SemanticModel semanticModel, CancellationToken cancellationToken) { - return parameter.Type != null + return parameter.Type is not null && !parameter.Identifier.IsMissing && parameter.IsParentKind(SyntaxKind.ParameterList) && parameter.Default?.Value?.IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression, SyntaxKind.DefaultExpression) != true diff --git a/src/Refactorings/CSharp/Refactorings/CloseParenTokenRefactoring.cs b/src/Refactorings/CSharp/Refactorings/CloseParenTokenRefactoring.cs index 7d8a4862f6..10b382128c 100644 --- a/src/Refactorings/CSharp/Refactorings/CloseParenTokenRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/CloseParenTokenRefactoring.cs @@ -28,7 +28,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Sy .FindNode(new TextSpan(context.Span.Start - 1, 1))? .FirstAncestorOrSelf(); - if (parameter != null) + if (parameter is not null) await ParameterRefactoring.ComputeRefactoringsAsync(context, parameter).ConfigureAwait(false); } @@ -38,7 +38,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Sy .Arguments .FirstOrDefault(f => f.FullSpan.End == closeParen.FullSpan.Start); - if (argument != null) + if (argument is not null) ArgumentRefactoring.ComputeRefactorings(context, argument); } } diff --git a/src/Refactorings/CSharp/Refactorings/CommaTokenRefactoring.cs b/src/Refactorings/CSharp/Refactorings/CommaTokenRefactoring.cs index ff1bdb3b2c..77eb9d8552 100644 --- a/src/Refactorings/CSharp/Refactorings/CommaTokenRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/CommaTokenRefactoring.cs @@ -28,7 +28,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Sy .FindNode(new TextSpan(context.Span.Start - 1, 1))? .FirstAncestorOrSelf(); - if (parameter != null) + if (parameter is not null) await ParameterRefactoring.ComputeRefactoringsAsync(context, parameter).ConfigureAwait(false); } @@ -38,7 +38,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Sy .Arguments .FirstOrDefault(f => f.FullSpan.End == commaToken.FullSpan.Start); - if (argument != null) + if (argument is not null) ArgumentRefactoring.ComputeRefactorings(context, argument); } } diff --git a/src/Refactorings/CSharp/Refactorings/ConditionalExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConditionalExpressionRefactoring.cs index b6f46825f7..f241a0e611 100644 --- a/src/Refactorings/CSharp/Refactorings/ConditionalExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConditionalExpressionRefactoring.cs @@ -47,10 +47,10 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Co semanticModel, context.CancellationToken); - if (codeAction != null) + if (codeAction is not null) context.RegisterRefactoring(codeAction); - if (recursiveCodeAction != null) + if (recursiveCodeAction is not null) context.RegisterRefactoring(recursiveCodeAction); } } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertAutoPropertyToFullPropertyRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertAutoPropertyToFullPropertyRefactoring.cs index 1c8872dbaa..9ca80ec184 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertAutoPropertyToFullPropertyRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertAutoPropertyToFullPropertyRefactoring.cs @@ -44,7 +44,7 @@ internal static class ConvertAutoPropertyToFullPropertyRefactoring AccessorDeclarationSyntax getter = propertyDeclaration.Getter(); - if (getter != null) + if (getter is not null) { AccessorDeclarationSyntax newGetter = getter.Update( getter.AttributeLists, @@ -63,7 +63,7 @@ internal static class ConvertAutoPropertyToFullPropertyRefactoring AccessorDeclarationSyntax newSetter = null; - if (setter != null) + if (setter is not null) { newSetter = ExpandSetter(); @@ -91,7 +91,7 @@ internal static class ConvertAutoPropertyToFullPropertyRefactoring int propertyIndex = membersInfo.IndexOf(propertyDeclaration); if (propertyDeclaration.AccessorList?.Getter()?.IsAutoImplemented() == true - && propertyDeclaration.AccessorList.Setter() == null) + && propertyDeclaration.AccessorList.Setter() is null) { var rewriter = new Rewriter(propertySymbol, fieldName, semanticModel, cancellationToken); @@ -128,7 +128,7 @@ AccessorDeclarationSyntax ExpandSetter() { IMethodSymbol methodSymbol = SymbolUtility.FindMethodThatRaisePropertyChanged(containingType, setter.SpanStart, semanticModel); - if (methodSymbol != null) + if (methodSymbol is not null) { string propertyName = propertyDeclaration.Identifier.ValueText; @@ -154,7 +154,7 @@ AccessorDeclarationSyntax ExpandSetter() } } - if (body == null) + if (body is null) { body = Block(SimpleAssignmentStatement(fieldExpression, valueName)); } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertAutoPropertyToFullPropertyWithoutBackingFieldRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertAutoPropertyToFullPropertyWithoutBackingFieldRefactoring.cs index ba9d510c84..5ed41f5b9a 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertAutoPropertyToFullPropertyWithoutBackingFieldRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertAutoPropertyToFullPropertyWithoutBackingFieldRefactoring.cs @@ -19,7 +19,7 @@ public static bool CanRefactor(PropertyDeclarationSyntax propertyDeclaration) && propertyDeclaration .AccessorList? .Accessors - .All(f => f.BodyOrExpressionBody() == null) == true; + .All(f => f.BodyOrExpressionBody() is null) == true; } public static Task RefactorAsync( @@ -53,7 +53,7 @@ IEnumerable ExpandProperty() { ExpressionSyntax value = propertyDeclaration.Initializer?.Value; - if (value != null) + if (value is not null) { yield return accessor .WithBody(Block(ReturnStatement(value))) diff --git a/src/Refactorings/CSharp/Refactorings/ConvertBodyAndExpressionBodyRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertBodyAndExpressionBodyRefactoring.cs index 83626dc39c..088b16d2a6 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertBodyAndExpressionBodyRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertBodyAndExpressionBodyRefactoring.cs @@ -17,7 +17,7 @@ public static void ComputeRefactoring(RefactoringContext context, MemberDeclarat RefactoringDescriptor refactoring = GetRefactoringDescriptor(selectedMembers.First()); - if (refactoring.Id == null) + if (refactoring.Id is null) return; if (!RefactoringDescriptorComparer.Id.Equals(refactoring, GetRefactoringDescriptor(selectedMembers.Last()))) @@ -48,7 +48,7 @@ private static RefactoringDescriptor GetRefactoringDescriptor(MemberDeclarationS { ArrowExpressionClauseSyntax expressionBody = methodDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; @@ -64,7 +64,7 @@ private static RefactoringDescriptor GetRefactoringDescriptor(MemberDeclarationS { ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; @@ -80,7 +80,7 @@ private static RefactoringDescriptor GetRefactoringDescriptor(MemberDeclarationS { ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; @@ -96,7 +96,7 @@ private static RefactoringDescriptor GetRefactoringDescriptor(MemberDeclarationS { ArrowExpressionClauseSyntax expressionBody = operatorDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; @@ -112,7 +112,7 @@ private static RefactoringDescriptor GetRefactoringDescriptor(MemberDeclarationS { ArrowExpressionClauseSyntax expressionBody = conversionOperatorDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; @@ -128,7 +128,7 @@ private static RefactoringDescriptor GetRefactoringDescriptor(MemberDeclarationS { ArrowExpressionClauseSyntax expressionBody = constructorDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; @@ -144,7 +144,7 @@ private static RefactoringDescriptor GetRefactoringDescriptor(MemberDeclarationS { ArrowExpressionClauseSyntax expressionBody = destructorDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; diff --git a/src/Refactorings/CSharp/Refactorings/ConvertForToForEachRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertForToForEachRefactoring.cs index 31d88a412e..8d4ce87034 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertForToForEachRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertForToForEachRefactoring.cs @@ -54,9 +54,9 @@ internal static class ConvertForToForEachRefactoring f => f.Parameters.SingleOrDefault(shouldThrow: false)?.Type.SpecialType == SpecialType.System_Int32, includeBaseTypes: true); - Debug.Assert(member != null, ""); + Debug.Assert(member is not null, ""); - if (member != null) + if (member is not null) type = member.Type.ToTypeSyntax().WithSimplifierAnnotation(); } @@ -80,7 +80,7 @@ public static async Task CanRefactorAsync(RefactoringContext context, ForS .Variables .SingleOrDefault(shouldThrow: false); - if (variableDeclarator == null) + if (variableDeclarator is null) return false; if (variableDeclarator.Initializer?.Value?.IsNumericLiteralExpression("0") != true) @@ -105,7 +105,7 @@ public static async Task CanRefactorAsync(RefactoringContext context, ForS ExpressionSyntax expression = memberAccessExpression.Expression; - if (expression == null) + if (expression is null) return false; if (forStatement.Incrementors.SingleOrDefault(shouldThrow: false)?.IsKind(SyntaxKind.PostIncrementExpression) != true) @@ -115,7 +115,7 @@ public static async Task CanRefactorAsync(RefactoringContext context, ForS ISymbol symbol = semanticModel.GetSymbol(expression, context.CancellationToken); - if (symbol == null) + if (symbol is null) return false; ISymbol variableSymbol = semanticModel.GetDeclaredSymbol(variableDeclarator, context.CancellationToken); @@ -162,7 +162,7 @@ public static async Task CanRefactorAsync(RefactoringContext context, ForS ExpressionSyntax expression = elementAccess.Expression; - if (expression == null) + if (expression is null) return false; ISymbol expressionSymbol = semanticModel.GetSymbol(expression, cancellationToken); diff --git a/src/Refactorings/CSharp/Refactorings/ConvertForToWhileRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertForToWhileRefactoring.cs index db911e5bf9..f615199b9c 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertForToWhileRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertForToWhileRefactoring.cs @@ -23,7 +23,7 @@ internal static class ConvertForToWhileRefactoring VariableDeclarationSyntax declaration = forStatement.Declaration; - if (declaration != null) + if (declaration is not null) { statements.Add(LocalDeclarationStatement(declaration)); } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs index d78dd689c3..72297af33d 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs @@ -107,7 +107,7 @@ internal static class ConvertIfToSwitchRefactoring ExpressionSyntax expression = isPatternExpression.Expression.WalkDownParentheses(); - if (switchExpression == null) + if (switchExpression is null) { switchExpression = expression; } @@ -139,7 +139,7 @@ bool IsFixableEqualsExpression(BinaryExpressionSyntax equalsExpression) { ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(right, cancellationToken).ConvertedType; - if (typeSymbol == null) + if (typeSymbol is null) return false; if (!SymbolUtility.SupportsSwitchExpression(typeSymbol)) @@ -151,7 +151,7 @@ bool IsFixableEqualsExpression(BinaryExpressionSyntax equalsExpression) ExpressionSyntax left = binaryExpressionInfo.Left; - if (switchExpression == null) + if (switchExpression is null) { switchExpression = left; } @@ -342,7 +342,7 @@ static bool ShouldDescendIntoChildren(SyntaxKind kind) bool IsContainedInIterationStatement() { - for (SyntaxNode node = statement.Parent; node != null; node = node.Parent) + for (SyntaxNode node = statement.Parent; node is not null; node = node.Parent) { if (node is MemberDeclarationSyntax) break; diff --git a/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToConcatenationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToConcatenationRefactoring.cs index 4e2ad17740..47690852c2 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToConcatenationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToConcatenationRefactoring.cs @@ -25,10 +25,10 @@ public static void ComputeRefactoring(RefactoringContext context, InterpolatedSt { var interpolation = (InterpolationSyntax)content; - if (interpolation.AlignmentClause != null) + if (interpolation.AlignmentClause is not null) return; - if (interpolation.FormatClause != null) + if (interpolation.FormatClause is not null) return; } } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToStringFormatRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToStringFormatRefactoring.cs index 1f3945eb09..ca8cb7e129 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToStringFormatRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToStringFormatRefactoring.cs @@ -94,14 +94,14 @@ void Analyze() index++; InterpolationAlignmentClauseSyntax alignmentClause = interpolation.AlignmentClause; - if (alignmentClause != null) + if (alignmentClause is not null) { b.Append(","); b.AppendSpan(alignmentClause.Value); } InterpolationFormatClauseSyntax formatClause = interpolation.FormatClause; - if (formatClause != null) + if (formatClause is not null) { b.Append(":"); b.AppendSpan(formatClause.FormatStringToken); diff --git a/src/Refactorings/CSharp/Refactorings/ConvertReturnToIf/ConvertReturnToIfRefactoring`1.cs b/src/Refactorings/CSharp/Refactorings/ConvertReturnToIf/ConvertReturnToIfRefactoring`1.cs index fd19bafa88..ca6b4a2b11 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertReturnToIf/ConvertReturnToIfRefactoring`1.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertReturnToIf/ConvertReturnToIfRefactoring`1.cs @@ -22,7 +22,7 @@ public async Task ComputeRefactoringAsync(RefactoringContext context, TStatement { ExpressionSyntax expression = GetExpression(statement); - if (expression == null) + if (expression is null) return; if (CSharpFacts.IsBooleanLiteralExpression(expression.Kind())) @@ -71,7 +71,7 @@ private IfStatementSyntax CreateIfStatement(TStatement statement, ExpressionSynt { ExpressionSyntax right = binaryExpression.Right; - if (right != null) + if (right is not null) return CreateIfStatement(statement, left, TrueLiteralExpression(), right.WithoutTrivia()); } } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertStatementsToIfElseRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertStatementsToIfElseRefactoring.cs index 222a042066..ab380278a0 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertStatementsToIfElseRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertStatementsToIfElseRefactoring.cs @@ -34,7 +34,7 @@ public static void ComputeRefactorings(RefactoringContext context, StatementList if (statement is BlockSyntax block) statement = block.Statements.LastOrDefault(); - if (statement == null) + if (statement is null) return; if (!statement.IsKind( @@ -77,7 +77,7 @@ public static void ComputeRefactorings(RefactoringContext context, StatementList StatementSyntax elseStatement = newIfStatement; - if (elseStatement == null) + if (elseStatement is null) { if (selectedStatements.Count - ifStatementCount > 1) { diff --git a/src/Refactorings/CSharp/Refactorings/ConvertStringFormatToInterpolatedStringRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertStringFormatToInterpolatedStringRefactoring.cs index a192413e37..3d576582cd 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertStringFormatToInterpolatedStringRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertStringFormatToInterpolatedStringRefactoring.cs @@ -24,18 +24,18 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In ImmutableArray formatMethods; - while (invocation != null) + while (invocation is not null) { ArgumentListSyntax argumentList = invocation.ArgumentList; - if (argumentList != null) + if (argumentList is not null) { SeparatedSyntaxList arguments = argumentList.Arguments; if (arguments.Count >= 2 && (arguments[0].Expression?.Kind() == SyntaxKind.StringLiteralExpression)) { - if (semanticModel == null) + if (semanticModel is null) semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ISymbol invocationSymbol = semanticModel.GetSymbol(invocation, context.CancellationToken); @@ -56,7 +56,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In invocation = invocation.FirstAncestor(); } - if (invocation == null) + if (invocation is null) return; context.RegisterRefactoring( @@ -69,7 +69,7 @@ private static ImmutableArray GetFormatMethods(SemanticModel semanticMo { INamedTypeSymbol stringType = semanticModel.Compilation.GetSpecialType(SpecialType.System_String); - if (stringType == null) + if (stringType is null) return ImmutableArray.Empty; return stringType @@ -211,7 +211,7 @@ private static bool CanReplaceInterpolationWithStringLiteralInnerText(SeparatedS ITypeSymbol targetType = semanticModel.GetTypeInfo(expression, cancellationToken).ConvertedType; - if (targetType != null) + if (targetType is not null) { TypeSyntax type = targetType.ToMinimalTypeSyntax(semanticModel, expression.SpanStart); diff --git a/src/Refactorings/CSharp/Refactorings/ConvertSwitchToIfRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertSwitchToIfRefactoring.cs index 6b7631313b..f6d2e04361 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertSwitchToIfRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertSwitchToIfRefactoring.cs @@ -110,7 +110,7 @@ public static void ComputeRefactoring(RefactoringContext context, SwitchStatemen CreateCondition(switchStatement, sections[i], semanticModel), Block(statements)); - if (ifStatement != null) + if (ifStatement is not null) { ifStatement = @if.WithElse(ElseClause(ifStatement)); } @@ -118,7 +118,7 @@ public static void ComputeRefactoring(RefactoringContext context, SwitchStatemen { ifStatement = @if; - if (elseClause != null) + if (elseClause is not null) ifStatement = ifStatement.WithElse(elseClause); } } @@ -151,7 +151,7 @@ public static void ComputeRefactoring(RefactoringContext context, SwitchStatemen { BinaryExpressionSyntax equalsExpression = EqualsExpression(switchExpression, constantLabel.Value); - if (semanticModel.GetSpeculativeMethodSymbol(switchSection.SpanStart, equalsExpression) != null) + if (semanticModel.GetSpeculativeMethodSymbol(switchSection.SpanStart, equalsExpression) is not null) { expression = equalsExpression; } @@ -169,7 +169,7 @@ public static void ComputeRefactoring(RefactoringContext context, SwitchStatemen { expression = IsPatternExpression(switchExpression.Parenthesize(), patternLabel.Pattern).Parenthesize(); - if (patternLabel.WhenClause != null) + if (patternLabel.WhenClause is not null) { expression = LogicalAndExpression( expression, @@ -185,7 +185,7 @@ public static void ComputeRefactoring(RefactoringContext context, SwitchStatemen } } - if (condition != null) + if (condition is not null) { condition = LogicalOrExpression(expression, condition); } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertWhileToForRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertWhileToForRefactoring.cs index 94e20bd88f..35d849b087 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertWhileToForRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertWhileToForRefactoring.cs @@ -102,13 +102,13 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Sta { var symbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variable, cancellationToken); - if (symbol == null) + if (symbol is null) continue; if (symbol.Type.IsErrorType()) continue; - if (typeSymbol == null) + if (typeSymbol is null) { typeSymbol = symbol.Type; } @@ -146,7 +146,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Sta } finally { - if (walker != null) + if (walker is not null) ContainsLocalOrParameterReferenceWalker.Free(walker); } diff --git a/src/Refactorings/CSharp/Refactorings/CopyAttributeArgumentRefactoring.cs b/src/Refactorings/CSharp/Refactorings/CopyAttributeArgumentRefactoring.cs index 3ad9fda790..4fe473beb1 100644 --- a/src/Refactorings/CSharp/Refactorings/CopyAttributeArgumentRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/CopyAttributeArgumentRefactoring.cs @@ -16,7 +16,7 @@ public static void ComputeRefactoring(RefactoringContext context, AttributeArgum AttributeArgumentSyntax argument = GetArgument(context, argumentList); - if (argument == null) + if (argument is null) return; context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/DeclarationExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/DeclarationExpressionRefactoring.cs index e3a2803054..b5f3bcb6da 100644 --- a/src/Refactorings/CSharp/Refactorings/DeclarationExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/DeclarationExpressionRefactoring.cs @@ -25,7 +25,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, De { TypeSyntax type = declarationExpression.Type; - if (type == null) + if (type is null) return; VariableDesignationSyntax designation = declarationExpression.Designation; @@ -56,7 +56,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, De singleVariableDesignation.SpanStart, cancellationToken: context.CancellationToken); - if (newName == null) + if (newName is null) return; context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/DeclarationPatternRefactoring.cs b/src/Refactorings/CSharp/Refactorings/DeclarationPatternRefactoring.cs index 976ddf3e7f..7b829f44d7 100644 --- a/src/Refactorings/CSharp/Refactorings/DeclarationPatternRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/DeclarationPatternRefactoring.cs @@ -42,7 +42,7 @@ internal static async Task ComputeRefactoringAsync(RefactoringContext context, D singleVariableDesignation.SpanStart, cancellationToken: context.CancellationToken); - if (newName != null) + if (newName is not null) { context.RegisterRefactoring( $"Rename '{oldName}' to '{newName}'", diff --git a/src/Refactorings/CSharp/Refactorings/EventFieldDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/EventFieldDeclarationRefactoring.cs index b0446d45f9..dc810550e7 100644 --- a/src/Refactorings/CSharp/Refactorings/EventFieldDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/EventFieldDeclarationRefactoring.cs @@ -35,7 +35,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Ev { VariableDeclaratorSyntax variableDeclarator = eventFieldDeclaration.Declaration?.Variables.SingleOrDefault(shouldThrow: false); - if (variableDeclarator != null + if (variableDeclarator is not null && context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(variableDeclarator.Identifier)) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); diff --git a/src/Refactorings/CSharp/Refactorings/ExpandInitializerRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ExpandInitializerRefactoring.cs index a0a66d4e60..088f526df8 100644 --- a/src/Refactorings/CSharp/Refactorings/ExpandInitializerRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ExpandInitializerRefactoring.cs @@ -93,7 +93,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In { var objectCreationExpression = (ObjectCreationExpressionSyntax)initializer.Parent; - if (objectCreationExpression.Type != null) + if (objectCreationExpression.Type is not null) { ExpressionSyntax expression = initializer.Expressions[0]; @@ -156,7 +156,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In IParameterSymbol parameter = methodSymbol.Parameters.SingleOrDefault(shouldThrow: false); - if (parameter != null) + if (parameter is not null) { TypeInfo typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken); @@ -189,7 +189,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In { IParameterSymbol parameter = propertySymbol.Parameters.SingleOrDefault(shouldThrow: false); - if (parameter != null) + if (parameter is not null) { TypeInfo typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken); @@ -220,7 +220,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In ObjectCreationExpressionSyntax newObjectCreationExpression = objectCreationExpression.WithInitializer(null); - if (newObjectCreationExpression.ArgumentList == null) + if (newObjectCreationExpression.ArgumentList is null) { TypeSyntax type = newObjectCreationExpression.Type; diff --git a/src/Refactorings/CSharp/Refactorings/ExpandPositionalConstructorRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ExpandPositionalConstructorRefactoring.cs index 2350f67f84..3a85ba0533 100644 --- a/src/Refactorings/CSharp/Refactorings/ExpandPositionalConstructorRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ExpandPositionalConstructorRefactoring.cs @@ -48,7 +48,7 @@ public static void ComputeRefactoring(RefactoringContext context, RecordDeclarat ImmutableHashSet basePropertyNames = ImmutableHashSet.Empty; - if (baseType != null) + if (baseType is not null) { basePropertyNames = baseType .ArgumentList? @@ -125,7 +125,7 @@ public static void ComputeRefactoring(RefactoringContext context, RecordDeclarat .WithParameterList(null) .WithSemicolonToken(default); - if (baseType != null) + if (baseType is not null) { SimpleBaseTypeSyntax newBaseType = SimpleBaseType(baseType.Type).WithTrailingTrivia(baseType.GetTrailingTrivia()); diff --git a/src/Refactorings/CSharp/Refactorings/ExtractCondition/ExtractConditionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ExtractCondition/ExtractConditionRefactoring.cs index 387c724411..62e208869a 100644 --- a/src/Refactorings/CSharp/Refactorings/ExtractCondition/ExtractConditionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ExtractCondition/ExtractConditionRefactoring.cs @@ -20,7 +20,7 @@ internal static void ComputeRefactoring(RefactoringContext context, ExpressionCh BinaryExpressionSyntax condition = GetCondition(binaryExpression); - if (condition == null) + if (condition is null) return; SyntaxNode parent = condition.Parent; @@ -76,7 +76,7 @@ public static void ComputeRefactoring(RefactoringContext context, ExpressionSynt { SyntaxNode parent = expression.Parent; - if (parent == null) + if (parent is null) return; SyntaxKind kind = parent.Kind(); @@ -86,7 +86,7 @@ public static void ComputeRefactoring(RefactoringContext context, ExpressionSynt BinaryExpressionSyntax binaryExpression = GetCondition((BinaryExpressionSyntax)parent); - if (binaryExpression == null) + if (binaryExpression is null) return; parent = binaryExpression.Parent; @@ -147,7 +147,7 @@ private static BinaryExpressionSyntax GetCondition(BinaryExpressionSyntax binary { SyntaxKind kind = binaryExpression.Kind(); - for (SyntaxNode parent = binaryExpression.Parent; parent != null; parent = parent.Parent) + for (SyntaxNode parent = binaryExpression.Parent; parent is not null; parent = parent.Parent) { SyntaxKind parentKind = parent.Kind(); diff --git a/src/Refactorings/CSharp/Refactorings/ExtractEventHandlerMethodRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ExtractEventHandlerMethodRefactoring.cs index cb1205daa7..bb29d7bdb4 100644 --- a/src/Refactorings/CSharp/Refactorings/ExtractEventHandlerMethodRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ExtractEventHandlerMethodRefactoring.cs @@ -39,7 +39,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Par MemberDeclarationSyntax memberDeclaration = assignmentExpression.FirstAncestor(); - if (memberDeclaration == null) + if (memberDeclaration is null) return; Debug.Assert(memberDeclaration.Parent is TypeDeclarationSyntax); diff --git a/src/Refactorings/CSharp/Refactorings/FieldDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/FieldDeclarationRefactoring.cs index a8b91d6369..8d51a54e29 100644 --- a/src/Refactorings/CSharp/Refactorings/FieldDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/FieldDeclarationRefactoring.cs @@ -32,7 +32,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Fi .Variables .FirstOrDefault(f => context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(f.Identifier)); - if (variableDeclarator != null) + if (variableDeclarator is not null) { context.RegisterRefactoring( "Inline constant", diff --git a/src/Refactorings/CSharp/Refactorings/ForEachStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ForEachStatementRefactoring.cs index 60af469228..bb586584b1 100644 --- a/src/Refactorings/CSharp/Refactorings/ForEachStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ForEachStatementRefactoring.cs @@ -132,7 +132,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Fo { TypeSyntax type = forEachStatement.Type; - if (type == null) + if (type is null) return; SyntaxToken identifier = forEachStatement.Identifier; @@ -156,7 +156,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Fo forEachStatement.SpanStart, cancellationToken: context.CancellationToken); - if (newName == null) + if (newName is null) return; ISymbol symbol = semanticModel.GetDeclaredSymbol(forEachStatement, context.CancellationToken); diff --git a/src/Refactorings/CSharp/Refactorings/GenerateAllEnumValuesRefactoring.cs b/src/Refactorings/CSharp/Refactorings/GenerateAllEnumValuesRefactoring.cs index 059377878e..25b4b62e17 100644 --- a/src/Refactorings/CSharp/Refactorings/GenerateAllEnumValuesRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/GenerateAllEnumValuesRefactoring.cs @@ -26,7 +26,7 @@ internal static class GenerateAllEnumValuesRefactoring if (!members.Any()) return; - if (members.All(f => f.EqualsValue?.Value == null)) + if (members.All(f => f.EqualsValue?.Value is null)) return; INamedTypeSymbol enumSymbol = semanticModel.GetDeclaredSymbol(enumDeclaration, context.CancellationToken); @@ -150,7 +150,7 @@ EnumMemberDeclarationSyntax CreateNewMember(EnumMemberDeclarationSyntax enumMemb Token(TriviaList(ElasticSpace), SyntaxKind.EqualsToken, TriviaList(ElasticSpace)), NumericLiteralExpression(value, numericType)); - if (enumMember.EqualsValue != null) + if (enumMember.EqualsValue is not null) equalsValue = equalsValue.WithTriviaFrom(enumMember.EqualsValue); return enumMember.WithEqualsValue(equalsValue); diff --git a/src/Refactorings/CSharp/Refactorings/GenerateEnumMemberRefactoring.cs b/src/Refactorings/CSharp/Refactorings/GenerateEnumMemberRefactoring.cs index ec9da00425..3c148845e3 100644 --- a/src/Refactorings/CSharp/Refactorings/GenerateEnumMemberRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/GenerateEnumMemberRefactoring.cs @@ -87,7 +87,7 @@ private static ImmutableArray GetConstantValues(INamedTypeSymbol enumSymb { EqualsValueClauseSyntax equalsValue = null; - if (value != null) + if (value is not null) equalsValue = EqualsValueClause(CSharpFactory.NumericLiteralExpression(value.Value, enumSymbol.EnumUnderlyingType.SpecialType)); string name = NameGenerator.Default.EnsureUniqueEnumMemberName(DefaultNames.EnumMember, enumSymbol); diff --git a/src/Refactorings/CSharp/Refactorings/GenerateEnumValuesRefactoring.cs b/src/Refactorings/CSharp/Refactorings/GenerateEnumValuesRefactoring.cs index 1819bb895a..16486b5e2f 100644 --- a/src/Refactorings/CSharp/Refactorings/GenerateEnumValuesRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/GenerateEnumValuesRefactoring.cs @@ -28,7 +28,7 @@ internal static class GenerateEnumValuesRefactoring SeparatedSyntaxList members = enumDeclaration.Members; - if (!members.Any(f => f.EqualsValue == null)) + if (!members.Any(f => f.EqualsValue is null)) return; ImmutableArray values = GetExplicitValues(enumDeclaration, semanticModel, context.CancellationToken); @@ -48,7 +48,7 @@ internal static class GenerateEnumValuesRefactoring ct => RefactorAsync(document, enumDeclaration, enumSymbol, values, startFromHighestExistingValue: false, cancellationToken: ct), RefactoringDescriptors.GenerateEnumValues); - if (members.Any(f => f.EqualsValue != null)) + if (members.Any(f => f.EqualsValue is not null)) { Optional optional2 = FlagsUtility.Instance.GetUniquePowerOfTwo(values, startFromHighestExistingValue: true); @@ -78,7 +78,7 @@ internal static class GenerateEnumValuesRefactoring for (int i = 0; i < members.Count; i++) { - if (members[i].EqualsValue == null) + if (members[i].EqualsValue is null) { Optional optional = FlagsUtility.Instance.GetUniquePowerOfTwo(valuesList, startFromHighestExistingValue); @@ -118,7 +118,7 @@ internal static class GenerateEnumValuesRefactoring { ExpressionSyntax value = member.EqualsValue?.Value; - if (value != null) + if (value is not null) { IFieldSymbol fieldSymbol = semanticModel.GetDeclaredSymbol(member, cancellationToken); diff --git a/src/Refactorings/CSharp/Refactorings/GenerateOnEventMethodRefactoring.cs b/src/Refactorings/CSharp/Refactorings/GenerateOnEventMethodRefactoring.cs index 8a16af1667..8041684499 100644 --- a/src/Refactorings/CSharp/Refactorings/GenerateOnEventMethodRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/GenerateOnEventMethodRefactoring.cs @@ -22,7 +22,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Eve VariableDeclarationSyntax variableDeclaration = eventFieldDeclaration.Declaration; - if (variableDeclaration == null) + if (variableDeclaration is null) return; SemanticModel semanticModel = null; @@ -41,7 +41,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Eve INamedTypeSymbol containingType = eventSymbol.ContainingType; - if (containingType == null) + if (containingType is null) return; if (eventSymbol.Type is not INamedTypeSymbol eventHandlerType) @@ -49,7 +49,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Eve ITypeSymbol eventArgsSymbol = GetEventArgsSymbol(eventHandlerType, semanticModel); - if (eventArgsSymbol == null) + if (eventArgsSymbol is null) continue; string methodName = "On" + eventSymbol.Name; diff --git a/src/Refactorings/CSharp/Refactorings/GeneratePropertyForDebuggerDisplayAttributeRefactoring.cs b/src/Refactorings/CSharp/Refactorings/GeneratePropertyForDebuggerDisplayAttributeRefactoring.cs index 59126a3379..c104ba1a33 100644 --- a/src/Refactorings/CSharp/Refactorings/GeneratePropertyForDebuggerDisplayAttributeRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/GeneratePropertyForDebuggerDisplayAttributeRefactoring.cs @@ -17,7 +17,7 @@ internal static class GeneratePropertyForDebuggerDisplayAttributeRefactoring { public static async Task ComputeRefactoringAsync(RefactoringContext context, AttributeSyntax attribute) { - if (attribute.ArgumentList?.Arguments.Count(f => f.NameEquals == null) != 1) + if (attribute.ArgumentList?.Arguments.Count(f => f.NameEquals is null) != 1) return; if (!attribute.IsParentKind(SyntaxKind.AttributeList)) @@ -36,7 +36,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Att .Value? .ToString(); - if (value == null) + if (value is null) return; if (string.Equals(value, $"{{{DefaultNames.DebuggerDisplayPropertyName},nq}}", StringComparison.Ordinal)) diff --git a/src/Refactorings/CSharp/Refactorings/IdentifierNameRefactoring.cs b/src/Refactorings/CSharp/Refactorings/IdentifierNameRefactoring.cs index dd0d8fbd93..2e838c7c2d 100644 --- a/src/Refactorings/CSharp/Refactorings/IdentifierNameRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/IdentifierNameRefactoring.cs @@ -43,7 +43,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Id PropertyDeclarationSyntax propertyDeclaration = identifierName.FirstAncestor(); - if (propertyDeclaration == null) + if (propertyDeclaration is null) return; SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -55,7 +55,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Id IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken); - if (propertySymbol == null) + if (propertySymbol is null) return; if (fieldSymbol.IsStatic != propertySymbol.IsStatic) diff --git a/src/Refactorings/CSharp/Refactorings/ImplementCustomEnumeratorRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ImplementCustomEnumeratorRefactoring.cs index b4e52c42fb..39da9676cf 100644 --- a/src/Refactorings/CSharp/Refactorings/ImplementCustomEnumeratorRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ImplementCustomEnumeratorRefactoring.cs @@ -27,7 +27,7 @@ internal static class ImplementCustomEnumeratorRefactoring INamedTypeSymbol ienumerableOfT = symbol.Interfaces.FirstOrDefault(f => f.OriginalDefinition.HasMetadataName(MetadataNames.System_Collections_Generic_IEnumerable_T)); - if (ienumerableOfT == null) + if (ienumerableOfT is null) return; INamedTypeSymbol enumerator = symbol.FindTypeMember( @@ -37,7 +37,7 @@ internal static class ImplementCustomEnumeratorRefactoring && f.Arity == 0, includeBaseTypes: true); - if (enumerator != null) + if (enumerator is not null) return; context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/ImplementIEquatableOfTRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ImplementIEquatableOfTRefactoring.cs index d1d3209366..380b3afcb2 100644 --- a/src/Refactorings/CSharp/Refactorings/ImplementIEquatableOfTRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ImplementIEquatableOfTRefactoring.cs @@ -26,12 +26,12 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Cla BaseListSyntax baseList = classDeclaration.BaseList; - if (baseList != null) + if (baseList is not null) span = TextSpan.FromBounds(span.Start, baseList.Span.End); TypeParameterListSyntax typeParameterList = classDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) span = TextSpan.FromBounds(span.Start, typeParameterList.Span.End); if (!span.Contains(context.Span)) @@ -58,7 +58,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Cla INamedTypeSymbol equatableSymbol = semanticModel.GetTypeByMetadataName("System.IEquatable`1"); - if (equatableSymbol == null) + if (equatableSymbol is null) return; equatableSymbol = equatableSymbol.Construct(classSymbol); @@ -80,12 +80,12 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Str BaseListSyntax baseList = structDeclaration.BaseList; - if (baseList != null) + if (baseList is not null) span = TextSpan.FromBounds(span.Start, baseList.Span.End); TypeParameterListSyntax typeParameterList = structDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) span = TextSpan.FromBounds(span.Start, typeParameterList.Span.End); if (!span.Contains(context.Span)) @@ -109,7 +109,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Str INamedTypeSymbol equatableSymbol = semanticModel.GetTypeByMetadataName("System.IEquatable`1"); - if (equatableSymbol == null) + if (equatableSymbol is null) return; equatableSymbol = equatableSymbol.Construct(typeSymbol); @@ -150,13 +150,13 @@ private static ClassDeclarationSyntax AddBaseType(ClassDeclarationSyntax classDe { BaseListSyntax baseList = classDeclaration.BaseList; - if (baseList == null) + if (baseList is null) { baseList = BaseList(baseType); TypeParameterListSyntax typeParameterList = classDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { return classDeclaration .WithTypeParameterList(typeParameterList.WithoutTrailingTrivia()) @@ -177,7 +177,7 @@ private static ClassDeclarationSyntax AddBaseType(ClassDeclarationSyntax classDe BaseTypeSyntax lastType = types.LastOrDefault(); - if (lastType == null + if (lastType is null || (types.Count == 1 && types[0].IsMissing)) { SyntaxToken colonToken = baseList.ColonToken; @@ -228,13 +228,13 @@ private static StructDeclarationSyntax AddBaseType(StructDeclarationSyntax struc { BaseListSyntax baseList = structDeclaration.BaseList; - if (baseList == null) + if (baseList is null) { baseList = BaseList(baseType); TypeParameterListSyntax typeParameterList = structDeclaration.TypeParameterList; - if (typeParameterList != null) + if (typeParameterList is not null) { return structDeclaration .WithTypeParameterList(typeParameterList.WithoutTrailingTrivia()) @@ -255,7 +255,7 @@ private static StructDeclarationSyntax AddBaseType(StructDeclarationSyntax struc BaseTypeSyntax lastType = types.LastOrDefault(); - if (lastType == null + if (lastType is null || (types.Count == 1 && types[0].IsMissing)) { SyntaxToken colonToken = baseList.ColonToken; diff --git a/src/Refactorings/CSharp/Refactorings/InitializeFieldFromConstructorRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InitializeFieldFromConstructorRefactoring.cs index f7afa044b5..31984d4d4d 100644 --- a/src/Refactorings/CSharp/Refactorings/InitializeFieldFromConstructorRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InitializeFieldFromConstructorRefactoring.cs @@ -23,7 +23,7 @@ public static void ComputeRefactoring(RefactoringContext context, FieldDeclarati SeparatedSyntaxList variables = fieldDeclaration.Declaration.Variables; - if (variables.Any(f => f.Initializer != null)) + if (variables.Any(f => f.Initializer is not null)) return; context.RegisterRefactoring( @@ -43,7 +43,7 @@ public static void ComputeRefactoring(RefactoringContext context, MemberDeclarat var fieldDeclaration = (FieldDeclarationSyntax)selectedMember; - if (fieldDeclaration.Declaration.Variables.Any(f => f.Initializer != null)) + if (fieldDeclaration.Declaration.Variables.Any(f => f.Initializer is not null)) return; if (!CanRefactor(fieldDeclaration)) @@ -67,7 +67,7 @@ private static string GetTitle(bool isSingle) public static void ComputeRefactoring(RefactoringContext context, VariableDeclaratorSyntax variableDeclarator) { - if (variableDeclarator.Initializer != null) + if (variableDeclarator.Initializer is not null) return; if (variableDeclarator.Parent is not VariableDeclarationSyntax variableDeclaration) @@ -151,12 +151,12 @@ private static bool CanRefactor(FieldDeclarationSyntax fieldDeclaration) ParameterListSyntax parameterList = constructorDeclaration.ParameterList; - if (parameterList == null) + if (parameterList is null) continue; BlockSyntax body = constructorDeclaration.Body; - if (body == null) + if (body is null) continue; SeparatedSyntaxList parameters = parameterList.Parameters; @@ -168,7 +168,7 @@ private static bool CanRefactor(FieldDeclarationSyntax fieldDeclaration) SeparatedSyntaxList arguments = argumentList?.Arguments ?? default; bool addToInitializer = initializer?.Kind() == SyntaxKind.ThisConstructorInitializer - && argumentList != null; + && argumentList is not null; SyntaxList statements = body.Statements; @@ -235,7 +235,7 @@ private static bool CanRefactor(FieldDeclarationSyntax fieldDeclaration) if (!isConflict) return name; - if (reservedNames == null) + if (reservedNames is null) reservedNames = new HashSet(); foreach (ParameterSyntax parameter in parameters) diff --git a/src/Refactorings/CSharp/Refactorings/InitializeLocalVariableWithDefaultValueRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InitializeLocalVariableWithDefaultValueRefactoring.cs index 615b890de4..0002f310b9 100644 --- a/src/Refactorings/CSharp/Refactorings/InitializeLocalVariableWithDefaultValueRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InitializeLocalVariableWithDefaultValueRefactoring.cs @@ -16,7 +16,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Loc { VariableDeclarationSyntax declaration = localDeclaration.Declaration; - if (declaration == null) + if (declaration is null) return; SeparatedSyntaxList variables = declaration.Variables; diff --git a/src/Refactorings/CSharp/Refactorings/InlineConstantDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InlineConstantDeclarationRefactoring.cs index 6b6f0fbae8..da04009183 100644 --- a/src/Refactorings/CSharp/Refactorings/InlineConstantDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InlineConstantDeclarationRefactoring.cs @@ -53,7 +53,7 @@ internal static class InlineConstantDeclarationRefactoring SyntaxNode nodeToRemove = newRoot.GetAnnotatedNodes(_removeAnnotation).FirstOrDefault(); - if (nodeToRemove != null) + if (nodeToRemove is not null) newRoot = newRoot.RemoveNode(nodeToRemove); newDocuments.Add(new KeyValuePair(grouping.Key.Id, newRoot)); diff --git a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineAnalyzer.cs b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineAnalyzer.cs index c94e89685d..7cf133d769 100644 --- a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineAnalyzer.cs +++ b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineAnalyzer.cs @@ -30,10 +30,10 @@ public async Task ComputeRefactoringsAsync(RefactoringContext context, TNode nod TDeclaration declaration = await GetMemberDeclarationAsync(symbol, context.CancellationToken).ConfigureAwait(false); - if (declaration == null) + if (declaration is null) return; - for (SyntaxNode parent = node.Parent; parent != null; parent = parent.Parent) + for (SyntaxNode parent = node.Parent; parent is not null; parent = parent.Parent) { if (object.ReferenceEquals(declaration, parent)) return; @@ -43,7 +43,7 @@ public async Task ComputeRefactoringsAsync(RefactoringContext context, TNode nod SyntaxNode nodeIncludingConditionalAccess = node.WalkUp(f => f.IsKind(SyntaxKind.ConditionalAccessExpression)); - if (expression != null + if (expression is not null || (statements.Any() && nodeIncludingConditionalAccess.IsParentKind(SyntaxKind.ExpressionStatement))) { ImmutableArray parameterInfos = GetParameterInfos(node, symbol); @@ -60,7 +60,7 @@ public async Task ComputeRefactoringsAsync(RefactoringContext context, TNode nod Document document = context.Solution.GetDocument(declaration.SyntaxTree); // https://github.com/dotnet/roslyn/issues/5260 - if (document == null) + if (document is null) return; declarationSemanticModel = await document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); @@ -70,7 +70,7 @@ public async Task ComputeRefactoringsAsync(RefactoringContext context, TNode nod string title = CSharpFacts.GetTitle(declaration); - if (expression != null) + if (expression is not null) { context.RegisterRefactoring($"Inline {title}", ct => refactoring.InlineAsync(nodeIncludingConditionalAccess, expression, ct), GetDescriptor()); diff --git a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineMethodAnalyzer.cs b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineMethodAnalyzer.cs index d028c5de92..06117a7591 100644 --- a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineMethodAnalyzer.cs +++ b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineMethodAnalyzer.cs @@ -19,12 +19,12 @@ protected override bool ValidateNode(InvocationExpressionSyntax node, TextSpan s { ExpressionSyntax expression = node.Expression; - if (expression == null) + if (expression is null) return false; ArgumentListSyntax argumentList = node.ArgumentList; - if (argumentList == null) + if (argumentList is null) return false; if (expression.Kind() == SyntaxKind.SimpleMemberAccessExpression) @@ -89,7 +89,7 @@ protected override bool ValidateNode(InvocationExpressionSyntax node, TextSpan s SyntaxNode node = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); if ((node is MethodDeclarationSyntax methodDeclaration) - && methodDeclaration.BodyOrExpressionBody() != null) + && methodDeclaration.BodyOrExpressionBody() is not null) { return methodDeclaration; } @@ -114,7 +114,7 @@ protected override bool ValidateNode(InvocationExpressionSyntax node, TextSpan s { IParameterSymbol parameterSymbol = DetermineParameterHelper.DetermineParameter(argument, arguments, parameters); - if (parameterSymbol != null) + if (parameterSymbol is not null) { var parameterInfo = new ParameterInfo(parameterSymbol, argument.Expression); @@ -128,7 +128,7 @@ protected override bool ValidateNode(InvocationExpressionSyntax node, TextSpan s foreach (IParameterSymbol parameterSymbol in parameters) { - if (parameterInfos == null + if (parameterInfos is null || parameterInfos.FindIndex(f => SymbolEqualityComparer.Default.Equals(f.ParameterSymbol, parameterSymbol)) == -1) { if (parameterSymbol.HasExplicitDefaultValue) @@ -163,7 +163,7 @@ protected override bool ValidateNode(InvocationExpressionSyntax node, TextSpan s (parameterInfos ??= new List()).Add(parameterInfo); } - return (parameterInfos != null) + return (parameterInfos is not null) ? parameterInfos.ToImmutableArray() : ImmutableArray.Empty; } @@ -172,7 +172,7 @@ protected override (ExpressionSyntax expression, SyntaxList sta { BlockSyntax body = declaration.Body; - if (body == null) + if (body is null) return (declaration.ExpressionBody?.Expression, default(SyntaxList)); SyntaxList statements = body.Statements; diff --git a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlinePropertyAnalyzer.cs b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlinePropertyAnalyzer.cs index 9a9635639e..654bd70b43 100644 --- a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlinePropertyAnalyzer.cs +++ b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlinePropertyAnalyzer.cs @@ -77,7 +77,7 @@ protected override async Task GetMemberDeclarationAsy { SyntaxReference syntaxReference = symbol.DeclaringSyntaxReferences.FirstOrDefault(); - if (syntaxReference != null) + if (syntaxReference is not null) { SyntaxNode node = await syntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); @@ -97,7 +97,7 @@ protected override (ExpressionSyntax expression, SyntaxList sta { ArrowExpressionClauseSyntax expressionBody = declaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) return (expressionBody.Expression, default(SyntaxList)); AccessorDeclarationSyntax accessor = declaration.AccessorList?.Accessors.SingleOrDefault(shouldThrow: false); @@ -107,7 +107,7 @@ protected override (ExpressionSyntax expression, SyntaxList sta expressionBody = accessor.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) return (expressionBody.Expression, default(SyntaxList)); switch (accessor.Body?.Statements.SingleOrDefault(shouldThrow: false)) diff --git a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineRefactoring.cs index 518a086bc3..f4a85bc98a 100644 --- a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineRefactoring.cs @@ -218,7 +218,7 @@ private StatementSyntax[] RewriteStatements(SyntaxList statemen ISymbol symbol = DeclarationSemanticModel.GetSymbol(identifierName, CancellationToken); - if (symbol != null) + if (symbol is not null) { if (symbol is IParameterSymbol parameterSymbol) { @@ -228,7 +228,7 @@ private StatementSyntax[] RewriteStatements(SyntaxList statemen { ExpressionSyntax expression = parameterInfo.Expression; - if (expression == null + if (expression is null && parameterInfo.ParameterSymbol.HasExplicitDefaultValue) { expression = parameterInfo.ParameterSymbol.GetDefaultValueMinimalSyntax(InvocationSemanticModel, Node.SpanStart); @@ -253,7 +253,7 @@ private StatementSyntax[] RewriteStatements(SyntaxList statemen { INamedTypeSymbol containingType = symbol.ContainingType; - if (containingType != null) + if (containingType is not null) { if (!NodeEnclosingType .BaseTypesAndSelf() @@ -268,14 +268,14 @@ private StatementSyntax[] RewriteStatements(SyntaxList statemen } } - if (symbolMap != null + if (symbolMap is not null && symbolMap.TryGetValue(symbol, out string name)) { replacementMap.Add(identifierName, IdentifierName(name)); } } } - else if (symbolMap != null) + else if (symbolMap is not null) { switch (kind) { @@ -288,9 +288,9 @@ private StatementSyntax[] RewriteStatements(SyntaxList statemen { ISymbol symbol = DeclarationSemanticModel.GetDeclaredSymbol(descendant, CancellationToken); - Debug.Assert(symbol != null || (descendant as ForEachVariableStatementSyntax)?.Variable?.Kind() == SyntaxKind.TupleExpression, kind.ToString()); + Debug.Assert(symbol is not null || (descendant as ForEachVariableStatementSyntax)?.Variable?.Kind() == SyntaxKind.TupleExpression, kind.ToString()); - if (symbol != null + if (symbol is not null && symbolMap.TryGetValue(symbol, out string name)) { replacementMap.Add(descendant, name); @@ -361,7 +361,7 @@ static bool ParameterEquals(in ParameterInfo parameterInfo, IParameterSymbol par (symbols ??= new List()).Add(symbol); } - if (symbols == null) + if (symbols is null) return null; reservedNames.UnionWith(declarationSymbols.Select(f => f.Name)); diff --git a/src/Refactorings/CSharp/Refactorings/IntroduceAndInitialize/IntroduceAndInitializeRefactoring.cs b/src/Refactorings/CSharp/Refactorings/IntroduceAndInitialize/IntroduceAndInitializeRefactoring.cs index 7185aee4e9..6b62028cc4 100644 --- a/src/Refactorings/CSharp/Refactorings/IntroduceAndInitialize/IntroduceAndInitializeRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/IntroduceAndInitialize/IntroduceAndInitializeRefactoring.cs @@ -143,11 +143,11 @@ private IEnumerable CreateDeclarations(ConstructorDecla { IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(constructor, cancellationToken); - if (methodSymbol != null) + if (methodSymbol is not null) { INamedTypeSymbol containingType = methodSymbol.ContainingType; - if (containingType != null) + if (containingType is not null) { ImmutableArray members = containingType.GetMembers(); @@ -162,7 +162,7 @@ private IEnumerable CreateDeclarations(ConstructorDecla private static bool IsValid(ParameterSyntax parameter) { - if (parameter.Type == null) + if (parameter.Type is null) return false; if (parameter.Identifier.IsMissing) @@ -179,7 +179,7 @@ private static bool IsValid(ParameterSyntax parameter) ArgumentListSyntax argumentList = constructorDeclaration.Initializer?.ArgumentList; - if (argumentList != null) + if (argumentList is not null) { foreach (ArgumentSyntax argument in argumentList.Arguments) { diff --git a/src/Refactorings/CSharp/Refactorings/IntroduceConstructorRefactoring.cs b/src/Refactorings/CSharp/Refactorings/IntroduceConstructorRefactoring.cs index a37e75e525..62248180f0 100644 --- a/src/Refactorings/CSharp/Refactorings/IntroduceConstructorRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/IntroduceConstructorRefactoring.cs @@ -45,7 +45,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me { if (context.Span.Contains(member.Span)) { - if (semanticModel == null) + if (semanticModel is null) semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); if (CanBeAssignedFromConstructor(member, context.Span, semanticModel, context.CancellationToken)) @@ -56,7 +56,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me } } - if (members == null) + if (members is null) return; context.RegisterRefactoring( @@ -89,7 +89,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me { ISymbol symbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); - if (symbol == null) + if (symbol is null) return false; if (symbol.IsStatic) @@ -100,18 +100,18 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { ExpressionSyntax expression = expressionBody?.Expression; - if (expression != null) - return GetBackingFieldSymbol(expression, semanticModel, cancellationToken) != null; + if (expression is not null) + return GetBackingFieldSymbol(expression, semanticModel, cancellationToken) is not null; } else { AccessorDeclarationSyntax getter = propertyDeclaration.Getter(); - if (getter != null) + if (getter is not null) return CanPropertyBeAssignedFromConstructor(getter, semanticModel, cancellationToken); } @@ -125,19 +125,19 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me { BlockSyntax body = getter.Body; - if (body != null) + if (body is not null) { StatementSyntax statement = body.Statements.SingleOrDefault(shouldThrow: false); - if (statement != null) - return GetBackingFieldSymbol(statement, semanticModel, cancellationToken) != null; + if (statement is not null) + return GetBackingFieldSymbol(statement, semanticModel, cancellationToken) is not null; } else { ExpressionSyntax expression = getter.ExpressionBody?.Expression; - return expression != null - && GetBackingFieldSymbol(expression, semanticModel, cancellationToken) != null; + return expression is not null + && GetBackingFieldSymbol(expression, semanticModel, cancellationToken) is not null; } return true; @@ -154,7 +154,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me .Variables .SingleOrDefault(shouldThrow: false); - if (variable == null) + if (variable is null) return false; MemberDeclarationListInfo info = SyntaxInfo.MemberDeclarationListInfo(GetContainingDeclaration(fieldDeclaration)); @@ -164,7 +164,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me ISymbol symbol = semanticModel.GetDeclaredSymbol(variable, cancellationToken); - if (symbol == null) + if (symbol is null) return false; if (symbol.IsStatic) @@ -196,18 +196,18 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { ExpressionSyntax expression = expressionBody.Expression; - return expression != null + return expression is not null && SymbolEqualityComparer.Default.Equals(symbol, GetBackingFieldSymbol(expression, semanticModel, cancellationToken)); } else { AccessorDeclarationSyntax getter = propertyDeclaration.Getter(); - if (getter != null) + if (getter is not null) return IsBackingField(getter, symbol, semanticModel, cancellationToken); } @@ -218,18 +218,18 @@ private static bool IsBackingField(AccessorDeclarationSyntax getter, ISymbol sym { BlockSyntax body = getter.Body; - if (body != null) + if (body is not null) { StatementSyntax statement = body.Statements.SingleOrDefault(shouldThrow: false); - if (statement != null) + if (statement is not null) return SymbolEqualityComparer.Default.Equals(symbol, GetBackingFieldSymbol(statement, semanticModel, cancellationToken)); } else { ExpressionSyntax expression = getter.ExpressionBody?.Expression; - return expression != null + return expression is not null && SymbolEqualityComparer.Default.Equals(symbol, GetBackingFieldSymbol(expression, semanticModel, cancellationToken)); } @@ -245,7 +245,7 @@ private static bool IsBackingField(AccessorDeclarationSyntax getter, ISymbol sym { ExpressionSyntax expression = returnStatement.Expression; - if (expression != null) + if (expression is not null) return GetBackingFieldSymbol(expression, semanticModel, cancellationToken); } @@ -398,7 +398,7 @@ private static SyntaxToken GetPropertyIdentifier(PropertyDeclarationSyntax prope { ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - if (expressionBody != null) + if (expressionBody is not null) { ExpressionSyntax expression = expressionBody.Expression; @@ -409,11 +409,11 @@ private static SyntaxToken GetPropertyIdentifier(PropertyDeclarationSyntax prope { AccessorDeclarationSyntax getter = propertyDeclaration.Getter(); - if (getter != null) + if (getter is not null) { BlockSyntax getterBody = getter.Body; - if (getterBody != null) + if (getterBody is not null) { var returnStatement = (ReturnStatementSyntax)getterBody.Statements[0]; @@ -423,7 +423,7 @@ private static SyntaxToken GetPropertyIdentifier(PropertyDeclarationSyntax prope { ArrowExpressionClauseSyntax getterExpressionBody = getter.ExpressionBody; - if (getterExpressionBody != null) + if (getterExpressionBody is not null) return GetIdentifier(getterExpressionBody.Expression); } } diff --git a/src/Refactorings/CSharp/Refactorings/InvertBinaryExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InvertBinaryExpressionRefactoring.cs index 298fa8489d..c5961a1301 100644 --- a/src/Refactorings/CSharp/Refactorings/InvertBinaryExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InvertBinaryExpressionRefactoring.cs @@ -18,7 +18,7 @@ public static void ComputeRefactoring(RefactoringContext context, BinaryExpressi binaryExpression = GetBinaryExpression(binaryExpression, context.Span); - if (binaryExpression == null) + if (binaryExpression is null) return; context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/InvertIfRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InvertIfRefactoring.cs index bebfbee67a..bdf38ad0d9 100644 --- a/src/Refactorings/CSharp/Refactorings/InvertIfRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InvertIfRefactoring.cs @@ -32,7 +32,7 @@ public static void ComputeRefactoring(RefactoringContext context, IfStatementSyn ElseClauseSyntax elseClause = ifStatement.Else; - if (elseClause != null) + if (elseClause is not null) { if (context.IsRefactoringEnabled(RefactoringDescriptors.InvertIfElse)) { @@ -223,7 +223,7 @@ bool IsLastStatementRedundant() { case SyntaxKind.ReturnStatement: { - if (((ReturnStatementSyntax)jumpStatement).Expression == null + if (((ReturnStatementSyntax)jumpStatement).Expression is null && RemoveRedundantStatementAnalysis.IsFixable(lastStatement, SyntaxKind.ReturnStatement)) { return true; @@ -269,7 +269,7 @@ public StatementSyntax NextStatement public bool Success { - get { return IfStatement != null; } + get { return IfStatement is not null; } } public static InvertIfAnalysis Create( @@ -280,7 +280,7 @@ public bool Success { statement = block.Statements.LastOrDefault(); - if (statement == null) + if (statement is null) return default; } @@ -294,7 +294,7 @@ public bool Success FindLastStatement(); - if (lastStatement == null) + if (lastStatement is null) return default; return new InvertIfAnalysis(ifStatement, lastStatement, statement); diff --git a/src/Refactorings/CSharp/Refactorings/InvertLinqMethodCallRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InvertLinqMethodCallRefactoring.cs index 4dc0c5bec0..1aa5c29725 100644 --- a/src/Refactorings/CSharp/Refactorings/InvertLinqMethodCallRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InvertLinqMethodCallRefactoring.cs @@ -25,7 +25,7 @@ public static void ComputeRefactoring(RefactoringContext context, InvocationExpr { IMethodSymbol methodSymbol = semanticModel.GetExtensionMethodInfo(invocation, context.CancellationToken).Symbol; - if (methodSymbol == null) + if (methodSymbol is null) return false; if (!SymbolUtility.IsLinqExtensionOfIEnumerableOfTWithPredicate(methodSymbol, fromMethodName)) @@ -33,7 +33,7 @@ public static void ComputeRefactoring(RefactoringContext context, InvocationExpr ExpressionSyntax expression = GetExpression(invocation); - if (expression == null) + if (expression is null) return false; context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/InvocationExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InvocationExpressionRefactoring.cs index 01d40f63cd..6175f6ad55 100644 --- a/src/Refactorings/CSharp/Refactorings/InvocationExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InvocationExpressionRefactoring.cs @@ -21,8 +21,8 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In { ExpressionSyntax expression = invocationExpression.Expression; - if (expression != null - && invocationExpression.ArgumentList != null) + if (expression is not null + && invocationExpression.ArgumentList is not null) { if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) && ((MemberAccessExpressionSyntax)expression).Name?.Span.Contains(context.Span) == true) diff --git a/src/Refactorings/CSharp/Refactorings/LocalFunctionStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/LocalFunctionStatementRefactoring.cs index 3ede6cfbee..b8e4b94591 100644 --- a/src/Refactorings/CSharp/Refactorings/LocalFunctionStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/LocalFunctionStatementRefactoring.cs @@ -14,7 +14,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Lo { BlockSyntax body = localFunctionStatement.Body; - if (body != null) + if (body is not null) { if (body.OpenBraceToken.Span.Contains(context.Span) || body.CloseBraceToken.Span.Contains(context.Span)) diff --git a/src/Refactorings/CSharp/Refactorings/LockStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/LockStatementRefactoring.cs index 8430e535cd..f14c49c6e3 100644 --- a/src/Refactorings/CSharp/Refactorings/LockStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/LockStatementRefactoring.cs @@ -14,7 +14,7 @@ public static void ComputeRefactorings(RefactoringContext context, LockStatement { ExpressionSyntax expression = lockStatement.Expression; - if (expression != null) + if (expression is not null) { if (expression.IsMissing || expression.IsKind(SyntaxKind.ThisExpression)) { diff --git a/src/Refactorings/CSharp/Refactorings/MakeMemberAbstract/MakeIndexerAbstractRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MakeMemberAbstract/MakeIndexerAbstractRefactoring.cs index 2a343f1d4b..e739fa7d5b 100644 --- a/src/Refactorings/CSharp/Refactorings/MakeMemberAbstract/MakeIndexerAbstractRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MakeMemberAbstract/MakeIndexerAbstractRefactoring.cs @@ -35,7 +35,7 @@ public static void ComputeRefactoring(RefactoringContext context, IndexerDeclara { AccessorListSyntax accessorList = AccessorList(); - if (indexerDeclaration.ExpressionBody != null) + if (indexerDeclaration.ExpressionBody is not null) { accessorList = accessorList .AddAccessors( @@ -44,7 +44,7 @@ public static void ComputeRefactoring(RefactoringContext context, IndexerDeclara else { AccessorDeclarationSyntax getter = indexerDeclaration.Getter(); - if (getter != null) + if (getter is not null) { accessorList = accessorList.AddAccessors(getter .WithBody(null) @@ -52,7 +52,7 @@ public static void ComputeRefactoring(RefactoringContext context, IndexerDeclara } AccessorDeclarationSyntax setter = indexerDeclaration.Setter(); - if (setter != null) + if (setter is not null) { accessorList = accessorList.AddAccessors(setter .WithBody(null) diff --git a/src/Refactorings/CSharp/Refactorings/MakeMemberAbstract/MakePropertyAbstractRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MakeMemberAbstract/MakePropertyAbstractRefactoring.cs index 745c29c4df..2037af786f 100644 --- a/src/Refactorings/CSharp/Refactorings/MakeMemberAbstract/MakePropertyAbstractRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MakeMemberAbstract/MakePropertyAbstractRefactoring.cs @@ -35,7 +35,7 @@ public static void ComputeRefactoring(RefactoringContext context, PropertyDeclar { AccessorListSyntax accessorList = AccessorList(); - if (propertyDeclaration.ExpressionBody != null) + if (propertyDeclaration.ExpressionBody is not null) { accessorList = accessorList .AddAccessors(AutoGetAccessorDeclaration()); @@ -43,7 +43,7 @@ public static void ComputeRefactoring(RefactoringContext context, PropertyDeclar else { AccessorDeclarationSyntax getter = propertyDeclaration.Getter(); - if (getter != null) + if (getter is not null) { if (SyntaxAccessibility.Instance.GetExplicitAccessibility(getter) == Accessibility.Private) getter = SyntaxAccessibility.WithExplicitAccessibility(getter, Accessibility.Protected); @@ -54,7 +54,7 @@ public static void ComputeRefactoring(RefactoringContext context, PropertyDeclar } AccessorDeclarationSyntax setter = propertyDeclaration.Setter(); - if (setter != null) + if (setter is not null) { if (SyntaxAccessibility.Instance.GetExplicitAccessibility(setter) == Accessibility.Private) setter = SyntaxAccessibility.WithExplicitAccessibility(setter, Accessibility.Protected); diff --git a/src/Refactorings/CSharp/Refactorings/MemberDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MemberDeclarationRefactoring.cs index f6a5d09e60..497c388869 100644 --- a/src/Refactorings/CSharp/Refactorings/MemberDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MemberDeclarationRefactoring.cs @@ -42,7 +42,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me || (!closeBrace.IsKind(SyntaxKind.None) && closeBrace.Span.Contains(context.Span))) { - if (member.Parent != null + if (member.Parent is not null && CSharpFacts.CanHaveMembers(member.Parent.Kind())) { if (context.IsRefactoringEnabled(RefactoringDescriptors.RemoveMemberDeclaration)) @@ -305,14 +305,14 @@ private static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(MemberD (SyntaxToken openBrace, SyntaxToken closeBrace) FromBody(BlockSyntax body) { - return (body != null) + return (body is not null) ? (body.OpenBraceToken, body.CloseBraceToken) : default; } (SyntaxToken openBrace, SyntaxToken closeBrace) FromAccessorList(AccessorListSyntax accessorList) { - return (accessorList != null) + return (accessorList is not null) ? (accessorList.OpenBraceToken, accessorList.CloseBraceToken) : default; } diff --git a/src/Refactorings/CSharp/Refactorings/MergeIfStatementsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MergeIfStatementsRefactoring.cs index 00fbf58942..196638cbe2 100644 --- a/src/Refactorings/CSharp/Refactorings/MergeIfStatementsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MergeIfStatementsRefactoring.cs @@ -41,7 +41,7 @@ public static void ComputeRefactorings(RefactoringContext context, StatementList { statement = ifStatement.Statement; - if (statement == null) + if (statement is null) return; } else if (!AreEquivalent(statement, ifStatement.Statement)) @@ -79,7 +79,7 @@ public static void ComputeRefactorings(RefactoringContext context, StatementList private static BinaryExpressionSyntax BinaryExpression(SyntaxKind kind, IEnumerable expressions) { - if (expressions == null) + if (expressions is null) throw new ArgumentNullException(nameof(expressions)); using (IEnumerator en = expressions.GetEnumerator()) @@ -106,10 +106,10 @@ private static BinaryExpressionSyntax BinaryExpression(SyntaxKind kind, IEnumera private static bool AreEquivalent(StatementSyntax statement1, StatementSyntax statement2) { - if (statement1 == null) + if (statement1 is null) return false; - if (statement2 == null) + if (statement2 is null) return false; if (statement1 is not BlockSyntax block1) diff --git a/src/Refactorings/CSharp/Refactorings/MergeIfWithParentIfRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MergeIfWithParentIfRefactoring.cs index 07a6bd7b57..b5f0d403a5 100644 --- a/src/Refactorings/CSharp/Refactorings/MergeIfWithParentIfRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MergeIfWithParentIfRefactoring.cs @@ -33,7 +33,7 @@ public static void ComputeRefactoring(RefactoringContext context, IfStatementSyn parentIf = block.Parent as IfStatementSyntax; - if (parentIf == null) + if (parentIf is null) return; } diff --git a/src/Refactorings/CSharp/Refactorings/MergeLocalDeclarationsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MergeLocalDeclarationsRefactoring.cs index 75ffd3dbc7..9b7514adee 100644 --- a/src/Refactorings/CSharp/Refactorings/MergeLocalDeclarationsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MergeLocalDeclarationsRefactoring.cs @@ -42,18 +42,18 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, St TypeSyntax type = localDeclaration.Declaration?.Type; - if (type == null) + if (type is null) return false; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, cancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return false; if (typeSymbol.IsErrorType()) return false; - if (prevTypeSymbol != null && !SymbolEqualityComparer.Default.Equals(prevTypeSymbol, typeSymbol)) + if (prevTypeSymbol is not null && !SymbolEqualityComparer.Default.Equals(prevTypeSymbol, typeSymbol)) return false; prevTypeSymbol = typeSymbol; diff --git a/src/Refactorings/CSharp/Refactorings/MethodDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MethodDeclarationRefactoring.cs index 29a105b655..fb021f8d1d 100644 --- a/src/Refactorings/CSharp/Refactorings/MethodDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MethodDeclarationRefactoring.cs @@ -113,7 +113,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me ITypeSymbol typeSymbol = GetType(returnType, semanticModel, context.CancellationToken); - if (typeSymbol == null) + if (typeSymbol is null) return; string newName = NameGenerator.CreateName(typeSymbol); @@ -154,7 +154,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me { ITypeSymbol returnTypeSymbol = semanticModel.GetTypeSymbol(returnType, cancellationToken); - if (returnTypeSymbol == null) + if (returnTypeSymbol is null) return null; if (returnTypeSymbol.HasMetadataName(MetadataNames.System_Threading_Tasks_Task)) diff --git a/src/Refactorings/CSharp/Refactorings/MoveUnsafeContextToContainingDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MoveUnsafeContextToContainingDeclarationRefactoring.cs index 6eda79389e..72b875e0b8 100644 --- a/src/Refactorings/CSharp/Refactorings/MoveUnsafeContextToContainingDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MoveUnsafeContextToContainingDeclarationRefactoring.cs @@ -41,7 +41,7 @@ private static void ComputeRefactoring(RefactoringContext context, SyntaxNode no SyntaxNode parent = node.FirstAncestor(f => CSharpFacts.CanHaveUnsafeModifier(f.Kind())); - if (parent == null) + if (parent is null) return; ModifierListInfo modifiersInfo = SyntaxInfo.ModifierListInfo(parent); @@ -67,7 +67,7 @@ public static void ComputeRefactoring(RefactoringContext context, UnsafeStatemen SyntaxNode parent = unsafeStatement.FirstAncestor(f => CSharpFacts.CanHaveUnsafeModifier(f.Kind())); - if (parent == null) + if (parent is null) return; ModifierListInfo modifiersInfo = SyntaxInfo.ModifierListInfo(parent); diff --git a/src/Refactorings/CSharp/Refactorings/NotifyWhenPropertyChangesRefactoring.cs b/src/Refactorings/CSharp/Refactorings/NotifyWhenPropertyChangesRefactoring.cs index 89fe3c2e61..8f3be3be9b 100644 --- a/src/Refactorings/CSharp/Refactorings/NotifyWhenPropertyChangesRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/NotifyWhenPropertyChangesRefactoring.cs @@ -19,7 +19,7 @@ internal static class NotifyWhenPropertyChangesRefactoring { AccessorDeclarationSyntax setter = property.Setter(); - if (setter == null) + if (setter is null) return; if (setter.IsKind(SyntaxKind.InitAccessorDeclaration)) @@ -27,7 +27,7 @@ internal static class NotifyWhenPropertyChangesRefactoring ExpressionSyntax expression = GetExpression(); - if (expression == null) + if (expression is null) return; SimpleAssignmentExpressionInfo simpleAssignment = SyntaxInfo.SimpleAssignmentExpressionInfo(expression); @@ -50,7 +50,7 @@ internal static class NotifyWhenPropertyChangesRefactoring .GetDeclaredSymbol(property, context.CancellationToken)? .ContainingType; - if (containingType == null) + if (containingType is null) return; if (!containingType.Implements(MetadataNames.System_ComponentModel_INotifyPropertyChanged, allInterfaces: true)) @@ -58,7 +58,7 @@ internal static class NotifyWhenPropertyChangesRefactoring IMethodSymbol methodSymbol = SymbolUtility.FindMethodThatRaisePropertyChanged(containingType, expression.SpanStart, semanticModel); - if (methodSymbol == null) + if (methodSymbol is null) return; Document document = context.Document; @@ -72,7 +72,7 @@ ExpressionSyntax GetExpression() { BlockSyntax body = setter.Body; - if (body != null) + if (body is not null) { if (body.Statements.SingleOrDefault(shouldThrow: false) is ExpressionStatementSyntax expressionStatement) return expressionStatement.Expression; @@ -134,7 +134,7 @@ public static IdentifierNameSyntax GetBackingFieldIdentifierName(AccessorDeclara { BlockSyntax body = accessor.Body; - if (body != null) + if (body is not null) { var expressionStatement = (ExpressionStatementSyntax)body.Statements[0]; diff --git a/src/Refactorings/CSharp/Refactorings/PostfixUnaryExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/PostfixUnaryExpressionRefactoring.cs index be3a31b7e9..3965f0690f 100644 --- a/src/Refactorings/CSharp/Refactorings/PostfixUnaryExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/PostfixUnaryExpressionRefactoring.cs @@ -41,7 +41,7 @@ private static void ReplacePostIncrementWithPreIncrement(RefactoringContext cont ExpressionSyntax operand = postIncrement.Operand; - if (operand == null) + if (operand is null) return; PrefixUnaryExpressionSyntax preIncrement = PreIncrementExpression(operand.WithoutTrivia()) @@ -77,7 +77,7 @@ private static void ReplacePostDecrementWithPreDecrement(RefactoringContext cont ExpressionSyntax operand = postDecrement.Operand; - if (operand == null) + if (operand is null) return; PrefixUnaryExpressionSyntax preDecrement = PreDecrementExpression(operand.WithoutTrivia()) diff --git a/src/Refactorings/CSharp/Refactorings/PrefixUnaryExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/PrefixUnaryExpressionRefactoring.cs index 888b73949f..fb70e21927 100644 --- a/src/Refactorings/CSharp/Refactorings/PrefixUnaryExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/PrefixUnaryExpressionRefactoring.cs @@ -41,7 +41,7 @@ private static void ReplacePreIncrementWithPostIncrement(RefactoringContext cont ExpressionSyntax operand = preIncrement.Operand; - if (operand == null) + if (operand is null) return; PostfixUnaryExpressionSyntax postIncrement = PostIncrementExpression(operand.WithoutTrivia()) @@ -77,7 +77,7 @@ private static void ReplacePreDecrementWithPostDecrement(RefactoringContext cont ExpressionSyntax operand = preDecrement.Operand; - if (operand == null) + if (operand is null) return; PostfixUnaryExpressionSyntax postDecrement = PostDecrementExpression(operand.WithoutTrivia()) diff --git a/src/Refactorings/CSharp/Refactorings/PromoteLocalToParameterRefactoring.cs b/src/Refactorings/CSharp/Refactorings/PromoteLocalToParameterRefactoring.cs index 7fd231f574..d5479bd014 100644 --- a/src/Refactorings/CSharp/Refactorings/PromoteLocalToParameterRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/PromoteLocalToParameterRefactoring.cs @@ -27,7 +27,7 @@ internal static class PromoteLocalToParameterRefactoring if (!methodSymbol.MethodKind.Is(MethodKind.Ordinary, MethodKind.LocalFunction)) return; - if (methodSymbol.PartialImplementationPart != null) + if (methodSymbol.PartialImplementationPart is not null) methodSymbol = methodSymbol.PartialImplementationPart; SyntaxNode methodOrLocalFunction = methodSymbol.GetSyntax(context.CancellationToken); @@ -37,19 +37,19 @@ internal static class PromoteLocalToParameterRefactoring VariableDeclarationSyntax declaration = localDeclaration.Declaration; - if (declaration == null) + if (declaration is null) return; VariableDeclaratorSyntax variable = declaration .Variables .FirstOrDefault(f => !f.IsMissing && f.Identifier.Span.Contains(context.Span)); - if (variable == null) + if (variable is null) return; TypeSyntax type = declaration.Type; - if (type == null) + if (type is null) return; if (type.IsVar) @@ -95,7 +95,7 @@ internal static class PromoteLocalToParameterRefactoring SyntaxNode newNode = methodOrLocalFunction; - if (initializerValue != null) + if (initializerValue is not null) { ExpressionStatementSyntax expressionStatement = SimpleAssignmentStatement( IdentifierName(identifier), diff --git a/src/Refactorings/CSharp/Refactorings/PropertyDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/PropertyDeclarationRefactoring.cs index 9eda575114..d70453fdc7 100644 --- a/src/Refactorings/CSharp/Refactorings/PropertyDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/PropertyDeclarationRefactoring.cs @@ -104,7 +104,7 @@ private static async Task RenamePropertyAccordingToTypeName(RefactoringContext c { TypeSyntax type = propertyDeclaration.Type; - if (type == null) + if (type is null) return; SyntaxToken identifier = propertyDeclaration.Identifier; diff --git a/src/Refactorings/CSharp/Refactorings/QualifiedNameRefactoring.cs b/src/Refactorings/CSharp/Refactorings/QualifiedNameRefactoring.cs index 634253ae54..8ef3402476 100644 --- a/src/Refactorings/CSharp/Refactorings/QualifiedNameRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/QualifiedNameRefactoring.cs @@ -16,7 +16,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Qu IdentifierNameSyntax identifierName = qualifiedName.Left as IdentifierNameSyntax ?? qualifiedName.Right as IdentifierNameSyntax; - if (identifierName != null) + if (identifierName is not null) await AddUsingDirectiveRefactoring.ComputeRefactoringsAsync(context, identifierName).ConfigureAwait(false); } } diff --git a/src/Refactorings/CSharp/Refactorings/RecordDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RecordDeclarationRefactoring.cs index f5f58186dd..16648a2b31 100644 --- a/src/Refactorings/CSharp/Refactorings/RecordDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RecordDeclarationRefactoring.cs @@ -44,7 +44,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Re } if (context.IsRefactoringEnabled(RefactoringDescriptors.ExpandPositionalConstructor) - && recordDeclaration.ParameterList != null + && recordDeclaration.ParameterList is not null && context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(recordDeclaration.ParameterList.Parameters)) { ExpandPositionalConstructorRefactoring.ComputeRefactoring(context, recordDeclaration); diff --git a/src/Refactorings/CSharp/Refactorings/RefactoringContext.cs b/src/Refactorings/CSharp/Refactorings/RefactoringContext.cs index d83aa6824d..29deb451db 100644 --- a/src/Refactorings/CSharp/Refactorings/RefactoringContext.cs +++ b/src/Refactorings/CSharp/Refactorings/RefactoringContext.cs @@ -185,7 +185,7 @@ public bool IsRefactoringEnabled(RefactoringDescriptor refactoring) return enabled; } - if (_globalIsEnabled != null) + if (_globalIsEnabled is not null) return _globalIsEnabled.Value; if (CodeAnalysisConfig.Instance.Refactorings.TryGetValue(refactoring.OptionKey, out enabled)) @@ -290,7 +290,7 @@ public void ComputeRefactoringsForNodeInsideTrivia() { SyntaxNode node = Root.FindNode(Span, findInsideTrivia: true, getInnermostNodeForTie: true); - for (; node != null; node = node.Parent) + for (; node is not null; node = node.Parent) { if (node is DirectiveTriviaSyntax directiveTrivia) { @@ -415,7 +415,7 @@ public async Task ComputeRefactoringsForNodeAsync() { SyntaxNode node = Root.FindNode(Span, findInsideTrivia: false, getInnermostNodeForTie: true); - if (node == null) + if (node is null) return; RefactoringFlags flags = RefactoringFlagsCache.GetInstance(); @@ -423,7 +423,7 @@ public async Task ComputeRefactoringsForNodeAsync() SyntaxNode firstNode = node; - for (; node != null; node = node.GetParent(ascendOutOfTrivia: true)) + for (; node is not null; node = node.GetParent(ascendOutOfTrivia: true)) { SyntaxKind kind = node.Kind(); @@ -1081,7 +1081,7 @@ public static RefactoringFlags GetInstance() { RefactoringFlags instance = _cachedInstance; - if (instance != null) + if (instance is not null) { _cachedInstance = null; return instance; diff --git a/src/Refactorings/CSharp/Refactorings/RemoveBracesFromSwitchSectionsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveBracesFromSwitchSectionsRefactoring.cs index 47d7bff862..71904d6576 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveBracesFromSwitchSectionsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveBracesFromSwitchSectionsRefactoring.cs @@ -25,7 +25,7 @@ internal static class RemoveBracesFromSwitchSectionsRefactoring .Sections .Select(section => { - if ((sections == null || Array.IndexOf(sections, section) != -1) + if ((sections is null || Array.IndexOf(sections, section) != -1) && RemoveBracesFromSwitchSectionRefactoring.CanRemoveBraces(section)) { var block = (BlockSyntax)section.Statements[0]; diff --git a/src/Refactorings/CSharp/Refactorings/RemoveBracesRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveBracesRefactoring.cs index 2b54d1fa77..c49995e410 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveBracesRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveBracesRefactoring.cs @@ -24,7 +24,7 @@ public static void ComputeRefactoring(RefactoringContext context, StatementSynta block = (BlockSyntax)statement.Parent; } - if (block != null) + if (block is not null) ComputeRefactoring(context, block); } @@ -47,7 +47,7 @@ private static void ComputeRefactoring(RefactoringContext context, BlockSyntax b { IfStatementSyntax topmostIf = GetTopmostIf(block); - if (topmostIf?.Else != null + if (topmostIf?.Else is not null && CanRefactorIfElse(block, topmostIf)) { context.RegisterRefactoring( @@ -158,7 +158,7 @@ private static bool IsEmbeddableBlock(BlockSyntax block) { SyntaxNode parent = block.Parent; - if (parent != null) + if (parent is not null) { SyntaxKind kind = parent.Kind(); @@ -168,7 +168,7 @@ private static bool IsEmbeddableBlock(BlockSyntax block) .Statements .SingleOrDefault(shouldThrow: false); - if (statement != null) + if (statement is not null) { switch (statement.Kind()) { @@ -180,7 +180,7 @@ private static bool IsEmbeddableBlock(BlockSyntax block) case SyntaxKind.IfStatement: { return kind != SyntaxKind.IfStatement - || ((IfStatementSyntax)parent).Else == null + || ((IfStatementSyntax)parent).Else is null || !((IfStatementSyntax)statement).GetCascadeInfo().EndsWithIf; } default: diff --git a/src/Refactorings/CSharp/Refactorings/RemoveConditionFromLastElseRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveConditionFromLastElseRefactoring.cs index 5af6d76a0e..112ecdd4e0 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveConditionFromLastElseRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveConditionFromLastElseRefactoring.cs @@ -13,7 +13,7 @@ internal static class RemoveConditionFromLastElseRefactoring public static void ComputeRefactorings(RefactoringContext context, ElseClauseSyntax elseClause) { if (elseClause.Statement?.Kind() == SyntaxKind.IfStatement - && ((IfStatementSyntax)elseClause.Statement).Else == null) + && ((IfStatementSyntax)elseClause.Statement).Else is null) { context.RegisterRefactoring( "Remove condition", diff --git a/src/Refactorings/CSharp/Refactorings/RemoveContainingStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveContainingStatementRefactoring.cs index 211af4d76a..f20ae799e2 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveContainingStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveContainingStatementRefactoring.cs @@ -31,7 +31,7 @@ public static void ComputeRefactoring(RefactoringContext context, StatementSynta parent = statement.Parent; } - if (parent == null) + if (parent is null) return; if (!CheckContainingNode(parent)) diff --git a/src/Refactorings/CSharp/Refactorings/RemoveEnumMemberValueRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveEnumMemberValueRefactoring.cs index bf4da20a68..25604f9a28 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveEnumMemberValueRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveEnumMemberValueRefactoring.cs @@ -22,7 +22,7 @@ internal static class RemoveEnumMemberValueRefactoring for (int i = 0; i < selectedMembers.Count; i++) { - if (selectedMembers[i].EqualsValue?.Value != null) + if (selectedMembers[i].EqualsValue?.Value is not null) { count++; @@ -50,7 +50,7 @@ internal static class RemoveEnumMemberValueRefactoring for (int i = 0; i < members.Count; i++) { - if (members[i].EqualsValue?.Value != null) + if (members[i].EqualsValue?.Value is not null) { count++; @@ -91,7 +91,7 @@ internal static class RemoveEnumMemberValueRefactoring { ExpressionSyntax expression = enumMember.EqualsValue?.Value; - if (expression == null) + if (expression is null) return false; if (keepCompositeValue diff --git a/src/Refactorings/CSharp/Refactorings/RemoveInstantiationOfLocalVariableRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveInstantiationOfLocalVariableRefactoring.cs index d39d85a8f8..2e1446941e 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveInstantiationOfLocalVariableRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveInstantiationOfLocalVariableRefactoring.cs @@ -18,7 +18,7 @@ internal static async Task ComputeRefactoringAsync(RefactoringContext context, L .SingleOrDefault(shouldThrow: false)? .Initializer; - if (equalsValueClause == null) + if (equalsValueClause is null) return; if (!context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(equalsValueClause)) @@ -26,7 +26,7 @@ internal static async Task ComputeRefactoringAsync(RefactoringContext context, L ExpressionSyntax value = equalsValueClause.Value; - if (value == null) + if (value is null) return; const string title = "Remove instantiation"; diff --git a/src/Refactorings/CSharp/Refactorings/RemoveUnnecessaryAssignmentRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveUnnecessaryAssignmentRefactoring.cs index 8a306d5a99..783007a07d 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveUnnecessaryAssignmentRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveUnnecessaryAssignmentRefactoring.cs @@ -23,7 +23,7 @@ public static void ComputeRefactorings(RefactoringContext context, StatementList if (selectedStatements.Last() is not ReturnStatementSyntax returnStatement) return; - if (returnStatement.Expression == null) + if (returnStatement.Expression is null) return; if (!CSharpFactory.AreEquivalent(simpleAssignment.Left, returnStatement.Expression)) diff --git a/src/Refactorings/CSharp/Refactorings/ReplaceConditionalExpressionWithTrueOrFalseBranchRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ReplaceConditionalExpressionWithTrueOrFalseBranchRefactoring.cs index b694f0d130..428757d871 100644 --- a/src/Refactorings/CSharp/Refactorings/ReplaceConditionalExpressionWithTrueOrFalseBranchRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ReplaceConditionalExpressionWithTrueOrFalseBranchRefactoring.cs @@ -30,7 +30,7 @@ public static void ComputeRefactoring(RefactoringContext context, ExpressionSynt if (expression == conditionalExpression.WhenFalse) title = "Replace ?: with false branch"; - if (title != null) + if (title is not null) { context.RegisterRefactoring( title, diff --git a/src/Refactorings/CSharp/Refactorings/ReplaceMethodWithProperty/ReplaceMethodWithPropertyRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ReplaceMethodWithProperty/ReplaceMethodWithPropertyRefactoring.cs index 7c0070bf39..981dfdd0f6 100644 --- a/src/Refactorings/CSharp/Refactorings/ReplaceMethodWithProperty/ReplaceMethodWithPropertyRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ReplaceMethodWithProperty/ReplaceMethodWithPropertyRefactoring.cs @@ -18,7 +18,7 @@ public static bool CanRefactor(MethodDeclarationSyntax methodDeclaration) { return methodDeclaration.ReturnType?.IsVoid() == false && methodDeclaration.ParameterList?.Parameters.Count == 0 - && methodDeclaration.TypeParameterList == null + && methodDeclaration.TypeParameterList is null && !methodDeclaration.Modifiers.ContainsAny(SyntaxKind.OverrideKeyword, SyntaxKind.AsyncKeyword); } @@ -78,7 +78,7 @@ private static PropertyDeclarationSyntax ToPropertyDeclarationCore(MethodDeclara parameterList.CloseParenToken.GetAllTrivia())); } - if (methodDeclaration.ExpressionBody != null) + if (methodDeclaration.ExpressionBody is not null) { return PropertyDeclaration( methodDeclaration.AttributeLists, @@ -107,7 +107,7 @@ private static AccessorListSyntax CreateAccessorList(MethodDeclarationSyntax met { BlockSyntax body = method.Body; - if (body != null) + if (body is not null) { SyntaxList statements = body.Statements; diff --git a/src/Refactorings/CSharp/Refactorings/ReplaceMethodWithProperty/ReplaceMethodWithPropertySyntaxRewriter.cs b/src/Refactorings/CSharp/Refactorings/ReplaceMethodWithProperty/ReplaceMethodWithPropertySyntaxRewriter.cs index c85e145811..55a30658c2 100644 --- a/src/Refactorings/CSharp/Refactorings/ReplaceMethodWithProperty/ReplaceMethodWithPropertySyntaxRewriter.cs +++ b/src/Refactorings/CSharp/Refactorings/ReplaceMethodWithProperty/ReplaceMethodWithPropertySyntaxRewriter.cs @@ -26,7 +26,7 @@ public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax { ExpressionSyntax expression = node.Expression; - if (expression != null) + if (expression is not null) { if (_nodes.Contains(expression)) { @@ -40,7 +40,7 @@ public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax SimpleNameSyntax name = memberAccess.Name; - if (name != null && _nodes.Contains(name)) + if (name is not null && _nodes.Contains(name)) { expression = (ExpressionSyntax)base.Visit(memberAccess.Expression); @@ -60,7 +60,7 @@ public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax { ArgumentListSyntax argumentList = invocation.ArgumentList; - if (argumentList != null) + if (argumentList is not null) { node = node.AppendToTrailingTrivia( argumentList.OpenParenToken.GetAllTrivia() diff --git a/src/Refactorings/CSharp/Refactorings/ReplacePropertyWithMethod/ReplacePropertyWithMethodRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ReplacePropertyWithMethod/ReplacePropertyWithMethodRefactoring.cs index 8ca712252c..19f0d0e634 100644 --- a/src/Refactorings/CSharp/Refactorings/ReplacePropertyWithMethod/ReplacePropertyWithMethodRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ReplacePropertyWithMethod/ReplacePropertyWithMethodRefactoring.cs @@ -44,12 +44,12 @@ public static bool CanRefactor(RefactoringContext context, PropertyDeclarationSy if (accessor?.Kind() != SyntaxKind.GetAccessorDeclaration) return false; - if (accessor.BodyOrExpressionBody() != null) + if (accessor.BodyOrExpressionBody() is not null) return true; return context.SupportsCSharp6 && accessor.IsAutoImplemented() - && propertyDeclaration.Initializer?.Value != null; + && propertyDeclaration.Initializer?.Value is not null; } public static async Task RefactorAsync( @@ -96,7 +96,7 @@ public static MethodDeclarationSyntax ToMethodDeclaration(PropertyDeclarationSyn BlockSyntax methodBody; - if (getterBody != null) + if (getterBody is not null) { methodBody = Block(getterBody.Statements); } @@ -104,7 +104,7 @@ public static MethodDeclarationSyntax ToMethodDeclaration(PropertyDeclarationSyn { ArrowExpressionClauseSyntax getterExpressionBody = getter.ExpressionBody; - if (getterExpressionBody != null) + if (getterExpressionBody is not null) { methodBody = Block(ReturnStatement(getterExpressionBody.Expression)); } diff --git a/src/Refactorings/CSharp/Refactorings/ReplacePropertyWithMethod/ReplacePropertyWithMethodSyntaxRewriter.cs b/src/Refactorings/CSharp/Refactorings/ReplacePropertyWithMethod/ReplacePropertyWithMethodSyntaxRewriter.cs index 8085e05f0a..59bbdc1f55 100644 --- a/src/Refactorings/CSharp/Refactorings/ReplacePropertyWithMethod/ReplacePropertyWithMethodSyntaxRewriter.cs +++ b/src/Refactorings/CSharp/Refactorings/ReplacePropertyWithMethod/ReplacePropertyWithMethodSyntaxRewriter.cs @@ -39,7 +39,7 @@ public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyn { SimpleNameSyntax name = node.Name; - if (name != null && _nodes.Contains(name)) + if (name is not null && _nodes.Contains(name)) { var expression = (ExpressionSyntax)base.Visit(node.Expression); @@ -65,7 +65,7 @@ public override SyntaxNode VisitConditionalAccessExpression(ConditionalAccessExp SimpleNameSyntax name = memberBinding.Name; - if (name != null + if (name is not null && _nodes.Contains(name)) { var expression = (ExpressionSyntax)base.Visit(node.Expression); @@ -85,7 +85,7 @@ public override SyntaxNode VisitConditionalAccessExpression(ConditionalAccessExp public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) { - if (_propertyDeclaration != null + if (_propertyDeclaration is not null && node.Span == _propertyDeclaration.Span) { node = (PropertyDeclarationSyntax)base.VisitPropertyDeclaration(node); diff --git a/src/Refactorings/CSharp/Refactorings/ReturnStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ReturnStatementRefactoring.cs index b0b90a7424..4a3c2f92ed 100644 --- a/src/Refactorings/CSharp/Refactorings/ReturnStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ReturnStatementRefactoring.cs @@ -12,7 +12,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Re { ExpressionSyntax expression = returnStatement.Expression; - if (expression != null + if (expression is not null && context.IsRefactoringEnabled(RefactoringDescriptors.ConvertReturnStatementToIf) && (context.Span.IsEmptyAndContainedInSpan(returnStatement.ReturnKeyword) || context.Span.IsBetweenSpans(returnStatement))) diff --git a/src/Refactorings/CSharp/Refactorings/SelectedLinesRefactoring.cs b/src/Refactorings/CSharp/Refactorings/SelectedLinesRefactoring.cs index d16ba23673..871a4b2a26 100644 --- a/src/Refactorings/CSharp/Refactorings/SelectedLinesRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/SelectedLinesRefactoring.cs @@ -132,7 +132,7 @@ bool IsStartOrEndOfLine(int position, bool compareWithStart, int offset = 0) { n = n.Parent; - if (n == null) + if (n is null) return false; } @@ -155,7 +155,7 @@ private static bool IsInMultiLineDocumentationComment(SyntaxNode root, int posit { SyntaxToken token = root.FindToken(position, findInsideTrivia: true); - for (SyntaxNode node = token.Parent; node != null; node = node.Parent) + for (SyntaxNode node = token.Parent; node is not null; node = node.Parent) { if (node.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia)) return true; diff --git a/src/Refactorings/CSharp/Refactorings/SortCaseLabelsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/SortCaseLabelsRefactoring.cs index cc9b971f38..2943eca0b8 100644 --- a/src/Refactorings/CSharp/Refactorings/SortCaseLabelsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/SortCaseLabelsRefactoring.cs @@ -63,12 +63,12 @@ internal static class SortCaseLabelsRefactoring string containingName = (memberAccess.Expression as IdentifierNameSyntax)?.Identifier.ValueText; - if (containingName == null) + if (containingName is null) return; string name = (memberAccess.Name as IdentifierNameSyntax)?.Identifier.ValueText; - if (name == null) + if (name is null) return; for (int i = firstIndex + 1; i <= selectedLabels.LastIndex; i++) @@ -130,10 +130,10 @@ public int Compare(SwitchLabelSyntax x, SwitchLabelSyntax y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; var label1 = (CaseSwitchLabelSyntax)x; @@ -155,10 +155,10 @@ public int Compare(SwitchLabelSyntax x, SwitchLabelSyntax y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; var label1 = (CaseSwitchLabelSyntax)x; diff --git a/src/Refactorings/CSharp/Refactorings/SortMemberDeclarations/SortEnumMemberDeclarationsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/SortMemberDeclarations/SortEnumMemberDeclarationsRefactoring.cs index 94d1f70bed..e836ba963e 100644 --- a/src/Refactorings/CSharp/Refactorings/SortMemberDeclarations/SortEnumMemberDeclarationsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/SortMemberDeclarations/SortEnumMemberDeclarationsRefactoring.cs @@ -25,7 +25,7 @@ internal static class SortEnumMemberDeclarationsRefactoring RefactoringDescriptors.SortMemberDeclarations); } - if (selectedMembers.Any(f => f.EqualsValue?.Value != null)) + if (selectedMembers.Any(f => f.EqualsValue?.Value is not null)) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); diff --git a/src/Refactorings/CSharp/Refactorings/SplitIfElseRefactoring.cs b/src/Refactorings/CSharp/Refactorings/SplitIfElseRefactoring.cs index e8f45c80b4..ec7f4a3d2a 100644 --- a/src/Refactorings/CSharp/Refactorings/SplitIfElseRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/SplitIfElseRefactoring.cs @@ -17,7 +17,7 @@ public static void ComputeRefactoring(RefactoringContext context, IfStatementSyn if (ifStatement.IsParentKind(SyntaxKind.ElseClause)) return; - if (ifStatement.Else == null) + if (ifStatement.Else is null) return; foreach (IfStatementOrElseClause ifOrElse in ifStatement.AsCascade()) @@ -27,7 +27,7 @@ public static void ComputeRefactoring(RefactoringContext context, IfStatementSyn if (statement is BlockSyntax block) statement = block.Statements.LastOrDefault(); - if (statement == null) + if (statement is null) return; if (!statement.IsKind( @@ -67,10 +67,10 @@ IEnumerable GetNewStatements() newIfStatement = newIfStatement.WithElse(null); - if (parentElse != null) + if (parentElse is not null) newIfStatement = newIfStatement.PrependToLeadingTrivia(parentElse.GetLeadingTrivia()); - if (elseClause != null) + if (elseClause is not null) newIfStatement = newIfStatement.AppendToTrailingTrivia(CSharpFactory.NewLine()); yield return newIfStatement.WithFormatterAnnotation(); diff --git a/src/Refactorings/CSharp/Refactorings/SplitIfStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/SplitIfStatementRefactoring.cs index 25d10b1020..1eb3786dfe 100644 --- a/src/Refactorings/CSharp/Refactorings/SplitIfStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/SplitIfStatementRefactoring.cs @@ -29,7 +29,7 @@ internal static void ComputeRefactoring(RefactoringContext context, IfStatementS } } else if (ifStatement.IsParentKind(SyntaxKind.ElseClause) - && ifStatement.Else == null + && ifStatement.Else is null && ifStatement.Condition.IsKind(SyntaxKind.LogicalOrExpression)) { context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/SplitLocalDeclarationAndAssignmentRefactoring.cs b/src/Refactorings/CSharp/Refactorings/SplitLocalDeclarationAndAssignmentRefactoring.cs index 2880f98c99..4a44f36227 100644 --- a/src/Refactorings/CSharp/Refactorings/SplitLocalDeclarationAndAssignmentRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/SplitLocalDeclarationAndAssignmentRefactoring.cs @@ -34,7 +34,7 @@ internal static class SplitLocalDeclarationAndAssignmentRefactoring ExpressionSyntax value = localInfo.Value; - if (value == null) + if (value is null) return; SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -81,7 +81,7 @@ internal static class SplitLocalDeclarationAndAssignmentRefactoring VariableDeclarationSyntax newDeclaration = localInfo.Declaration.ReplaceNode(declarator, newDeclarator); - if (type != null) + if (type is not null) newDeclaration = newDeclaration.WithType(type.WithTriviaFrom(newDeclaration.Type)); LocalDeclarationStatementSyntax newLocalStatement = localStatement diff --git a/src/Refactorings/CSharp/Refactorings/StatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/StatementRefactoring.cs index cb510d8af7..20e9edbc9e 100644 --- a/src/Refactorings/CSharp/Refactorings/StatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/StatementRefactoring.cs @@ -20,7 +20,7 @@ public static void ComputeRefactoring(RefactoringContext context, BlockSyntax bl { StatementSyntax statement = GetStatement(context, block, block.Parent); - if (statement != null) + if (statement is not null) RegisterRefactoring(context, statement); } } @@ -122,7 +122,7 @@ private static void RegisterRefactoring(RefactoringContext context, StatementSyn return ifStatement; } - if (ifStatement.Else == null + if (ifStatement.Else is null && block.CloseBraceToken.Span.Contains(context.Span)) { return ifStatement.GetTopmostIf(); @@ -147,7 +147,7 @@ private static void RegisterRefactoring(RefactoringContext context, StatementSyn { var tryStatement = (TryStatementSyntax)catchClause.Parent; - if (tryStatement.Finally == null + if (tryStatement.Finally is null && catchClause.Block?.CloseBraceToken.Span.Contains(context.Span) == true) { return tryStatement; diff --git a/src/Refactorings/CSharp/Refactorings/UseElementAccessRefactoring.cs b/src/Refactorings/CSharp/Refactorings/UseElementAccessRefactoring.cs index fab9fd0bc6..7d43167fb3 100644 --- a/src/Refactorings/CSharp/Refactorings/UseElementAccessRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/UseElementAccessRefactoring.cs @@ -52,7 +52,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In string propertyName = CSharpUtility.GetCountOrLengthPropertyName(invocationInfo.Expression, semanticModel, context.CancellationToken); - if (propertyName == null) + if (propertyName is null) break; context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/UseIndexInitializerRefactoring.cs b/src/Refactorings/CSharp/Refactorings/UseIndexInitializerRefactoring.cs index 1a770ccda6..afc87b4546 100644 --- a/src/Refactorings/CSharp/Refactorings/UseIndexInitializerRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/UseIndexInitializerRefactoring.cs @@ -43,7 +43,7 @@ public static async Task ComputeRefactoringAsync(RefactoringContext context, Ini semanticModel, context.CancellationToken); - if (propertySymbol == null) + if (propertySymbol is null) return; ITypeSymbol keyType = propertySymbol.Parameters[0].Type; diff --git a/src/Refactorings/CSharp/Refactorings/UseObjectInitializerRefactoring.cs b/src/Refactorings/CSharp/Refactorings/UseObjectInitializerRefactoring.cs index f6dc92cf6c..b1a2b2b651 100644 --- a/src/Refactorings/CSharp/Refactorings/UseObjectInitializerRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/UseObjectInitializerRefactoring.cs @@ -36,7 +36,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, St objectCreation = variable?.Initializer?.Value as ObjectCreationExpressionSyntax; - if (objectCreation != null) + if (objectCreation is not null) { semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -51,7 +51,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, St { objectCreation = assignment.Right as ObjectCreationExpressionSyntax; - if (objectCreation != null) + if (objectCreation is not null) { semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -60,7 +60,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, St } } - if (objectCreation == null) + if (objectCreation is null) return; if (symbol?.IsErrorType() != false) diff --git a/src/Refactorings/CSharp/Refactorings/UsingDirectiveRefactoring.cs b/src/Refactorings/CSharp/Refactorings/UsingDirectiveRefactoring.cs index 9d136f1967..eea6d3335e 100644 --- a/src/Refactorings/CSharp/Refactorings/UsingDirectiveRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/UsingDirectiveRefactoring.cs @@ -15,11 +15,11 @@ public static void ComputeRefactoring(RefactoringContext context, UsingDirective { NameEqualsSyntax alias = usingDirective.Alias; - if (alias != null) + if (alias is not null) { IdentifierNameSyntax name = alias.Name; - if (name != null + if (name is not null && context.Span.IsContainedInSpanOrBetweenSpans(name)) { context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/UsingStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/UsingStatementRefactoring.cs index 83fcba3d84..378c186cad 100644 --- a/src/Refactorings/CSharp/Refactorings/UsingStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/UsingStatementRefactoring.cs @@ -12,7 +12,7 @@ public static void ComputeRefactorings(RefactoringContext context, UsingStatemen { ExpressionSyntax expression = usingStatement.Expression; - if (expression != null) + if (expression is not null) { context.RegisterRefactoring( IntroduceLocalVariableRefactoring.GetTitle(expression), diff --git a/src/Refactorings/CSharp/Refactorings/VariableDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/VariableDeclarationRefactoring.cs index 35bd1428ab..b3e37ff691 100644 --- a/src/Refactorings/CSharp/Refactorings/VariableDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/VariableDeclarationRefactoring.cs @@ -39,7 +39,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Va { TypeSyntax type = variableDeclaration.Type; - if (type == null) + if (type is null) return; if (variableDeclaration.IsParentKind(SyntaxKind.EventFieldDeclaration)) @@ -47,7 +47,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Va VariableDeclaratorSyntax variable = variableDeclaration.Variables.SingleOrDefault(shouldThrow: false); - if (variable == null) + if (variable is null) return; SyntaxToken identifier = variable.Identifier; @@ -69,7 +69,7 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Va variable.SpanStart, cancellationToken: context.CancellationToken); - if (newName == null) + if (newName is null) return; context.RegisterRefactoring( diff --git a/src/Refactorings/CSharp/Refactorings/WrapBinaryExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/WrapBinaryExpressionRefactoring.cs index 9a035cbfd0..c14f584b31 100644 --- a/src/Refactorings/CSharp/Refactorings/WrapBinaryExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/WrapBinaryExpressionRefactoring.cs @@ -13,7 +13,7 @@ public static void ComputeRefactorings(RefactoringContext context, BinaryExpress { binaryExpression = GetBinaryExpression(binaryExpression, context.Span); - if (binaryExpression == null) + if (binaryExpression is null) return; if (!IsFormattableKind(binaryExpression.Kind())) @@ -66,7 +66,7 @@ private static BinaryExpressionSyntax GetTopmostBinaryExpression(BinaryExpressio { success = false; - if (binaryExpression.Parent != null + if (binaryExpression.Parent is not null && IsFormattableKind(binaryExpression.Parent.Kind())) { var parent = (BinaryExpressionSyntax)binaryExpression.Parent; diff --git a/src/Refactorings/CSharp/Refactorings/WrapStatements/WrapStatementsInUsingStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/WrapStatements/WrapStatementsInUsingStatementRefactoring.cs index e5a134e8f6..7ae5950448 100644 --- a/src/Refactorings/CSharp/Refactorings/WrapStatements/WrapStatementsInUsingStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/WrapStatements/WrapStatementsInUsingStatementRefactoring.cs @@ -23,7 +23,7 @@ public async Task ComputeRefactoringAsync(RefactoringContext context, StatementL ExpressionSyntax value = localInfo.Value; - if (value == null) + if (value is null) return; if (value.Kind() == SyntaxKind.DefaultExpression) diff --git a/src/Refactorings/CSharp/Refactorings/YieldStatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/YieldStatementRefactoring.cs index 7d3ec35d92..08efabfc11 100644 --- a/src/Refactorings/CSharp/Refactorings/YieldStatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/YieldStatementRefactoring.cs @@ -27,9 +27,9 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Yi { SyntaxNode declaration = yieldStatement.FirstAncestor(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement, SyntaxKind.GetAccessorDeclaration, ascendOutOfTrivia: false); - Debug.Assert(declaration != null); + Debug.Assert(declaration is not null); - if (declaration != null) + if (declaration is not null) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); diff --git a/src/Tests/CSharp.Tests/SyntaxKindTests.cs b/src/Tests/CSharp.Tests/SyntaxKindTests.cs index 3893737d66..9b7cc660dc 100644 --- a/src/Tests/CSharp.Tests/SyntaxKindTests.cs +++ b/src/Tests/CSharp.Tests/SyntaxKindTests.cs @@ -573,7 +573,7 @@ public static void DetectNewSyntaxKinds() } } - if (unknownKinds != null) + if (unknownKinds is not null) { Assert.True( false, diff --git a/src/Tests/Testing.Common/Extensions/TestExtensions.cs b/src/Tests/Testing.Common/Extensions/TestExtensions.cs index eed0afe4a1..efe798d809 100644 --- a/src/Tests/Testing.Common/Extensions/TestExtensions.cs +++ b/src/Tests/Testing.Common/Extensions/TestExtensions.cs @@ -34,7 +34,7 @@ internal static class TestExtensions public static LinePositionSpan ToLinePositionSpan(this TextSpan span, string s) { - if (s == null) + if (s is null) throw new ArgumentNullException(nameof(s)); int length = s.Length; diff --git a/src/Tests/Testing.Common/RuntimeMetadataReference.cs b/src/Tests/Testing.Common/RuntimeMetadataReference.cs index 81b9348e5f..71d6f82fdc 100644 --- a/src/Tests/Testing.Common/RuntimeMetadataReference.cs +++ b/src/Tests/Testing.Common/RuntimeMetadataReference.cs @@ -21,7 +21,7 @@ internal static class RuntimeMetadataReference { get { - if (_trustedPlatformAssemblyMap == null) + if (_trustedPlatformAssemblyMap is null) Interlocked.CompareExchange(ref _trustedPlatformAssemblyMap, CreateTrustedPlatformAssemblies(), null); return _trustedPlatformAssemblyMap; @@ -41,7 +41,7 @@ internal static class RuntimeMetadataReference { get { - if (_metadataReferences == null) + if (_metadataReferences is null) Interlocked.CompareExchange(ref _metadataReferences, CreateMetadataReferences(), null); return _metadataReferences; diff --git a/src/Tests/Testing.Common/Testing/CodeVerifier.cs b/src/Tests/Testing.Common/Testing/CodeVerifier.cs index 1bcb3b6892..e7280a3fc6 100644 --- a/src/Tests/Testing.Common/Testing/CodeVerifier.cs +++ b/src/Tests/Testing.Common/Testing/CodeVerifier.cs @@ -60,7 +60,7 @@ internal void Fail(string userMessage, IEnumerable codeActions) { var s = ""; - if (codeActions != null) + if (codeActions is not null) s = string.Join(NewLine, codeActions.Select(a => $"\"{a.Title}\", EquivalenceKey: {a.EquivalenceKey}")); if (s.Length == 0) @@ -142,7 +142,7 @@ bool IsNewCompilerDiagnostic(Diagnostic newDiagnostic) CodeAction codeAction, string title) { - if (title != null) + if (title is not null) Assert.Equal(title, codeAction.Title); ImmutableArray operations = await codeAction.GetOperationsAsync(CancellationToken.None); @@ -251,7 +251,7 @@ static string GetAnnotationKind(string value) expectedSpan.ToLinePositionSpan(source), actualSpan.ToLinePositionSpan(source)); - if (message != null) + if (message is not null) Fail($"Annotation '{kind}'{message}"); } } @@ -328,7 +328,7 @@ internal static (Document document, ImmutableArray expectedDoc project = configFile.Project; } - if (descriptor != null) + if (descriptor is not null) { CompilationOptions newCompilationOptions = project.CompilationOptions.EnsureDiagnosticEnabled(descriptor); @@ -358,7 +358,7 @@ internal static (Document document, ImmutableArray expectedDoc string expectedSource = additionalFiles[i].ExpectedSource; - if (expectedSource != null) + if (expectedSource is not null) expectedDocuments.Add(new ExpectedDocument(additionalDocument.Id, expectedSource)); project = additionalDocument.Project; diff --git a/src/Tests/Testing.Common/Testing/CompilerDiagnosticFixVerifier.cs b/src/Tests/Testing.Common/Testing/CompilerDiagnosticFixVerifier.cs index 7dcd0b46c1..47d2ec1a14 100644 --- a/src/Tests/Testing.Common/Testing/CompilerDiagnosticFixVerifier.cs +++ b/src/Tests/Testing.Common/Testing/CompilerDiagnosticFixVerifier.cs @@ -35,10 +35,10 @@ internal CompilerDiagnosticFixVerifier(IAssert assert) : base(assert) TestOptions options = null, CancellationToken cancellationToken = default) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (expected == null) + if (expected is null) throw new ArgumentNullException(nameof(expected)); cancellationToken.ThrowIfCancellationRequested(); @@ -87,7 +87,7 @@ internal CompilerDiagnosticFixVerifier(IAssert assert) : base(assert) Diagnostic diagnostic = FindDiagnosticToFix(diagnostics); - if (diagnostic == null) + if (diagnostic is null) { if (!fixRegistered) Fail($"No compiler diagnostic with ID '{data.DiagnosticId}' found.", diagnostics); @@ -103,11 +103,11 @@ internal CompilerDiagnosticFixVerifier(IAssert assert) : base(assert) diagnostic, (a, d) => { - if ((data.EquivalenceKey == null + if ((data.EquivalenceKey is null || string.Equals(data.EquivalenceKey, a.EquivalenceKey, StringComparison.Ordinal)) && d.Contains(diagnostic)) { - if (action != null) + if (action is not null) Fail($"Multiple fixes registered by '{fixProvider.GetType().Name}'.", new CodeAction[] { action, a }); action = a; @@ -121,7 +121,7 @@ internal CompilerDiagnosticFixVerifier(IAssert assert) : base(assert) await fixProvider.RegisterCodeFixesAsync(context); - if (action == null) + if (action is null) Fail("No code fix has been registered.", candidateActions); fixRegistered = true; @@ -145,7 +145,7 @@ Diagnostic FindDiagnosticToFix(ImmutableArray diagnostics) { if (string.Equals(diagnostic.Id, data.DiagnosticId, StringComparison.Ordinal)) { - if (match == null + if (match is null || diagnostic.Location.SourceSpan.Start > match.Location.SourceSpan.Start) { match = diagnostic; @@ -168,7 +168,7 @@ Diagnostic FindDiagnosticToFix(ImmutableArray diagnostics) TestOptions options = null, CancellationToken cancellationToken = default) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); cancellationToken.ThrowIfCancellationRequested(); @@ -196,7 +196,7 @@ Diagnostic FindDiagnosticToFix(ImmutableArray diagnostics) diagnostic, (a, d) => { - if (data.EquivalenceKey != null + if (data.EquivalenceKey is not null && !string.Equals(a.EquivalenceKey, data.EquivalenceKey, StringComparison.Ordinal)) { return; diff --git a/src/Tests/Testing.Common/Testing/DiagnosticVerifier.cs b/src/Tests/Testing.Common/Testing/DiagnosticVerifier.cs index 39c081b542..2a176b4e4f 100644 --- a/src/Tests/Testing.Common/Testing/DiagnosticVerifier.cs +++ b/src/Tests/Testing.Common/Testing/DiagnosticVerifier.cs @@ -37,7 +37,7 @@ internal DiagnosticVerifier(IAssert assert) : base(assert) TestOptions options = null, CancellationToken cancellationToken = default) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); cancellationToken.ThrowIfCancellationRequested(); @@ -112,7 +112,7 @@ internal DiagnosticVerifier(IAssert assert) : base(assert) TestOptions options = null, CancellationToken cancellationToken = default) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); cancellationToken.ThrowIfCancellationRequested(); @@ -186,10 +186,10 @@ internal DiagnosticVerifier(IAssert assert) : base(assert) TestOptions options = null, CancellationToken cancellationToken = default) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (expected == null) + if (expected is null) throw new ArgumentNullException(nameof(expected)); cancellationToken.ThrowIfCancellationRequested(); @@ -268,7 +268,7 @@ internal DiagnosticVerifier(IAssert assert) : base(assert) return null; } - if (diagnostic == null) + if (diagnostic is null) { if (!fixRegistered) Fail($"No diagnostic with ID '{data.Descriptor.Id}' found.", diagnostics); @@ -284,11 +284,11 @@ internal DiagnosticVerifier(IAssert assert) : base(assert) diagnostic, (a, d) => { - if ((data.EquivalenceKey == null + if ((data.EquivalenceKey is null || string.Equals(data.EquivalenceKey, a.EquivalenceKey, StringComparison.Ordinal)) && d.Contains(diagnostic)) { - if (action != null) + if (action is not null) Fail($"Multiple fixes registered by '{fixProvider.GetType().Name}'.", new CodeAction[] { action, a }); action = a; @@ -302,7 +302,7 @@ internal DiagnosticVerifier(IAssert assert) : base(assert) await fixProvider.RegisterCodeFixesAsync(context); - if (action == null) + if (action is null) Fail("No code fix has been registered.", candidateActions); fixRegistered = true; @@ -331,7 +331,7 @@ internal DiagnosticVerifier(IAssert assert) : base(assert) TestOptions options = null, CancellationToken cancellationToken = default) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); cancellationToken.ThrowIfCancellationRequested(); @@ -374,7 +374,7 @@ internal DiagnosticVerifier(IAssert assert) : base(assert) diagnostic, (a, d) => { - if ((data.EquivalenceKey == null + if ((data.EquivalenceKey is null || string.Equals(a.EquivalenceKey, data.EquivalenceKey, StringComparison.Ordinal)) && d.Contains(diagnostic)) { @@ -475,7 +475,7 @@ void ReportMismatch(IEnumerable actualDiagnostics, int actualCount, if (verifyAdditionalLocations) VerifyAdditionalLocations(expectedDiagnostic.AdditionalLocations, actualDiagnostic.AdditionalLocations); - if (message != null) + if (message is not null) Assert.Equal(message, actualDiagnostic.GetMessage(formatProvider)); void VerifyLocation( @@ -528,7 +528,7 @@ void ReportMismatch(IEnumerable actualDiagnostics, int actualCount, string message = VerifyLinePositionSpan(expected.Span, actual.Span); - if (message != null) + if (message is not null) Fail($"Diagnostic{message}{GetMessage()}"); } @@ -579,10 +579,10 @@ string GetMessage() ImmutableArray diagnostics = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(cancellationToken); - if (exception != null) + if (exception is not null) Fail($"An exception occurred in analyzer '{analyzer.GetType()}'.{Environment.NewLine}{exception}"); - return (comparer != null) + return (comparer is not null) ? diagnostics.Sort(comparer) : diagnostics; } diff --git a/src/Tests/Testing.Common/Testing/ExpectedTestState.cs b/src/Tests/Testing.Common/Testing/ExpectedTestState.cs index fac88bc8ab..98db2e0650 100644 --- a/src/Tests/Testing.Common/Testing/ExpectedTestState.cs +++ b/src/Tests/Testing.Common/Testing/ExpectedTestState.cs @@ -65,7 +65,7 @@ public sealed class ExpectedTestState { get { - if (_annotationsByKind == null) + if (_annotationsByKind is null) { Interlocked.CompareExchange( ref _annotationsByKind, diff --git a/src/Tests/Testing.Common/Testing/RefactoringVerifier.cs b/src/Tests/Testing.Common/Testing/RefactoringVerifier.cs index 2ba4e4e16e..266857f237 100644 --- a/src/Tests/Testing.Common/Testing/RefactoringVerifier.cs +++ b/src/Tests/Testing.Common/Testing/RefactoringVerifier.cs @@ -36,10 +36,10 @@ internal RefactoringVerifier(IAssert assert) : base(assert) TestOptions options = null, CancellationToken cancellationToken = default) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); - if (expected == null) + if (expected is null) throw new ArgumentNullException(nameof(expected)); if (data.Spans.IsEmpty) @@ -71,10 +71,10 @@ internal RefactoringVerifier(IAssert assert) : base(assert) span, a => { - if (data.EquivalenceKey == null + if (data.EquivalenceKey is null || string.Equals(a.EquivalenceKey, data.EquivalenceKey, StringComparison.Ordinal)) { - if (action != null) + if (action is not null) Fail($"Multiple refactorings registered by '{refactoringProvider.GetType().Name}'.", new CodeAction[] { action, a }); action = a; @@ -88,7 +88,7 @@ internal RefactoringVerifier(IAssert assert) : base(assert) await refactoringProvider.ComputeRefactoringsAsync(context); - if (action == null) + if (action is null) Fail("No code refactoring has been registered.", candidateActions); document = await VerifyAndApplyCodeActionAsync(document, action, expected.CodeActionTitle); @@ -118,7 +118,7 @@ internal RefactoringVerifier(IAssert assert) : base(assert) TestOptions options = null, CancellationToken cancellationToken = default) { - if (data == null) + if (data is null) throw new ArgumentNullException(nameof(data)); if (data.Spans.IsEmpty) @@ -149,7 +149,7 @@ internal RefactoringVerifier(IAssert assert) : base(assert) span, a => { - if (data.EquivalenceKey == null + if (data.EquivalenceKey is null || string.Equals(a.EquivalenceKey, data.EquivalenceKey, StringComparison.Ordinal)) { Fail("No code refactoring expected."); diff --git a/src/Tests/Testing.Common/Testing/TestCode.cs b/src/Tests/Testing.Common/Testing/TestCode.cs index a0979c4b59..3d91f7b1e2 100644 --- a/src/Tests/Testing.Common/Testing/TestCode.cs +++ b/src/Tests/Testing.Common/Testing/TestCode.cs @@ -57,7 +57,7 @@ internal TestCode(string value, string expectedValue, ImmutableArray s /// public static TestCode Parse(string value) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); (string source, ImmutableArray spans) = FindSpansAndRemove(value); @@ -78,10 +78,10 @@ public static TestCode Parse(string value) string replacement1, string replacement2 = null) { - if (value == null) + if (value is null) throw new ArgumentNullException(nameof(value)); - if (replacement1 == null) + if (replacement1 is null) throw new ArgumentNullException(nameof(replacement1)); (string source, string expected, ImmutableArray spans) = FindSpansAndReplace(value, replacement1, replacement2); diff --git a/src/Tests/Testing.Common/Testing/Text/LinePositionSpanInfoComparer.cs b/src/Tests/Testing.Common/Testing/Text/LinePositionSpanInfoComparer.cs index 1417e8ed72..b1d50f24c7 100644 --- a/src/Tests/Testing.Common/Testing/Text/LinePositionSpanInfoComparer.cs +++ b/src/Tests/Testing.Common/Testing/Text/LinePositionSpanInfoComparer.cs @@ -23,10 +23,10 @@ public int Compare(object x, object y) if (x == y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is LinePositionSpanInfo a @@ -43,10 +43,10 @@ public int Compare(object x, object y) if (x == y) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x is LinePositionSpanInfo a @@ -60,7 +60,7 @@ public int Compare(object x, object y) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) return 0; if (obj is LinePositionSpanInfo linePositionInfo) diff --git a/src/Tests/Testing.Common/Testing/Text/TextProcessor.cs b/src/Tests/Testing.Common/Testing/Text/TextProcessor.cs index 4e955c1e76..a9a87e0b77 100644 --- a/src/Tests/Testing.Common/Testing/Text/TextProcessor.cs +++ b/src/Tests/Testing.Common/Testing/Text/TextProcessor.cs @@ -52,7 +52,7 @@ public static (string source, ImmutableArray<(string kind, TextSpan span)> annot string identifier = match.Groups["identifier"].Value; - if (annotationIdentifier == null + if (annotationIdentifier is null || string.Equals(annotationIdentifier, identifier, StringComparison.Ordinal)) { var span = new TextSpan(match.Index - offset, content.Length); @@ -123,7 +123,7 @@ public static (string, ImmutableArray) FindSpansAndRemove(string text) var start2 = new LinePositionInfo(sb.Length, line, column); - if (stack != null) + if (stack is not null) { stack.Push(start2); } @@ -202,7 +202,7 @@ char PeekChar(int offset) void CloseSpan() { - if (stack != null) + if (stack is not null) { start = stack.Pop(); } @@ -238,7 +238,7 @@ void CloseSpan() if (spans.Length > 1) throw new InvalidOperationException("Text contains more than one span."); - string expected = (replacement2 != null) + string expected = (replacement2 is not null) ? source.Remove(spans[0].Start) + replacement2 + source.Substring(spans[0].End) : null; diff --git a/src/Tests/Tests.Common/Testing/CSharp/WellKnownCSharpTestOptions.cs b/src/Tests/Tests.Common/Testing/CSharp/WellKnownCSharpTestOptions.cs index 33ee00d4f2..570663548b 100644 --- a/src/Tests/Tests.Common/Testing/CSharp/WellKnownCSharpTestOptions.cs +++ b/src/Tests/Tests.Common/Testing/CSharp/WellKnownCSharpTestOptions.cs @@ -20,7 +20,7 @@ public static CSharpTestOptions Default_CSharp5 { get { - if (_default_CSharp5 == null) + if (_default_CSharp5 is null) Interlocked.CompareExchange(ref _default_CSharp5, Create(), null); return _default_CSharp5; @@ -33,7 +33,7 @@ public static CSharpTestOptions Default_CSharp6 { get { - if (_default_CSharp6 == null) + if (_default_CSharp6 is null) Interlocked.CompareExchange(ref _default_CSharp6, Create(), null); return _default_CSharp6; @@ -46,7 +46,7 @@ public static CSharpTestOptions Default_CSharp7 { get { - if (_default_CSharp7 == null) + if (_default_CSharp7 is null) Interlocked.CompareExchange(ref _default_CSharp7, Create(), null); return _default_CSharp7; @@ -59,7 +59,7 @@ public static CSharpTestOptions Default_CSharp7_3 { get { - if (_default_CSharp7_3 == null) + if (_default_CSharp7_3 is null) Interlocked.CompareExchange(ref _default_CSharp7_3, Create(), null); return _default_CSharp7_3; @@ -72,7 +72,7 @@ public static CSharpTestOptions Default_CSharp8 { get { - if (_default_CSharp8 == null) + if (_default_CSharp8 is null) Interlocked.CompareExchange(ref _default_CSharp8, Create(), null); return _default_CSharp8; @@ -85,7 +85,7 @@ public static CSharpTestOptions Default_CSharp9 { get { - if (_default_CSharp9 == null) + if (_default_CSharp9 is null) Interlocked.CompareExchange(ref _default_CSharp9, Create(), null); return _default_CSharp9; @@ -98,7 +98,7 @@ public static CSharpTestOptions Default_NullableReferenceTypes { get { - if (_default_NullableReferenceTypes == null) + if (_default_NullableReferenceTypes is null) Interlocked.CompareExchange(ref _default_NullableReferenceTypes, Create(), null); return _default_NullableReferenceTypes; diff --git a/src/Tools/CodeGeneration/CSharp/CodeFixDescriptorsGenerator.cs b/src/Tools/CodeGeneration/CSharp/CodeFixDescriptorsGenerator.cs index f6debbb8ad..a3befa4eec 100644 --- a/src/Tools/CodeGeneration/CSharp/CodeFixDescriptorsGenerator.cs +++ b/src/Tools/CodeGeneration/CSharp/CodeFixDescriptorsGenerator.cs @@ -94,7 +94,7 @@ public override SyntaxNode VisitArgument(ArgumentSyntax node) { ExpressionSyntax newExpression = node.Expression.PrependToLeadingTrivia(Whitespace(new string(' ', 18 - node.NameColon?.Name.Identifier.ValueText.Length ?? 0))); - if (node.NameColon != null) + if (node.NameColon is not null) { node = node.WithNameColon(node.NameColon.AppendToLeadingTrivia(TriviaList(NewLine(), Whitespace(" ")))); } diff --git a/src/Tools/CodeGeneration/CSharp/CodeGenerator.cs b/src/Tools/CodeGeneration/CSharp/CodeGenerator.cs index 0de4c9a406..974e88184b 100644 --- a/src/Tools/CodeGeneration/CSharp/CodeGenerator.cs +++ b/src/Tools/CodeGeneration/CSharp/CodeGenerator.cs @@ -35,7 +35,7 @@ public static CompilationUnitSyntax GenerateConfigOptions(IEnumerable !options.Any(o => o.Key == f.Key)); - Debug.Assert(mismatch.Key == null, mismatch.Key); + Debug.Assert(mismatch.Key is null, mismatch.Key); IEnumerable optionKeys = f.keys .Join(options, f => f.Key, f => f.Key, (_, g) => g) diff --git a/src/Tools/CodeGeneration/CSharp/DiagnosticIdentifiersGenerator.cs b/src/Tools/CodeGeneration/CSharp/DiagnosticIdentifiersGenerator.cs index fe13e62b14..b83b4c55dd 100644 --- a/src/Tools/CodeGeneration/CSharp/DiagnosticIdentifiersGenerator.cs +++ b/src/Tools/CodeGeneration/CSharp/DiagnosticIdentifiersGenerator.cs @@ -38,7 +38,7 @@ private static IEnumerable CreateMembers(AnalyzerMetadat string id = analyzer.Id; string identifier = analyzer.Identifier; - if (id != null) + if (id is not null) yield return CreateMember(id, identifier, analyzer.IsObsolete); } diff --git a/src/Tools/CodeGeneration/CSharp/DiagnosticRulesGenerator.cs b/src/Tools/CodeGeneration/CSharp/DiagnosticRulesGenerator.cs index 207a7b911f..a27eafddc2 100644 --- a/src/Tools/CodeGeneration/CSharp/DiagnosticRulesGenerator.cs +++ b/src/Tools/CodeGeneration/CSharp/DiagnosticRulesGenerator.cs @@ -55,7 +55,7 @@ public class DiagnosticRulesGenerator { foreach (AnalyzerMetadata analyzer in analyzers) { - if (analyzer.Id == null) + if (analyzer.Id is null) continue; string identifier = analyzer.Identifier; diff --git a/src/Tools/CodeGeneration/CSharp/Symbols.cs b/src/Tools/CodeGeneration/CSharp/Symbols.cs index 0ba0e3cf55..3c0bf295e5 100644 --- a/src/Tools/CodeGeneration/CSharp/Symbols.cs +++ b/src/Tools/CodeGeneration/CSharp/Symbols.cs @@ -106,7 +106,7 @@ public static IMethodSymbol FindVisitMethod(ITypeSymbol typeSymbol) string name = null, bool skipObsolete = true) { - foreach (ISymbol symbol in (name != null) + foreach (ISymbol symbol in (name is not null) ? typeSymbol.GetMembers(name) : typeSymbol.GetMembers()) { diff --git a/src/Tools/CodeGeneration/CSharp/SyntaxWalker/CSharpFactory2.cs b/src/Tools/CodeGeneration/CSharp/SyntaxWalker/CSharpFactory2.cs index 2ed15c409f..986dcee519 100644 --- a/src/Tools/CodeGeneration/CSharp/SyntaxWalker/CSharpFactory2.cs +++ b/src/Tools/CodeGeneration/CSharp/SyntaxWalker/CSharpFactory2.cs @@ -18,7 +18,7 @@ internal static class CSharpFactory2 { ExpressionSyntax expression = IdentifierName(name); - if (propertyName != null) + if (propertyName is not null) { expression = SimpleMemberAccessExpression( expression, @@ -67,7 +67,7 @@ public static ThrowStatementSyntax ThrowNewInvalidOperationException(ExpressionS { ArgumentListSyntax argumentList; - if (expression != null) + if (expression is not null) { argumentList = ArgumentList(Argument(expression)); } diff --git a/src/Tools/CodeGeneration/CSharp/SyntaxWalker/CSharpSyntaxWalkerGenerator.cs b/src/Tools/CodeGeneration/CSharp/SyntaxWalker/CSharpSyntaxWalkerGenerator.cs index 11e6f9c537..564a4a5a3c 100644 --- a/src/Tools/CodeGeneration/CSharp/SyntaxWalker/CSharpSyntaxWalkerGenerator.cs +++ b/src/Tools/CodeGeneration/CSharp/SyntaxWalker/CSharpSyntaxWalkerGenerator.cs @@ -96,7 +96,7 @@ public List CreateMemberDeclarations() void AddIfNotNull(MemberDeclarationSyntax memberDeclaration) { - if (memberDeclaration != null) + if (memberDeclaration is not null) members.Add(memberDeclaration); } } @@ -308,7 +308,7 @@ protected virtual void CreateVisitListStatements(MethodGenerationContext context string methodName = null; - if (methodSymbol != null) + if (methodSymbol is not null) { methodName = methodSymbol.Name; } @@ -317,7 +317,7 @@ protected virtual void CreateVisitListStatements(MethodGenerationContext context methodName = GetMethodName(typeSymbol); } - if (methodName != null) + if (methodName is not null) { string typeName = typeSymbol.Name; @@ -348,7 +348,7 @@ protected virtual void CreateTypeVisitStatements(MethodGenerationContext context IMethodSymbol methodSymbol = FindVisitMethod(propertyType); - if (methodSymbol == null) + if (methodSymbol is null) { if (EliminateDefaultVisit) { @@ -397,7 +397,7 @@ private void CreateVisitListSyntaxStatements(MethodGenerationContext context) string methodName = null; - if (methodSymbol != null) + if (methodSymbol is not null) { methodName = methodSymbol.Name; } @@ -408,7 +408,7 @@ private void CreateVisitListSyntaxStatements(MethodGenerationContext context) StatementSyntax statement; - if (methodName != null) + if (methodName is not null) { string forEachVariableName = context.CreateVariableName(typeSymbol.Name.Remove(typeSymbol.Name.Length - 6)); @@ -471,7 +471,7 @@ private static string GetMethodName(ITypeSymbol typeSymbol) typeSymbol = typeSymbol.BaseType; } - while (typeSymbol != null); + while (typeSymbol is not null); throw new ArgumentException("", nameof(typeSymbol)); } diff --git a/src/Tools/CodeGeneration/CSharp/WrapRewriter.cs b/src/Tools/CodeGeneration/CSharp/WrapRewriter.cs index d626411ca7..f501a7a254 100644 --- a/src/Tools/CodeGeneration/CSharp/WrapRewriter.cs +++ b/src/Tools/CodeGeneration/CSharp/WrapRewriter.cs @@ -71,7 +71,7 @@ public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node) public override SyntaxNode VisitArgument(ArgumentSyntax node) { if ((Options & WrapRewriterOptions.WrapArguments) != 0 - && node.NameColon != null) + && node.NameColon is not null) { return node .WithNameColon(node.NameColon.AppendToLeadingTrivia(TriviaList(NewLine(), Whitespace(new string(' ', 4 * (2 + _classDeclarationDepth)))))) diff --git a/src/Tools/CodeGeneration/EditorConfig/EditorConfigGenerator.cs b/src/Tools/CodeGeneration/EditorConfig/EditorConfigGenerator.cs index d85420a61f..69d3669432 100644 --- a/src/Tools/CodeGeneration/EditorConfig/EditorConfigGenerator.cs +++ b/src/Tools/CodeGeneration/EditorConfig/EditorConfigGenerator.cs @@ -49,7 +49,7 @@ public static string GenerateEditorConfig(RoslynatorMetadata metadata, bool comm string defaultValue = option.DefaultValue; - if (defaultValue != null) + if (defaultValue is not null) w.WriteLine($"# Default: {defaultValue}"); if (analyzers?.Count > 0) diff --git a/src/Tools/CodeGeneration/Markdown/AnalyzersMapping.cs b/src/Tools/CodeGeneration/Markdown/AnalyzersMapping.cs index 130a14b9d5..86eb30ef66 100644 --- a/src/Tools/CodeGeneration/Markdown/AnalyzersMapping.cs +++ b/src/Tools/CodeGeneration/Markdown/AnalyzersMapping.cs @@ -38,7 +38,7 @@ internal static class AnalyzersMapping { get { - if (_mapping == null) + if (_mapping is null) Interlocked.CompareExchange(ref _mapping, LoadMapping(), null); return _mapping; @@ -53,7 +53,7 @@ internal static class AnalyzersMapping { string line = null; - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) { if (line.Length > 0) { diff --git a/src/Tools/CodeGeneration/Markdown/MarkdownGenerator.cs b/src/Tools/CodeGeneration/Markdown/MarkdownGenerator.cs index 20ef48e516..1c98049152 100644 --- a/src/Tools/CodeGeneration/Markdown/MarkdownGenerator.cs +++ b/src/Tools/CodeGeneration/Markdown/MarkdownGenerator.cs @@ -243,7 +243,7 @@ public static string CreateAnalyzerOptionMarkdown(AnalyzerOptionMetadata option) private static IEnumerable CreateAppliesTo(IEnumerable<(string title, string url)> appliesTo) { - if (appliesTo != null) + if (appliesTo is not null) { yield return Heading2("Applies to"); yield return BulletList(appliesTo.Select(f => LinkOrText(f.title, f.url))); diff --git a/src/Tools/CodeGenerator/Program.cs b/src/Tools/CodeGenerator/Program.cs index 20d05260ce..53d302f48d 100644 --- a/src/Tools/CodeGenerator/Program.cs +++ b/src/Tools/CodeGenerator/Program.cs @@ -18,7 +18,7 @@ internal static class Program { private static void Main(string[] args) { - if (args == null || args.Length == 0) + if (args is null || args.Length == 0) { #if DEBUG args = new[] { @"..\..\..\..\.." }; diff --git a/src/Tools/Metadata/AnalyzerMetadata.cs b/src/Tools/Metadata/AnalyzerMetadata.cs index 730f63dfdc..7428c4091c 100644 --- a/src/Tools/Metadata/AnalyzerMetadata.cs +++ b/src/Tools/Metadata/AnalyzerMetadata.cs @@ -55,7 +55,7 @@ public class AnalyzerMetadata Kind = kind; Parent = parent; - if (Parent != null) + if (Parent is not null) _optionAnalyzers = new ReadOnlyCollection(new List()); } @@ -99,7 +99,7 @@ public IReadOnlyList OptionAnalyzers { get { - if (_optionAnalyzers == null) + if (_optionAnalyzers is null) { Interlocked.CompareExchange( ref _optionAnalyzers, diff --git a/src/Tools/Metadata/AnalyzerOptionMetadata.cs b/src/Tools/Metadata/AnalyzerOptionMetadata.cs index 5ed8ca64f0..af2ca94d59 100644 --- a/src/Tools/Metadata/AnalyzerOptionMetadata.cs +++ b/src/Tools/Metadata/AnalyzerOptionMetadata.cs @@ -46,7 +46,7 @@ public class AnalyzerOptionMetadata public AnalyzerMetadata CreateAnalyzerMetadata(AnalyzerMetadata parent) { return new AnalyzerMetadata( - id: (Id != null) ? parent.Id + Id : null, + id: (Id is not null) ? parent.Id + Id : null, identifier: Identifier, title: Title, messageFormat: Title, diff --git a/src/Tools/Metadata/MetadataFile.cs b/src/Tools/Metadata/MetadataFile.cs index 69f54694dc..61ac11bc1d 100644 --- a/src/Tools/Metadata/MetadataFile.cs +++ b/src/Tools/Metadata/MetadataFile.cs @@ -18,7 +18,7 @@ public static class MetadataFile private static string NormalizeNewLine(this string value) { - return (value != null) ? _lfWithoutCr.Replace(value, "\r\n") : null; + return (value is not null) ? _lfWithoutCr.Replace(value, "\r\n") : null; } public static IEnumerable ReadAnalyzers(string filePath) @@ -317,7 +317,7 @@ public static void CleanAnalyzers(string filePath) XElement messageFormatElement = element.Element("MessageFormat"); - if (messageFormatElement != null) + if (messageFormatElement is not null) { string messageFormat = messageFormatElement.Value; @@ -331,7 +331,7 @@ public static void CleanAnalyzers(string filePath) XElement supportsFadeOutElement = element.Element("SupportsFadeOut"); - if (supportsFadeOutElement != null + if (supportsFadeOutElement is not null && !bool.Parse(supportsFadeOutElement.Value)) { supportsFadeOutElement.Remove(); @@ -339,7 +339,7 @@ public static void CleanAnalyzers(string filePath) XElement supportsFadeOutAnalyzerElement = element.Element("SupportsFadeOutAnalyzer"); - if (supportsFadeOutAnalyzerElement != null + if (supportsFadeOutAnalyzerElement is not null && !bool.Parse(supportsFadeOutAnalyzerElement.Value)) { supportsFadeOutAnalyzerElement.Remove(); @@ -347,7 +347,7 @@ public static void CleanAnalyzers(string filePath) XElement minLanguageVersionElement = element.Element("MinLanguageVersion"); - if (minLanguageVersionElement != null + if (minLanguageVersionElement is not null && string.IsNullOrWhiteSpace(minLanguageVersionElement.Value)) { minLanguageVersionElement.Remove(); @@ -355,7 +355,7 @@ public static void CleanAnalyzers(string filePath) XElement summaryElement = element.Element("Summary"); - if (summaryElement != null + if (summaryElement is not null && string.IsNullOrWhiteSpace(summaryElement.Value)) { summaryElement.Remove(); @@ -363,7 +363,7 @@ public static void CleanAnalyzers(string filePath) XElement remarksElement = element.Element("Remarks"); - if (remarksElement != null + if (remarksElement is not null && string.IsNullOrWhiteSpace(remarksElement.Value)) { remarksElement.Remove(); @@ -371,7 +371,7 @@ public static void CleanAnalyzers(string filePath) XElement configurationElement = element.Element("Configuration"); - if (configurationElement != null + if (configurationElement is not null && string.IsNullOrWhiteSpace(configurationElement.Value)) { configurationElement.Remove(); @@ -379,7 +379,7 @@ public static void CleanAnalyzers(string filePath) XElement samplesElement = element.Element("Samples"); - if (samplesElement != null) + if (samplesElement is not null) { foreach (XElement sampleElement in samplesElement.Elements("Sample")) { @@ -393,7 +393,7 @@ public static void CleanAnalyzers(string filePath) continue; } - if (beforeElement != null) + if (beforeElement is not null) { string before = beforeElement.Value; @@ -413,7 +413,7 @@ public static void CleanAnalyzers(string filePath) XElement linksElement = element.Element("Links"); - if (linksElement != null) + if (linksElement is not null) { foreach (XElement linkElement in linksElement.Elements("Link")) { diff --git a/src/Tools/Metadata/RefactoringMetadata.cs b/src/Tools/Metadata/RefactoringMetadata.cs index 43028caac5..0ad130bb90 100644 --- a/src/Tools/Metadata/RefactoringMetadata.cs +++ b/src/Tools/Metadata/RefactoringMetadata.cs @@ -26,7 +26,7 @@ public class RefactoringMetadata IEnumerable samples, IEnumerable links) { - if (optionKey == null + if (optionKey is null && !isObsolete) { throw new ArgumentNullException(nameof(optionKey)); diff --git a/src/Tools/Metadata/XmlExtensions.cs b/src/Tools/Metadata/XmlExtensions.cs index 232a6b0379..ac5dcc440e 100644 --- a/src/Tools/Metadata/XmlExtensions.cs +++ b/src/Tools/Metadata/XmlExtensions.cs @@ -15,7 +15,7 @@ public static bool AttributeValueAsBooleanOrDefault(this XElement element, strin { XAttribute attribute = element.Attribute(attributeName); - if (attribute == null) + if (attribute is null) return defaultValue; return bool.Parse(attribute.Value); @@ -30,7 +30,7 @@ public static bool ElementValueAsBooleanOrDefault(this XElement element, string { XElement e = element.Element(elementName); - if (e == null) + if (e is null) return defaultValue; return bool.Parse(e.Value); diff --git a/src/Tools/MetadataGenerator/Program.cs b/src/Tools/MetadataGenerator/Program.cs index 3c943ddd37..0f6483b584 100644 --- a/src/Tools/MetadataGenerator/Program.cs +++ b/src/Tools/MetadataGenerator/Program.cs @@ -27,7 +27,7 @@ internal static class Program private static async Task Main(string[] args) { - if (args == null || args.Length == 0) + if (args is null || args.Length == 0) { #if DEBUG args = new[] { @"..\..\..\..\.." }; @@ -176,7 +176,7 @@ void WriteAnalyzerMarkdown(AnalyzerMetadata analyzer, IEnumerable<(string title, fileMustExists: false); foreach (AnalyzerOptionMetadata option in analyzer.Options - .Where(f => f.Id != null)) + .Where(f => f.Id is not null)) { WriteAllText( $@"..\docs\analyzers\{option.ParentId}{option.Id}.md", @@ -235,7 +235,7 @@ void UpdateChangeLog() ImmutableDictionary dic = allAnalyzers .Concat(allAnalyzers.SelectMany(f => f.OptionAnalyzers)) - .Where(f => f.Id != null) + .Where(f => f.Id is not null) .ToImmutableDictionary(f => f.Id, f => f); s = issueRegex.Replace(s, "([issue](https://github.com/JosefPihrt/Roslynator/issues/${issue}))"); diff --git a/src/Tools/MetadataGenerator/RoslynatorInfo.cs b/src/Tools/MetadataGenerator/RoslynatorInfo.cs index 08035523bd..29d6352d17 100644 --- a/src/Tools/MetadataGenerator/RoslynatorInfo.cs +++ b/src/Tools/MetadataGenerator/RoslynatorInfo.cs @@ -68,14 +68,14 @@ public async Task> GetAnalyzerFilesAsync(string identifier, { ISymbol diagnosticDescriptor = DiagnosticDescriptors.FirstOrDefault(f => f.Name == identifier); - if (diagnosticDescriptor == null) + if (diagnosticDescriptor is null) throw new InvalidOperationException($"Diagnostic descriptor symbol not found for identifier '{identifier}'."); IEnumerable referencedSymbols = await SymbolFinder.FindReferencesAsync(diagnosticDescriptor, Solution, cancellationToken).ConfigureAwait(false); ISymbol diagnosticIdentifier = DiagnosticIdentifiers.FirstOrDefault(f => f.Name == identifier); - if (diagnosticIdentifier == null) + if (diagnosticIdentifier is null) throw new InvalidOperationException($"Diagnostic identifier symbol not found for identifier '{identifier}'."); IEnumerable referencedSymbols2 = await SymbolFinder.FindReferencesAsync(diagnosticIdentifier, Solution, cancellationToken).ConfigureAwait(false); @@ -87,7 +87,7 @@ public async Task> GetRefactoringFilesAsync(string identifie { ISymbol symbol = RefactoringIdentifiers.FirstOrDefault(f => f.Name == identifier); - if (symbol == null) + if (symbol is null) throw new InvalidOperationException($"Refactoring identifier symbol not found for identifier '{identifier}'."); IEnumerable referencedSymbols = await SymbolFinder.FindReferencesAsync(symbol, Solution, cancellationToken).ConfigureAwait(false); @@ -99,7 +99,7 @@ public async Task> GetCompilerDiagnosticFilesAsync(string id { ISymbol symbol = CompilerDiagnosticIdentifiers.FirstOrDefault(f => f.Name == identifier); - if (symbol == null) + if (symbol is null) throw new InvalidOperationException($"Compiler diagnostic identifier symbol not found for identifier '{identifier}'."); IEnumerable referencedSymbols = await SymbolFinder.FindReferencesAsync(symbol, Solution, cancellationToken).ConfigureAwait(false); diff --git a/src/Tools/TestCodeGenerator/Program.cs b/src/Tools/TestCodeGenerator/Program.cs index 16fb31ea3d..096fb1daaf 100644 --- a/src/Tools/TestCodeGenerator/Program.cs +++ b/src/Tools/TestCodeGenerator/Program.cs @@ -9,108 +9,109 @@ using Roslynator.CodeGeneration.CSharp; using Roslynator.Metadata; -namespace Roslynator.CodeGeneration; - -internal static class Program +namespace Roslynator.CodeGeneration { - private static readonly Regex _analyzerIdRegex = new(@"^RCS\d+", RegexOptions.IgnoreCase); - private static readonly Regex _refactoringIdRegex = new(@"^RR\d+", RegexOptions.IgnoreCase); - private static readonly Regex _codeFixIdRegex = new(@"^(CS|VB)\d+", RegexOptions.IgnoreCase); - - private static void Main(string[] args) + internal static class Program { - string rootPath = args[0]; - - var metadata = new RoslynatorMetadata(rootPath); + private static readonly Regex _analyzerIdRegex = new(@"^RCS\d+", RegexOptions.IgnoreCase); + private static readonly Regex _refactoringIdRegex = new(@"^RR\d+", RegexOptions.IgnoreCase); + private static readonly Regex _codeFixIdRegex = new(@"^(CS|VB)\d+", RegexOptions.IgnoreCase); - ImmutableArray analyzers = metadata.Analyzers; - ImmutableArray refactorings = metadata.Refactorings; - ImmutableArray compilerDiagnostics = metadata.CompilerDiagnostics; - - foreach (string id in args.Skip(1)) + private static void Main(string[] args) { - if (_analyzerIdRegex.IsMatch(id)) - { - AnalyzerMetadata analyzer = analyzers.FirstOrDefault(f => string.Equals(f.Id, id, StringComparison.OrdinalIgnoreCase)); + string rootPath = args[0]; - if (analyzer == null) - { - Console.WriteLine($"Analyzer '{id}' not found"); - continue; - } + var metadata = new RoslynatorMetadata(rootPath); - string className = $"{analyzer.Id}{analyzer.Identifier}Tests"; + ImmutableArray analyzers = metadata.Analyzers; + ImmutableArray refactorings = metadata.Refactorings; + ImmutableArray compilerDiagnostics = metadata.CompilerDiagnostics; - WriteCompilationUnit( - $@"Tests\Analyzers.Tests\{className}.cs", - AnalyzerTestGenerator.Generate(analyzer, className), - autoGenerated: false, - normalizeWhitespace: false, - fileMustExist: false, - overwrite: false); - } - else if (_refactoringIdRegex.IsMatch(id)) + foreach (string id in args.Skip(1)) { - RefactoringMetadata refactoring = refactorings.FirstOrDefault(f => string.Equals(f.Id, id, StringComparison.OrdinalIgnoreCase)); - - if (refactoring == null) + if (_analyzerIdRegex.IsMatch(id)) { - Console.WriteLine($"Refactoring '{id}' not found"); - continue; + AnalyzerMetadata analyzer = analyzers.FirstOrDefault(f => string.Equals(f.Id, id, StringComparison.OrdinalIgnoreCase)); + + if (analyzer is null) + { + Console.WriteLine($"Analyzer '{id}' not found"); + continue; + } + + string className = $"{analyzer.Id}{analyzer.Identifier}Tests"; + + WriteCompilationUnit( + $@"Tests\Analyzers.Tests\{className}.cs", + AnalyzerTestGenerator.Generate(analyzer, className), + autoGenerated: false, + normalizeWhitespace: false, + fileMustExist: false, + overwrite: false); } - - string className = $"{refactoring.Id}{refactoring.Identifier}Tests"; - - WriteCompilationUnit( - $@"Tests\Refactorings.Tests\{className}.cs", - RefactoringTestGenerator.Generate(refactoring, className), - autoGenerated: false, - normalizeWhitespace: false, - fileMustExist: false, - overwrite: false); - } - else if (_codeFixIdRegex.IsMatch(id)) - { - CompilerDiagnosticMetadata compilerDiagnostic = compilerDiagnostics.FirstOrDefault(f => string.Equals(f.Id, id, StringComparison.OrdinalIgnoreCase)); - - if (compilerDiagnostic == null) + else if (_refactoringIdRegex.IsMatch(id)) { - Console.WriteLine($"Compiler diagnostic '{id}' not found"); - continue; + RefactoringMetadata refactoring = refactorings.FirstOrDefault(f => string.Equals(f.Id, id, StringComparison.OrdinalIgnoreCase)); + + if (refactoring is null) + { + Console.WriteLine($"Refactoring '{id}' not found"); + continue; + } + + string className = $"{refactoring.Id}{refactoring.Identifier}Tests"; + + WriteCompilationUnit( + $@"Tests\Refactorings.Tests\{className}.cs", + RefactoringTestGenerator.Generate(refactoring, className), + autoGenerated: false, + normalizeWhitespace: false, + fileMustExist: false, + overwrite: false); + } + else if (_codeFixIdRegex.IsMatch(id)) + { + CompilerDiagnosticMetadata compilerDiagnostic = compilerDiagnostics.FirstOrDefault(f => string.Equals(f.Id, id, StringComparison.OrdinalIgnoreCase)); + + if (compilerDiagnostic is null) + { + Console.WriteLine($"Compiler diagnostic '{id}' not found"); + continue; + } + + string className = $"{compilerDiagnostic.Id}{compilerDiagnostic.Identifier}Tests"; + + WriteCompilationUnit( + $@"Tests\CodeFixes.Tests\{className}.cs", + CodeFixTestGenerator.Generate(compilerDiagnostic, className), + autoGenerated: false, + normalizeWhitespace: false, + fileMustExist: false, + overwrite: false); + } + else + { + Console.WriteLine($"Id '{id}' not recognized"); } - - string className = $"{compilerDiagnostic.Id}{compilerDiagnostic.Identifier}Tests"; - - WriteCompilationUnit( - $@"Tests\CodeFixes.Tests\{className}.cs", - CodeFixTestGenerator.Generate(compilerDiagnostic, className), - autoGenerated: false, - normalizeWhitespace: false, - fileMustExist: false, - overwrite: false); } - else + + void WriteCompilationUnit( + string path, + CompilationUnitSyntax compilationUnit, + bool autoGenerated = true, + bool normalizeWhitespace = true, + bool fileMustExist = true, + bool overwrite = true) { - Console.WriteLine($"Id '{id}' not recognized"); + CodeGenerationHelpers.WriteCompilationUnit( + path: Path.Combine(rootPath, path), + compilationUnit: compilationUnit, + banner: CodeGenerationHelpers.CopyrightBanner, + autoGenerated: autoGenerated, + normalizeWhitespace: normalizeWhitespace, + fileMustExist: fileMustExist, + overwrite: overwrite); } } - - void WriteCompilationUnit( - string path, - CompilationUnitSyntax compilationUnit, - bool autoGenerated = true, - bool normalizeWhitespace = true, - bool fileMustExist = true, - bool overwrite = true) - { - CodeGenerationHelpers.WriteCompilationUnit( - path: Path.Combine(rootPath, path), - compilationUnit: compilationUnit, - banner: CodeGenerationHelpers.CopyrightBanner, - autoGenerated: autoGenerated, - normalizeWhitespace: normalizeWhitespace, - fileMustExist: fileMustExist, - overwrite: overwrite); - } } } diff --git a/src/Workspaces.Common/CSharp/CodeActionFactory.cs b/src/Workspaces.Common/CSharp/CodeActionFactory.cs index 393ea5ca2c..dc815b8021 100644 --- a/src/Workspaces.Common/CSharp/CodeActionFactory.cs +++ b/src/Workspaces.Common/CSharp/CodeActionFactory.cs @@ -6,186 +6,187 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Roslynator.CSharp; - -internal static class CodeActionFactory +namespace Roslynator.CSharp { - public static CodeAction ChangeTypeToVar( - Document document, - TypeSyntax type, - string title = null, - string equivalenceKey = null) + internal static class CodeActionFactory { - return CodeAction.Create( - title ?? "Use implicit type", - ct => DocumentRefactorings.ChangeTypeToVarAsync(document, type, ct), - equivalenceKey); - } + public static CodeAction ChangeTypeToVar( + Document document, + TypeSyntax type, + string title = null, + string equivalenceKey = null) + { + return CodeAction.Create( + title ?? "Use implicit type", + ct => DocumentRefactorings.ChangeTypeToVarAsync(document, type, ct), + equivalenceKey); + } - public static CodeAction ChangeTypeToVar( - Document document, - TupleExpressionSyntax tupleExpression, - string title = null, - string equivalenceKey = null) - { - return CodeAction.Create( - title ?? "Use implicit type", - ct => DocumentRefactorings.ChangeTypeToVarAsync(document, tupleExpression, ct), - equivalenceKey); - } + public static CodeAction ChangeTypeToVar( + Document document, + TupleExpressionSyntax tupleExpression, + string title = null, + string equivalenceKey = null) + { + return CodeAction.Create( + title ?? "Use implicit type", + ct => DocumentRefactorings.ChangeTypeToVarAsync(document, tupleExpression, ct), + equivalenceKey); + } - public static CodeAction UseExplicitType( - Document document, - TypeSyntax type, - ITypeSymbol newTypeSymbol, - SemanticModel semanticModel, - string equivalenceKey = null) - { - return ChangeType(document, type, newTypeSymbol, semanticModel, title: "Use explicit type", equivalenceKey: equivalenceKey); - } + public static CodeAction UseExplicitType( + Document document, + TypeSyntax type, + ITypeSymbol newTypeSymbol, + SemanticModel semanticModel, + string equivalenceKey = null) + { + return ChangeType(document, type, newTypeSymbol, semanticModel, title: "Use explicit type", equivalenceKey: equivalenceKey); + } - public static CodeAction ChangeType( - Document document, - TypeSyntax type, - ITypeSymbol newTypeSymbol, - SemanticModel semanticModel, - string title = null, - string equivalenceKey = null) - { - if (title == null) + public static CodeAction ChangeType( + Document document, + TypeSyntax type, + ITypeSymbol newTypeSymbol, + SemanticModel semanticModel, + string title = null, + string equivalenceKey = null) { - SymbolDisplayFormat format = GetSymbolDisplayFormat(type, newTypeSymbol, semanticModel); + if (title is null) + { + SymbolDisplayFormat format = GetSymbolDisplayFormat(type, newTypeSymbol, semanticModel); + + string newTypeName = SymbolDisplay.ToMinimalDisplayString(newTypeSymbol, semanticModel, type.SpanStart, format); + + if ((type.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.ReturnType == type) + || (type.Parent is LocalFunctionStatementSyntax localFunction && localFunction.ReturnType == type)) + { + title = $"Change return type to '{newTypeName}'"; + } + else + { + title = $"Change type to '{newTypeName}'"; + } + } - string newTypeName = SymbolDisplay.ToMinimalDisplayString(newTypeSymbol, semanticModel, type.SpanStart, format); + return ChangeType(document, type, newTypeSymbol, title, equivalenceKey); + } - if ((type.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.ReturnType == type) - || (type.Parent is LocalFunctionStatementSyntax localFunction && localFunction.ReturnType == type)) + private static CodeAction ChangeType( + Document document, + TypeSyntax type, + ITypeSymbol newTypeSymbol, + string title, + string equivalenceKey = null) + { + return CodeAction.Create( + title, + ct => DocumentRefactorings.ChangeTypeAsync(document, type, newTypeSymbol, ct), + equivalenceKey); + } + + private static SymbolDisplayFormat GetSymbolDisplayFormat( + ExpressionSyntax expression, + ITypeSymbol newTypeSymbol, + SemanticModel semanticModel) + { + if (newTypeSymbol.NullableAnnotation == NullableAnnotation.Annotated + && (semanticModel.GetNullableContext(expression.SpanStart) & NullableContext.WarningsEnabled) != 0) { - title = $"Change return type to '{newTypeName}'"; + return SymbolDisplayFormats.FullName; } else { - title = $"Change type to '{newTypeName}'"; + return SymbolDisplayFormats.FullName_WithoutNullableReferenceTypeModifier; } } - return ChangeType(document, type, newTypeSymbol, title, equivalenceKey); - } - - private static CodeAction ChangeType( - Document document, - TypeSyntax type, - ITypeSymbol newTypeSymbol, - string title, - string equivalenceKey = null) - { - return CodeAction.Create( - title, - ct => DocumentRefactorings.ChangeTypeAsync(document, type, newTypeSymbol, ct), - equivalenceKey); - } - - private static SymbolDisplayFormat GetSymbolDisplayFormat( - ExpressionSyntax expression, - ITypeSymbol newTypeSymbol, - SemanticModel semanticModel) - { - if (newTypeSymbol.NullableAnnotation == NullableAnnotation.Annotated - && (semanticModel.GetNullableContext(expression.SpanStart) & NullableContext.WarningsEnabled) != 0) - { - return SymbolDisplayFormats.FullName; - } - else + public static CodeAction AddExplicitCast( + Document document, + ExpressionSyntax expression, + ITypeSymbol destinationType, + SemanticModel semanticModel, + string title = null, + string equivalenceKey = null) { - return SymbolDisplayFormats.FullName_WithoutNullableReferenceTypeModifier; - } - } - - public static CodeAction AddExplicitCast( - Document document, - ExpressionSyntax expression, - ITypeSymbol destinationType, - SemanticModel semanticModel, - string title = null, - string equivalenceKey = null) - { - SymbolDisplayFormat format = GetSymbolDisplayFormat(expression, destinationType, semanticModel); + SymbolDisplayFormat format = GetSymbolDisplayFormat(expression, destinationType, semanticModel); - string typeName = SymbolDisplay.ToMinimalDisplayString(destinationType, semanticModel, expression.SpanStart, format); + string typeName = SymbolDisplay.ToMinimalDisplayString(destinationType, semanticModel, expression.SpanStart, format); - TypeSyntax newType = ParseTypeName(typeName); + TypeSyntax newType = ParseTypeName(typeName); - return CodeAction.Create( - title ?? "Add explicit cast", - ct => DocumentRefactorings.AddExplicitCastAsync(document, expression, newType, ct), - equivalenceKey); - } - - public static CodeAction RemoveMemberDeclaration( - Document document, - MemberDeclarationSyntax memberDeclaration, - string title = null, - string equivalenceKey = null) - { - return CodeAction.Create( - title ?? $"Remove {CSharpFacts.GetTitle(memberDeclaration)}", - ct => document.RemoveMemberAsync(memberDeclaration, ct), - equivalenceKey); - } + return CodeAction.Create( + title ?? "Add explicit cast", + ct => DocumentRefactorings.AddExplicitCastAsync(document, expression, newType, ct), + equivalenceKey); + } - public static CodeAction RemoveStatement( - Document document, - StatementSyntax statement, - string title = null, - string equivalenceKey = null) - { - return CodeAction.Create( - title ?? $"Remove {CSharpFacts.GetTitle(statement)}", - ct => document.RemoveStatementAsync(statement, ct), - equivalenceKey); - } + public static CodeAction RemoveMemberDeclaration( + Document document, + MemberDeclarationSyntax memberDeclaration, + string title = null, + string equivalenceKey = null) + { + return CodeAction.Create( + title ?? $"Remove {CSharpFacts.GetTitle(memberDeclaration)}", + ct => document.RemoveMemberAsync(memberDeclaration, ct), + equivalenceKey); + } - public static CodeAction ReplaceNullWithDefaultValue( - Document document, - ExpressionSyntax expression, - ITypeSymbol typeSymbol, - string title = null, - string equivalenceKey = null) - { - return CodeAction.Create( - title ?? "Replace 'null' with default value", - ct => - { - ExpressionSyntax defaultValue = typeSymbol - .GetDefaultValueSyntax(document.GetDefaultSyntaxOptions()) - .WithTriviaFrom(expression); + public static CodeAction RemoveStatement( + Document document, + StatementSyntax statement, + string title = null, + string equivalenceKey = null) + { + return CodeAction.Create( + title ?? $"Remove {CSharpFacts.GetTitle(statement)}", + ct => document.RemoveStatementAsync(statement, ct), + equivalenceKey); + } - return document.ReplaceNodeAsync(expression, defaultValue, ct); - }, - equivalenceKey); - } + public static CodeAction ReplaceNullWithDefaultValue( + Document document, + ExpressionSyntax expression, + ITypeSymbol typeSymbol, + string title = null, + string equivalenceKey = null) + { + return CodeAction.Create( + title ?? "Replace 'null' with default value", + ct => + { + ExpressionSyntax defaultValue = typeSymbol + .GetDefaultValueSyntax(document.GetDefaultSyntaxOptions()) + .WithTriviaFrom(expression); + + return document.ReplaceNodeAsync(expression, defaultValue, ct); + }, + equivalenceKey); + } - public static CodeAction RemoveAsyncAwait( - Document document, - SyntaxToken asyncKeyword, - string title = null, - string equivalenceKey = null) - { - return CodeAction.Create( - title ?? "Remove async/await", - ct => DocumentRefactorings.RemoveAsyncAwaitAsync(document, asyncKeyword, ct), - equivalenceKey); - } + public static CodeAction RemoveAsyncAwait( + Document document, + SyntaxToken asyncKeyword, + string title = null, + string equivalenceKey = null) + { + return CodeAction.Create( + title ?? "Remove async/await", + ct => DocumentRefactorings.RemoveAsyncAwaitAsync(document, asyncKeyword, ct), + equivalenceKey); + } - public static CodeAction RemoveParentheses( - Document document, - ParenthesizedExpressionSyntax parenthesizedExpression, - string title = null, - string equivalenceKey = null) - { - return CodeAction.Create( - title ?? "Remove parentheses", - ct => DocumentRefactorings.RemoveParenthesesAsync(document, parenthesizedExpression, ct), - equivalenceKey); + public static CodeAction RemoveParentheses( + Document document, + ParenthesizedExpressionSyntax parenthesizedExpression, + string title = null, + string equivalenceKey = null) + { + return CodeAction.Create( + title ?? "Remove parentheses", + ct => DocumentRefactorings.RemoveParenthesesAsync(document, parenthesizedExpression, ct), + equivalenceKey); + } } } diff --git a/src/Workspaces.Common/CSharp/CodeFixes/ModifiersCodeFixRegistrator.cs b/src/Workspaces.Common/CSharp/CodeFixes/ModifiersCodeFixRegistrator.cs index 371c6dbb5f..9debafa95c 100644 --- a/src/Workspaces.Common/CSharp/CodeFixes/ModifiersCodeFixRegistrator.cs +++ b/src/Workspaces.Common/CSharp/CodeFixes/ModifiersCodeFixRegistrator.cs @@ -12,250 +12,282 @@ using Roslynator.CSharp.Refactorings; using static Microsoft.CodeAnalysis.CSharp.SyntaxFacts; -namespace Roslynator.CSharp.CodeFixes; - -internal static class ModifiersCodeFixRegistrator +namespace Roslynator.CSharp.CodeFixes { - public static void AddModifier( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - SyntaxKind modifierKind, - string title = null, - string additionalKey = null, - IComparer comparer = null) + internal static class ModifiersCodeFixRegistrator { - AddModifier(context, context.Document, diagnostic, node, modifierKind, title, additionalKey, comparer); - } + public static void AddModifier( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + SyntaxKind modifierKind, + string title = null, + string additionalKey = null, + IComparer comparer = null) + { + AddModifier(context, context.Document, diagnostic, node, modifierKind, title, additionalKey, comparer); + } - public static void AddModifier( - CodeFixContext context, - Document document, - Diagnostic diagnostic, - SyntaxNode node, - SyntaxKind modifierKind, - string title = null, - string additionalKey = null, - IComparer comparer = null) - { - CodeAction codeAction = CodeAction.Create( - title ?? GetAddModifierTitle(modifierKind, node), - ct => AddModifierAsync(document, node, modifierKind, comparer, ct), - GetEquivalenceKey(diagnostic, additionalKey)); + public static void AddModifier( + CodeFixContext context, + Document document, + Diagnostic diagnostic, + SyntaxNode node, + SyntaxKind modifierKind, + string title = null, + string additionalKey = null, + IComparer comparer = null) + { + CodeAction codeAction = CodeAction.Create( + title ?? GetAddModifierTitle(modifierKind, node), + ct => AddModifierAsync(document, node, modifierKind, comparer, ct), + GetEquivalenceKey(diagnostic, additionalKey)); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); + } - private static Task AddModifierAsync( - Document document, - TNode node, - SyntaxKind modifierKind, - IComparer comparer = null, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - TNode newNode = AddModifier(node, modifierKind, comparer); + private static Task AddModifierAsync( + Document document, + TNode node, + SyntaxKind modifierKind, + IComparer comparer = null, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + TNode newNode = AddModifier(node, modifierKind, comparer); - return document.ReplaceNodeAsync(node, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(node, newNode, cancellationToken); + } - private static TNode AddModifier( - TNode node, - SyntaxKind modifierKind, - IComparer comparer = null) where TNode : SyntaxNode - { - switch (modifierKind) + private static TNode AddModifier( + TNode node, + SyntaxKind modifierKind, + IComparer comparer = null) where TNode : SyntaxNode { - case SyntaxKind.AbstractKeyword: - { - node = node.RemoveModifiers(SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword); - break; - } - case SyntaxKind.VirtualKeyword: - { - node = node.RemoveModifiers(SyntaxKind.AbstractKeyword, SyntaxKind.OverrideKeyword); - break; - } - case SyntaxKind.OverrideKeyword: + switch (modifierKind) + { + case SyntaxKind.AbstractKeyword: + { + node = node.RemoveModifiers(SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword); + break; + } + case SyntaxKind.VirtualKeyword: + { + node = node.RemoveModifiers(SyntaxKind.AbstractKeyword, SyntaxKind.OverrideKeyword); + break; + } + case SyntaxKind.OverrideKeyword: + { + node = node.RemoveModifiers(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword); + break; + } + case SyntaxKind.StaticKeyword: + { + if (node.IsKind(SyntaxKind.ConstructorDeclaration)) + node = SyntaxAccessibility.WithoutExplicitAccessibility(node); + + node = node.RemoveModifier(SyntaxKind.SealedKeyword); + + break; + } + } + + return node.InsertModifier(modifierKind, comparer); + } + + public static void AddModifier( + CodeFixContext context, + Diagnostic diagnostic, + IEnumerable nodes, + SyntaxKind modifierKind, + string title = null, + string additionalKey = null, + IComparer comparer = null) where TNode : SyntaxNode + { + if (nodes is IList list) + { + if (list.Count == 0) + return; + + if (list.Count == 1) { - node = node.RemoveModifiers(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword); - break; + AddModifier(context, diagnostic, list[0], modifierKind, title, additionalKey, comparer); + return; } - case SyntaxKind.StaticKeyword: - { - if (node.IsKind(SyntaxKind.ConstructorDeclaration)) - node = SyntaxAccessibility.WithoutExplicitAccessibility(node); + } - node = node.RemoveModifier(SyntaxKind.SealedKeyword); + CodeAction codeAction = CodeAction.Create( + title ?? GetAddModifierTitle(modifierKind), + ct => + { + return context.Solution().ReplaceNodesAsync( + nodes, + (f, _) => AddModifier(f, modifierKind, comparer), + ct); + }, + GetEquivalenceKey(diagnostic, additionalKey)); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); } - return node.InsertModifier(modifierKind, comparer); - } - - public static void AddModifier( - CodeFixContext context, - Diagnostic diagnostic, - IEnumerable nodes, - SyntaxKind modifierKind, - string title = null, - string additionalKey = null, - IComparer comparer = null) where TNode : SyntaxNode - { - if (nodes is IList list) + public static void RemoveModifier( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + SyntaxKind modifierKind, + string title = null, + string additionalKey = null) { - if (list.Count == 0) - return; + Document document = context.Document; - if (list.Count == 1) - { - AddModifier(context, diagnostic, list[0], modifierKind, title, additionalKey, comparer); - return; - } + CodeAction codeAction = CodeAction.Create( + title ?? GetRemoveModifierTitle(modifierKind), + ct => RemoveModifierAsync(document, node, modifierKind, ct), + GetEquivalenceKey(diagnostic, additionalKey)); + + context.RegisterCodeFix(codeAction, diagnostic); } - CodeAction codeAction = CodeAction.Create( - title ?? GetAddModifierTitle(modifierKind), - ct => - { - return context.Solution().ReplaceNodesAsync( - nodes, - (f, _) => AddModifier(f, modifierKind, comparer), - ct); - }, - GetEquivalenceKey(diagnostic, additionalKey)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + public static void RemoveModifier( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + SyntaxToken modifier, + string title = null, + string additionalKey = null) + { + SyntaxKind kind = modifier.Kind(); - public static void RemoveModifier( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - SyntaxKind modifierKind, - string title = null, - string additionalKey = null) - { - Document document = context.Document; + Document document = context.Document; - CodeAction codeAction = CodeAction.Create( - title ?? GetRemoveModifierTitle(modifierKind), - ct => RemoveModifierAsync(document, node, modifierKind, ct), - GetEquivalenceKey(diagnostic, additionalKey)); + CodeAction codeAction = CodeAction.Create( + title ?? GetRemoveModifierTitle(kind), + ct => RemoveModifierAsync(document, node, modifier, ct), + GetEquivalenceKey(diagnostic, additionalKey)); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); + } - public static void RemoveModifier( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - SyntaxToken modifier, - string title = null, - string additionalKey = null) - { - SyntaxKind kind = modifier.Kind(); + private static Task RemoveModifierAsync( + Document document, + TNode node, + SyntaxKind modifierKind, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + TNode newNode = ModifierList.Remove(node, modifierKind); - Document document = context.Document; + return document.ReplaceNodeAsync(node, newNode, cancellationToken); + } - CodeAction codeAction = CodeAction.Create( - title ?? GetRemoveModifierTitle(kind), - ct => RemoveModifierAsync(document, node, modifier, ct), - GetEquivalenceKey(diagnostic, additionalKey)); + private static Task RemoveModifierAsync( + Document document, + TNode node, + SyntaxToken modifier, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + TNode newNode = ModifierList.Remove(node, modifier); - context.RegisterCodeFix(codeAction, diagnostic); - } + return document.ReplaceNodeAsync(node, newNode, cancellationToken); + } - private static Task RemoveModifierAsync( - Document document, - TNode node, - SyntaxKind modifierKind, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - TNode newNode = ModifierList.Remove(node, modifierKind); + public static void RemoveModifier( + CodeFixContext context, + Diagnostic diagnostic, + IEnumerable nodes, + SyntaxKind modifierKind, + string title = null, + string additionalKey = null) where TNode : SyntaxNode + { + if (nodes is IList list) + { + if (list.Count == 0) + return; - return document.ReplaceNodeAsync(node, newNode, cancellationToken); - } + if (list.Count == 1) + { + RemoveModifier(context, diagnostic, list[0], modifierKind, title, additionalKey); + return; + } + } - private static Task RemoveModifierAsync( - Document document, - TNode node, - SyntaxToken modifier, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - TNode newNode = ModifierList.Remove(node, modifier); + CodeAction codeAction = CodeAction.Create( + title ?? GetRemoveModifierTitle(modifierKind), + ct => + { + return context.Solution().ReplaceNodesAsync( + nodes, + (f, _) => ModifierList.Remove(f, modifierKind), + ct); + }, + GetEquivalenceKey(diagnostic, additionalKey)); - return document.ReplaceNodeAsync(node, newNode, cancellationToken); - } + context.RegisterCodeFix(codeAction, diagnostic); + } - public static void RemoveModifier( - CodeFixContext context, - Diagnostic diagnostic, - IEnumerable nodes, - SyntaxKind modifierKind, - string title = null, - string additionalKey = null) where TNode : SyntaxNode - { - if (nodes is IList list) + public static void RemoveModifiers( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + Func predicate, + string additionalKey = null) { - if (list.Count == 0) - return; + SyntaxTokenList modifiers = SyntaxInfo.ModifierListInfo(node).Modifiers; - if (list.Count == 1) - { - RemoveModifier(context, diagnostic, list[0], modifierKind, title, additionalKey); - return; - } + RemoveModifiers(context, diagnostic, node, modifiers, predicate, additionalKey); } - CodeAction codeAction = CodeAction.Create( - title ?? GetRemoveModifierTitle(modifierKind), - ct => + public static void RemoveModifiers( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + SyntaxTokenList modifiers, + Func predicate, + string additionalKey = null) + { + List indexes = null; + + for (int i = 0; i < modifiers.Count; i++) { - return context.Solution().ReplaceNodesAsync( - nodes, - (f, _) => ModifierList.Remove(f, modifierKind), - ct); - }, - GetEquivalenceKey(diagnostic, additionalKey)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + if (predicate(modifiers[i])) + (indexes ??= new List()).Add(i); + } - public static void RemoveModifiers( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - Func predicate, - string additionalKey = null) - { - SyntaxTokenList modifiers = SyntaxInfo.ModifierListInfo(node).Modifiers; + if (indexes is not null) + { + if (indexes.Count == 1) + { + RemoveModifier(context, diagnostic, node, modifiers[indexes[0]], additionalKey: additionalKey); + } + else + { + CodeAction codeAction = CodeAction.Create( + "Remove modifiers", + ct => + { + SyntaxNode newNode = node; - RemoveModifiers(context, diagnostic, node, modifiers, predicate, additionalKey); - } + for (int i = indexes.Count - 1; i >= 0; i--) + newNode = ModifierList.RemoveAt(newNode, indexes[i]); - public static void RemoveModifiers( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - SyntaxTokenList modifiers, - Func predicate, - string additionalKey = null) - { - List indexes = null; + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }, + GetEquivalenceKey(diagnostic, additionalKey)); - for (int i = 0; i < modifiers.Count; i++) - { - if (predicate(modifiers[i])) - (indexes ??= new List()).Add(i); + context.RegisterCodeFix(codeAction, diagnostic); + } + } } - if (indexes != null) + public static void RemoveModifiers( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + string additionalKey = null) { - if (indexes.Count == 1) + SyntaxToken modifier = SyntaxInfo.ModifierListInfo(node).Modifiers.SingleOrDefault(shouldThrow: false); + + if (modifier != default) { - RemoveModifier(context, diagnostic, node, modifiers[indexes[0]], additionalKey: additionalKey); + RemoveModifier(context, diagnostic, node, modifier, additionalKey); } else { @@ -263,10 +295,7 @@ internal static class ModifiersCodeFixRegistrator "Remove modifiers", ct => { - SyntaxNode newNode = node; - - for (int i = indexes.Count - 1; i >= 0; i--) - newNode = ModifierList.RemoveAt(newNode, indexes[i]); + SyntaxNode newNode = ModifierList.RemoveAll(node); return context.Document.ReplaceNodeAsync(node, newNode, ct); }, @@ -275,163 +304,135 @@ internal static class ModifiersCodeFixRegistrator context.RegisterCodeFix(codeAction, diagnostic); } } - } - - public static void RemoveModifiers( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - string additionalKey = null) - { - SyntaxToken modifier = SyntaxInfo.ModifierListInfo(node).Modifiers.SingleOrDefault(shouldThrow: false); - if (modifier != default) + public static void RemoveAccessibility( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + string additionalKey = null) { - RemoveModifier(context, diagnostic, node, modifier, additionalKey); - } - else - { - CodeAction codeAction = CodeAction.Create( - "Remove modifiers", - ct => - { - SyntaxNode newNode = ModifierList.RemoveAll(node); + var accessModifier = default(SyntaxToken); - return context.Document.ReplaceNodeAsync(node, newNode, ct); - }, - GetEquivalenceKey(diagnostic, additionalKey)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - } - - public static void RemoveAccessibility( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - string additionalKey = null) - { - var accessModifier = default(SyntaxToken); - - foreach (SyntaxToken modifier in SyntaxInfo.ModifierListInfo(node).Modifiers) - { - if (IsAccessibilityModifier(modifier.Kind())) + foreach (SyntaxToken modifier in SyntaxInfo.ModifierListInfo(node).Modifiers) { - if (IsAccessibilityModifier(accessModifier.Kind())) + if (IsAccessibilityModifier(modifier.Kind())) { - accessModifier = default; - break; - } - else - { - accessModifier = modifier; + if (IsAccessibilityModifier(accessModifier.Kind())) + { + accessModifier = default; + break; + } + else + { + accessModifier = modifier; + } } } - } - if (IsAccessibilityModifier(accessModifier.Kind())) - { - RemoveModifier(context, diagnostic, node, accessModifier, additionalKey: additionalKey); + if (IsAccessibilityModifier(accessModifier.Kind())) + { + RemoveModifier(context, diagnostic, node, accessModifier, additionalKey: additionalKey); + } + else + { + CodeAction codeAction = CodeAction.Create( + "Remove access modifiers", + ct => + { + SyntaxNode newNode = SyntaxAccessibility.WithoutExplicitAccessibility(node); + + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }, + GetEquivalenceKey(diagnostic, additionalKey)); + + context.RegisterCodeFix(codeAction, diagnostic); + } } - else + + public static void MoveModifier( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + SyntaxToken modifier, + string title = null, + string additionalKey = null, + IComparer comparer = null) { + Document document = context.Document; + + SyntaxKind kind = modifier.Kind(); + CodeAction codeAction = CodeAction.Create( - "Remove access modifiers", + title ?? GetRemoveModifierTitle(kind), ct => { - SyntaxNode newNode = SyntaxAccessibility.WithoutExplicitAccessibility(node); + SyntaxNode newNode = node + .RemoveModifier(modifier) + .InsertModifier(kind, comparer); - return context.Document.ReplaceNodeAsync(node, newNode, ct); + return document.ReplaceNodeAsync(node, newNode, ct); }, GetEquivalenceKey(diagnostic, additionalKey)); context.RegisterCodeFix(codeAction, diagnostic); } - } - public static void MoveModifier( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - SyntaxToken modifier, - string title = null, - string additionalKey = null, - IComparer comparer = null) - { - Document document = context.Document; - - SyntaxKind kind = modifier.Kind(); - - CodeAction codeAction = CodeAction.Create( - title ?? GetRemoveModifierTitle(kind), - ct => - { - SyntaxNode newNode = node - .RemoveModifier(modifier) - .InsertModifier(kind, comparer); - - return document.ReplaceNodeAsync(node, newNode, ct); - }, - GetEquivalenceKey(diagnostic, additionalKey)); + public static void ChangeAccessibility( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + IEnumerable accessibilities) + { + foreach (Accessibility accessibility in accessibilities) + ChangeAccessibility(context, diagnostic, node, accessibility); + } - context.RegisterCodeFix(codeAction, diagnostic); - } + public static void ChangeAccessibility( + CodeFixContext context, + Diagnostic diagnostic, + SyntaxNode node, + Accessibility accessibility) + { + if (!SyntaxAccessibility.IsValidAccessibility(node, accessibility)) + return; - public static void ChangeAccessibility( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - IEnumerable accessibilities) - { - foreach (Accessibility accessibility in accessibilities) - ChangeAccessibility(context, diagnostic, node, accessibility); - } + CodeAction codeAction = CodeAction.Create( + $"Change accessibility to '{GetText(accessibility)}'", + ct => ChangeAccessibilityRefactoring.RefactorAsync(context.Document, node, accessibility, ct), + GetEquivalenceKey(diagnostic, accessibility.ToString())); - public static void ChangeAccessibility( - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode node, - Accessibility accessibility) - { - if (!SyntaxAccessibility.IsValidAccessibility(node, accessibility)) - return; + context.RegisterCodeFix(codeAction, diagnostic); + } - CodeAction codeAction = CodeAction.Create( - $"Change accessibility to '{GetText(accessibility)}'", - ct => ChangeAccessibilityRefactoring.RefactorAsync(context.Document, node, accessibility, ct), - GetEquivalenceKey(diagnostic, accessibility.ToString())); + private static string GetEquivalenceKey(Diagnostic diagnostic, string additionalKey) + { + return EquivalenceKey.Create(diagnostic, additionalKey); + } - context.RegisterCodeFix(codeAction, diagnostic); - } + private static string GetAddModifierTitle(SyntaxKind modifierKind) + { + return $"Add modifier '{GetText(modifierKind)}'"; + } - private static string GetEquivalenceKey(Diagnostic diagnostic, string additionalKey) - { - return EquivalenceKey.Create(diagnostic, additionalKey); - } + private static string GetAddModifierTitle(SyntaxKind modifierKind, SyntaxNode node) + { + switch (modifierKind) + { + case SyntaxKind.StaticKeyword: + case SyntaxKind.VirtualKeyword: + case SyntaxKind.AbstractKeyword: + case SyntaxKind.ReadOnlyKeyword: + case SyntaxKind.AsyncKeyword: + case SyntaxKind.SealedKeyword: + return $"Make {CSharpFacts.GetTitle(node)} {CSharpFacts.GetTitle(modifierKind)}"; + } - private static string GetAddModifierTitle(SyntaxKind modifierKind) - { - return $"Add modifier '{GetText(modifierKind)}'"; - } + return GetAddModifierTitle(modifierKind); + } - private static string GetAddModifierTitle(SyntaxKind modifierKind, SyntaxNode node) - { - switch (modifierKind) + internal static string GetRemoveModifierTitle(SyntaxKind modifierKind) { - case SyntaxKind.StaticKeyword: - case SyntaxKind.VirtualKeyword: - case SyntaxKind.AbstractKeyword: - case SyntaxKind.ReadOnlyKeyword: - case SyntaxKind.AsyncKeyword: - case SyntaxKind.SealedKeyword: - return $"Make {CSharpFacts.GetTitle(node)} {CSharpFacts.GetTitle(modifierKind)}"; + return $"Remove modifier '{GetText(modifierKind)}'"; } - - return GetAddModifierTitle(modifierKind); - } - - internal static string GetRemoveModifierTitle(SyntaxKind modifierKind) - { - return $"Remove modifier '{GetText(modifierKind)}'"; } } diff --git a/src/Workspaces.Common/CSharp/DocumentRefactoringFactory.cs b/src/Workspaces.Common/CSharp/DocumentRefactoringFactory.cs index f28d3881a6..02530ac76c 100644 --- a/src/Workspaces.Common/CSharp/DocumentRefactoringFactory.cs +++ b/src/Workspaces.Common/CSharp/DocumentRefactoringFactory.cs @@ -7,76 +7,77 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp; - -internal static class DocumentRefactoringFactory +namespace Roslynator.CSharp { - public static Func> ChangeTypeAndAddAwait( - Document document, - VariableDeclarationSyntax variableDeclaration, - VariableDeclaratorSyntax variableDeclarator, - ITypeSymbol newTypeSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) + internal static class DocumentRefactoringFactory { - if (!newTypeSymbol.OriginalDefinition.EqualsOrInheritsFromTaskOfT()) - return default; + public static Func> ChangeTypeAndAddAwait( + Document document, + VariableDeclarationSyntax variableDeclaration, + VariableDeclaratorSyntax variableDeclarator, + ITypeSymbol newTypeSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + if (!newTypeSymbol.OriginalDefinition.EqualsOrInheritsFromTaskOfT()) + return default; - if (semanticModel.GetEnclosingSymbol(variableDeclaration.SpanStart, cancellationToken) is not IMethodSymbol methodSymbol) - return default; + if (semanticModel.GetEnclosingSymbol(variableDeclaration.SpanStart, cancellationToken) is not IMethodSymbol methodSymbol) + return default; - if (!methodSymbol.MethodKind.Is(MethodKind.Ordinary, MethodKind.LocalFunction)) - return default; + if (!methodSymbol.MethodKind.Is(MethodKind.Ordinary, MethodKind.LocalFunction)) + return default; - SyntaxNode containingMethod = GetContainingMethod(); + SyntaxNode containingMethod = GetContainingMethod(); - if (containingMethod == null) - return default; + if (containingMethod is null) + return default; - SyntaxNode bodyOrExpressionBody = GetBodyOrExpressionBody(); + SyntaxNode bodyOrExpressionBody = GetBodyOrExpressionBody(); - if (bodyOrExpressionBody == null) - return default; + if (bodyOrExpressionBody is null) + return default; - foreach (SyntaxNode descendant in bodyOrExpressionBody.DescendantNodes()) - { - if (descendant is ReturnStatementSyntax returnStatement - && returnStatement - .Expression? - .WalkDownParentheses() - .IsKind(SyntaxKind.AwaitExpression) == false) + foreach (SyntaxNode descendant in bodyOrExpressionBody.DescendantNodes()) { - return default; + if (descendant is ReturnStatementSyntax returnStatement + && returnStatement + .Expression? + .WalkDownParentheses() + .IsKind(SyntaxKind.AwaitExpression) == false) + { + return default; + } } - } - ITypeSymbol typeArgument = ((INamedTypeSymbol)newTypeSymbol).TypeArguments[0]; + ITypeSymbol typeArgument = ((INamedTypeSymbol)newTypeSymbol).TypeArguments[0]; - return ct => DocumentRefactorings.ChangeTypeAndAddAwaitAsync(document, variableDeclaration, variableDeclarator, containingMethod, typeArgument, ct); + return ct => DocumentRefactorings.ChangeTypeAndAddAwaitAsync(document, variableDeclaration, variableDeclarator, containingMethod, typeArgument, ct); - SyntaxNode GetContainingMethod() - { - foreach (SyntaxReference syntaxReference in methodSymbol.DeclaringSyntaxReferences) + SyntaxNode GetContainingMethod() { - SyntaxNode syntax = syntaxReference.GetSyntax(cancellationToken); + foreach (SyntaxReference syntaxReference in methodSymbol.DeclaringSyntaxReferences) + { + SyntaxNode syntax = syntaxReference.GetSyntax(cancellationToken); - if (syntax.Contains(variableDeclaration)) - return syntax; - } + if (syntax.Contains(variableDeclaration)) + return syntax; + } - return null; - } + return null; + } - SyntaxNode GetBodyOrExpressionBody() - { - switch (containingMethod.Kind()) + SyntaxNode GetBodyOrExpressionBody() { - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)containingMethod).BodyOrExpressionBody(); - case SyntaxKind.LocalFunctionStatement: - return ((LocalFunctionStatementSyntax)containingMethod).BodyOrExpressionBody(); - default: - throw new InvalidOperationException(); + switch (containingMethod.Kind()) + { + case SyntaxKind.MethodDeclaration: + return ((MethodDeclarationSyntax)containingMethod).BodyOrExpressionBody(); + case SyntaxKind.LocalFunctionStatement: + return ((LocalFunctionStatementSyntax)containingMethod).BodyOrExpressionBody(); + default: + throw new InvalidOperationException(); + } } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/AddBracesToIfElseRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/AddBracesToIfElseRefactoring.cs index 0b5638fd08..0860bddd57 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/AddBracesToIfElseRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/AddBracesToIfElseRefactoring.cs @@ -7,63 +7,64 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace Roslynator.CSharp.Refactorings; - -internal static class AddBracesToIfElseRefactoring +namespace Roslynator.CSharp.Refactorings { - public static Task RefactorAsync( - Document document, - IfStatementSyntax ifStatement, - CancellationToken cancellationToken = default) + internal static class AddBracesToIfElseRefactoring { - var rewriter = new SyntaxRewriter(); + public static Task RefactorAsync( + Document document, + IfStatementSyntax ifStatement, + CancellationToken cancellationToken = default) + { + var rewriter = new SyntaxRewriter(); - var newNode = (IfStatementSyntax)rewriter.Visit(ifStatement) - .WithFormatterAnnotation(); + var newNode = (IfStatementSyntax)rewriter.Visit(ifStatement) + .WithFormatterAnnotation(); - return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); - } - - private class SyntaxRewriter : CSharpSyntaxRewriter - { - private IfStatementSyntax _previousIf; + return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); + } - public override SyntaxNode VisitIfStatement(IfStatementSyntax node) + private class SyntaxRewriter : CSharpSyntaxRewriter { - if (node == null) - throw new ArgumentNullException(nameof(node)); + private IfStatementSyntax _previousIf; - if (_previousIf?.Equals(node.GetPreviousIf()) != false) + public override SyntaxNode VisitIfStatement(IfStatementSyntax node) { - if (node.Statement?.IsKind(SyntaxKind.Block) == false) + if (node is null) + throw new ArgumentNullException(nameof(node)); + + if (_previousIf?.Equals(node.GetPreviousIf()) != false) { - IfStatementSyntax ifStatement = node.WithStatement(SyntaxFactory.Block(node.Statement)); + if (node.Statement?.IsKind(SyntaxKind.Block) == false) + { + IfStatementSyntax ifStatement = node.WithStatement(SyntaxFactory.Block(node.Statement)); - _previousIf = ifStatement; + _previousIf = ifStatement; - return base.VisitIfStatement(ifStatement); - } - else - { - _previousIf = node; + return base.VisitIfStatement(ifStatement); + } + else + { + _previousIf = node; + } } + + return base.VisitIfStatement(node); } - return base.VisitIfStatement(node); - } + public override SyntaxNode VisitElseClause(ElseClauseSyntax node) + { + if (node is null) + throw new ArgumentNullException(nameof(node)); - public override SyntaxNode VisitElseClause(ElseClauseSyntax node) - { - if (node == null) - throw new ArgumentNullException(nameof(node)); + if (_previousIf.Equals(node.Parent) + && node.Statement?.IsKind(SyntaxKind.Block, SyntaxKind.IfStatement) == false) + { + return node.WithStatement(SyntaxFactory.Block(node.Statement)); + } - if (_previousIf.Equals(node.Parent) - && node.Statement?.IsKind(SyntaxKind.Block, SyntaxKind.IfStatement) == false) - { - return node.WithStatement(SyntaxFactory.Block(node.Statement)); + return base.VisitElseClause(node); } - - return base.VisitElseClause(node); } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/AddExceptionToDocumentationComment/AddExceptionElementToDocumentationCommentRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/AddExceptionToDocumentationComment/AddExceptionElementToDocumentationCommentRefactoring.cs index ad56d73a0f..1cc361a129 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/AddExceptionToDocumentationComment/AddExceptionElementToDocumentationCommentRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/AddExceptionToDocumentationComment/AddExceptionElementToDocumentationCommentRefactoring.cs @@ -14,357 +14,358 @@ using Roslynator.CSharp.Syntax; using Roslynator.Text; -namespace Roslynator.CSharp.Refactorings.AddExceptionToDocumentationComment; - -internal static class AddExceptionElementToDocumentationCommentRefactoring +namespace Roslynator.CSharp.Refactorings.AddExceptionToDocumentationComment { - private static IEnumerable GetOtherUndocumentedExceptions( - MemberDeclarationSyntax declaration, - ISymbol declarationSymbol, - Func predicate, - INamedTypeSymbol exceptionSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken) + internal static class AddExceptionElementToDocumentationCommentRefactoring { - foreach (SyntaxNode node in declaration.DescendantNodes(f => !CSharpFacts.IsAnonymousFunctionExpression(f.Kind()))) + private static IEnumerable GetOtherUndocumentedExceptions( + MemberDeclarationSyntax declaration, + ISymbol declarationSymbol, + Func predicate, + INamedTypeSymbol exceptionSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - switch (node.Kind()) + foreach (SyntaxNode node in declaration.DescendantNodes(f => !CSharpFacts.IsAnonymousFunctionExpression(f.Kind()))) { - case SyntaxKind.ThrowStatement: - { - if (predicate(node)) + switch (node.Kind()) + { + case SyntaxKind.ThrowStatement: { - var throwStatement = (ThrowStatementSyntax)node; + if (predicate(node)) + { + var throwStatement = (ThrowStatementSyntax)node; - ThrowInfo info = GetUndocumentedExceptionInfo(node, throwStatement.Expression, declaration, declarationSymbol, exceptionSymbol, semanticModel, cancellationToken); + ThrowInfo info = GetUndocumentedExceptionInfo(node, throwStatement.Expression, declaration, declarationSymbol, exceptionSymbol, semanticModel, cancellationToken); - if (info != null) - yield return info; - } + if (info is not null) + yield return info; + } - break; - } - case SyntaxKind.ThrowExpression: - { - if (predicate(node)) + break; + } + case SyntaxKind.ThrowExpression: { - var throwExpression = (ThrowExpressionSyntax)node; - ThrowInfo info = GetUndocumentedExceptionInfo(node, throwExpression.Expression, declaration, declarationSymbol, exceptionSymbol, semanticModel, cancellationToken); + if (predicate(node)) + { + var throwExpression = (ThrowExpressionSyntax)node; + ThrowInfo info = GetUndocumentedExceptionInfo(node, throwExpression.Expression, declaration, declarationSymbol, exceptionSymbol, semanticModel, cancellationToken); - if (info != null) - yield return info; - } + if (info is not null) + yield return info; + } - break; - } + break; + } + } } } - } - - private static ThrowInfo GetUndocumentedExceptionInfo( - SyntaxNode node, - ExpressionSyntax expression, - MemberDeclarationSyntax declaration, - ISymbol declarationSymbol, - INamedTypeSymbol exceptionSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - if (expression == null) - return null; - if (semanticModel.GetTypeSymbol(expression, cancellationToken) is not INamedTypeSymbol typeSymbol) - return null; + private static ThrowInfo GetUndocumentedExceptionInfo( + SyntaxNode node, + ExpressionSyntax expression, + MemberDeclarationSyntax declaration, + ISymbol declarationSymbol, + INamedTypeSymbol exceptionSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + if (expression is null) + return null; - if (!InheritsFromException(typeSymbol, exceptionSymbol)) - return null; + if (semanticModel.GetTypeSymbol(expression, cancellationToken) is not INamedTypeSymbol typeSymbol) + return null; - DocumentationCommentTriviaSyntax comment = declaration.GetSingleLineDocumentationComment(); + if (!InheritsFromException(typeSymbol, exceptionSymbol)) + return null; - if (comment == null) - return null; + DocumentationCommentTriviaSyntax comment = declaration.GetSingleLineDocumentationComment(); - if (!CanAddExceptionToComment(comment, typeSymbol, semanticModel, cancellationToken)) - return null; + if (comment is null) + return null; - return ThrowInfo.Create(node, typeSymbol, declarationSymbol); - } + if (!CanAddExceptionToComment(comment, typeSymbol, semanticModel, cancellationToken)) + return null; - private static bool CanAddExceptionToComment( - DocumentationCommentTriviaSyntax comment, - INamedTypeSymbol exceptionSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - var containsException = false; - var containsIncludeOrExclude = false; - var isFirst = true; + return ThrowInfo.Create(node, typeSymbol, declarationSymbol); + } - foreach (XmlNodeSyntax node in comment.Content) + private static bool CanAddExceptionToComment( + DocumentationCommentTriviaSyntax comment, + INamedTypeSymbol exceptionSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - XmlElementInfo info = SyntaxInfo.XmlElementInfo(node); - if (info.Success) + var containsException = false; + var containsIncludeOrExclude = false; + var isFirst = true; + + foreach (XmlNodeSyntax node in comment.Content) { - switch (info.GetTag()) + XmlElementInfo info = SyntaxInfo.XmlElementInfo(node); + if (info.Success) { - case XmlTag.Include: - case XmlTag.Exclude: - { - if (isFirst) - containsIncludeOrExclude = true; + switch (info.GetTag()) + { + case XmlTag.Include: + case XmlTag.Exclude: + { + if (isFirst) + containsIncludeOrExclude = true; - break; - } - case XmlTag.InheritDoc: - { - return false; - } - case XmlTag.Exception: - { - if (!containsException) + break; + } + case XmlTag.InheritDoc: { - if (info.IsEmptyElement) - { - containsException = ContainsException((XmlEmptyElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); - } - else + return false; + } + case XmlTag.Exception: + { + if (!containsException) { - containsException = ContainsException((XmlElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); + if (info.IsEmptyElement) + { + containsException = ContainsException((XmlEmptyElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); + } + else + { + containsException = ContainsException((XmlElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); + } } - } - break; - } - } + break; + } + } - if (isFirst) - { - isFirst = false; - } - else - { - containsIncludeOrExclude = false; + if (isFirst) + { + isFirst = false; + } + else + { + containsIncludeOrExclude = false; + } } } - } - return !containsIncludeOrExclude - && !containsException; - } + return !containsIncludeOrExclude + && !containsException; + } - private static bool ContainsException(XmlElementSyntax xmlElement, INamedTypeSymbol exceptionSymbol, SemanticModel semanticModel, CancellationToken cancellationToken) - { - XmlElementStartTagSyntax startTag = xmlElement.StartTag; + private static bool ContainsException(XmlElementSyntax xmlElement, INamedTypeSymbol exceptionSymbol, SemanticModel semanticModel, CancellationToken cancellationToken) + { + XmlElementStartTagSyntax startTag = xmlElement.StartTag; - return startTag != null - && ContainsException(startTag.Attributes, exceptionSymbol, semanticModel, cancellationToken); - } + return startTag is not null + && ContainsException(startTag.Attributes, exceptionSymbol, semanticModel, cancellationToken); + } - private static bool ContainsException(XmlEmptyElementSyntax xmlEmptyElement, INamedTypeSymbol exceptionSymbol, SemanticModel semanticModel, CancellationToken cancellationToken) - { - return ContainsException(xmlEmptyElement.Attributes, exceptionSymbol, semanticModel, cancellationToken); - } + private static bool ContainsException(XmlEmptyElementSyntax xmlEmptyElement, INamedTypeSymbol exceptionSymbol, SemanticModel semanticModel, CancellationToken cancellationToken) + { + return ContainsException(xmlEmptyElement.Attributes, exceptionSymbol, semanticModel, cancellationToken); + } - private static bool ContainsException(SyntaxList attributes, INamedTypeSymbol exceptionSymbol, SemanticModel semanticModel, CancellationToken cancellationToken) - { - foreach (XmlAttributeSyntax xmlAttribute in attributes) + private static bool ContainsException(SyntaxList attributes, INamedTypeSymbol exceptionSymbol, SemanticModel semanticModel, CancellationToken cancellationToken) { - if (xmlAttribute.Kind() == SyntaxKind.XmlCrefAttribute) + foreach (XmlAttributeSyntax xmlAttribute in attributes) { - var xmlCrefAttribute = (XmlCrefAttributeSyntax)xmlAttribute; - - CrefSyntax cref = xmlCrefAttribute.Cref; - - if (cref != null - && (semanticModel.GetSymbol(cref, cancellationToken) is INamedTypeSymbol symbol)) + if (xmlAttribute.Kind() == SyntaxKind.XmlCrefAttribute) { - if (SymbolEqualityComparer.Default.Equals(exceptionSymbol, symbol)) - return true; + var xmlCrefAttribute = (XmlCrefAttributeSyntax)xmlAttribute; - // http://github.com/dotnet/roslyn/issues/22923 - if (exceptionSymbol.IsGenericType - && symbol.IsGenericType - && SymbolEqualityComparer.Default.Equals(exceptionSymbol.ConstructedFrom, symbol.ConstructedFrom)) + CrefSyntax cref = xmlCrefAttribute.Cref; + + if (cref is not null + && (semanticModel.GetSymbol(cref, cancellationToken) is INamedTypeSymbol symbol)) { - return true; + if (SymbolEqualityComparer.Default.Equals(exceptionSymbol, symbol)) + return true; + + // http://github.com/dotnet/roslyn/issues/22923 + if (exceptionSymbol.IsGenericType + && symbol.IsGenericType + && SymbolEqualityComparer.Default.Equals(exceptionSymbol.ConstructedFrom, symbol.ConstructedFrom)) + { + return true; + } } } } + + return false; } - return false; - } + public static Task RefactorAsync( + Document document, + ThrowExpressionSyntax throwExpression, + CancellationToken cancellationToken) + { + return RefactorAsync(document, throwExpression, throwExpression.Expression, cancellationToken); + } - public static Task RefactorAsync( - Document document, - ThrowExpressionSyntax throwExpression, - CancellationToken cancellationToken) - { - return RefactorAsync(document, throwExpression, throwExpression.Expression, cancellationToken); - } + public static Task RefactorAsync( + Document document, + ThrowStatementSyntax throwStatement, + CancellationToken cancellationToken) + { + return RefactorAsync(document, throwStatement, throwStatement.Expression, cancellationToken); + } - public static Task RefactorAsync( - Document document, - ThrowStatementSyntax throwStatement, - CancellationToken cancellationToken) - { - return RefactorAsync(document, throwStatement, throwStatement.Expression, cancellationToken); - } + private static bool InheritsFromException(ITypeSymbol typeSymbol, INamedTypeSymbol exceptionSymbol) + { + return typeSymbol?.TypeKind == TypeKind.Class + && typeSymbol.BaseType?.IsObject() == false + && typeSymbol.InheritsFrom(exceptionSymbol); + } - private static bool InheritsFromException(ITypeSymbol typeSymbol, INamedTypeSymbol exceptionSymbol) - { - return typeSymbol?.TypeKind == TypeKind.Class - && typeSymbol.BaseType?.IsObject() == false - && typeSymbol.InheritsFrom(exceptionSymbol); - } + private static async Task RefactorAsync( + Document document, + SyntaxNode node, + ExpressionSyntax expression, + CancellationToken cancellationToken) + { + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - private static async Task RefactorAsync( - Document document, - SyntaxNode node, - ExpressionSyntax expression, - CancellationToken cancellationToken) - { - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + ITypeSymbol exceptionSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - ITypeSymbol exceptionSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); + ISymbol declarationSymbol = AddExceptionToDocumentationCommentAnalysis.GetDeclarationSymbol(node.SpanStart, semanticModel, cancellationToken); - ISymbol declarationSymbol = AddExceptionToDocumentationCommentAnalysis.GetDeclarationSymbol(node.SpanStart, semanticModel, cancellationToken); + var memberDeclaration = (MemberDeclarationSyntax)await declarationSymbol + .GetSyntaxAsync(cancellationToken) + .ConfigureAwait(false); - var memberDeclaration = (MemberDeclarationSyntax)await declarationSymbol - .GetSyntaxAsync(cancellationToken) - .ConfigureAwait(false); + SyntaxTrivia trivia = memberDeclaration.GetSingleLineDocumentationCommentTrivia(); - SyntaxTrivia trivia = memberDeclaration.GetSingleLineDocumentationCommentTrivia(); + ThrowInfo throwInfo = ThrowInfo.Create(node, exceptionSymbol, declarationSymbol); - ThrowInfo throwInfo = ThrowInfo.Create(node, exceptionSymbol, declarationSymbol); + return await RefactorAsync( + document, + trivia, + throwInfo, + memberDeclaration, + declarationSymbol, + semanticModel, + cancellationToken) + .ConfigureAwait(false); + } - return await RefactorAsync( - document, - trivia, - throwInfo, - memberDeclaration, - declarationSymbol, - semanticModel, - cancellationToken) - .ConfigureAwait(false); - } + public static async Task RefactorAsync( + Document document, + AddExceptionToDocumentationCommentAnalysisResult analysis, + CancellationToken cancellationToken) + { + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + + var memberDeclaration = (MemberDeclarationSyntax)await analysis.DeclarationSymbol + .GetSyntaxAsync(cancellationToken) + .ConfigureAwait(false); + + return await RefactorAsync( + document, + analysis.DocumentationComment, + analysis.ThrowInfo, + memberDeclaration, + analysis.DeclarationSymbol, + semanticModel, + cancellationToken) + .ConfigureAwait(false); + } - public static async Task RefactorAsync( - Document document, - AddExceptionToDocumentationCommentAnalysisResult analysis, - CancellationToken cancellationToken) - { - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - - var memberDeclaration = (MemberDeclarationSyntax)await analysis.DeclarationSymbol - .GetSyntaxAsync(cancellationToken) - .ConfigureAwait(false); - - return await RefactorAsync( - document, - analysis.DocumentationComment, - analysis.ThrowInfo, - memberDeclaration, - analysis.DeclarationSymbol, - semanticModel, - cancellationToken) - .ConfigureAwait(false); - } + private static Task RefactorAsync( + Document document, + SyntaxTrivia trivia, + ThrowInfo throwInfo, + MemberDeclarationSyntax memberDeclaration, + ISymbol declarationSymbol, + SemanticModel semanticModel, + CancellationToken cancellationToken) + { + var throwInfos = new List() { throwInfo }; - private static Task RefactorAsync( - Document document, - SyntaxTrivia trivia, - ThrowInfo throwInfo, - MemberDeclarationSyntax memberDeclaration, - ISymbol declarationSymbol, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - var throwInfos = new List() { throwInfo }; + INamedTypeSymbol exceptionSymbol = semanticModel.GetTypeByMetadataName("System.Exception"); - INamedTypeSymbol exceptionSymbol = semanticModel.GetTypeByMetadataName("System.Exception"); + foreach (ThrowInfo info in GetOtherUndocumentedExceptions(memberDeclaration, declarationSymbol, node => node != throwInfo.Node, exceptionSymbol, semanticModel, cancellationToken)) + { + if (!throwInfos.Any(f => SymbolEqualityComparer.Default.Equals(f.ExceptionSymbol, info.ExceptionSymbol))) + throwInfos.Add(info); + } - foreach (ThrowInfo info in GetOtherUndocumentedExceptions(memberDeclaration, declarationSymbol, node => node != throwInfo.Node, exceptionSymbol, semanticModel, cancellationToken)) - { - if (!throwInfos.Any(f => SymbolEqualityComparer.Default.Equals(f.ExceptionSymbol, info.ExceptionSymbol))) - throwInfos.Add(info); - } + string indent = GetIndent(memberDeclaration.GetLeadingTrivia()); - string indent = GetIndent(memberDeclaration.GetLeadingTrivia()); + StringBuilder sb = StringBuilderCache.GetInstance(); - StringBuilder sb = StringBuilderCache.GetInstance(); + foreach (ThrowInfo info in throwInfos) + { + sb.Append(indent); - foreach (ThrowInfo info in throwInfos) - { - sb.Append(indent); + IParameterSymbol parameterSymbol = info.GetParameterSymbol(semanticModel, cancellationToken); - IParameterSymbol parameterSymbol = info.GetParameterSymbol(semanticModel, cancellationToken); + AppendExceptionDocumentation(trivia, info.ExceptionSymbol, parameterSymbol, semanticModel, ref sb); + } - AppendExceptionDocumentation(trivia, info.ExceptionSymbol, parameterSymbol, semanticModel, ref sb); + return document.WithTextChangeAsync( + new TextSpan(trivia.FullSpan.End, 0), + StringBuilderCache.GetStringAndFree(sb), + cancellationToken); } - return document.WithTextChangeAsync( - new TextSpan(trivia.FullSpan.End, 0), - StringBuilderCache.GetStringAndFree(sb), - cancellationToken); - } - - private static string GetIndent(SyntaxTriviaList leadingTrivia) - { - if (leadingTrivia.Any()) + private static string GetIndent(SyntaxTriviaList leadingTrivia) { - int index = leadingTrivia.Count; - - while (index >= 1 - && leadingTrivia[index - 1].IsWhitespaceTrivia()) + if (leadingTrivia.Any()) { - index--; - } + int index = leadingTrivia.Count; - return string.Concat(leadingTrivia.Skip(index)); - } + while (index >= 1 + && leadingTrivia[index - 1].IsWhitespaceTrivia()) + { + index--; + } - return ""; - } + return string.Concat(leadingTrivia.Skip(index)); + } - private static void AppendExceptionDocumentation( - SyntaxTrivia trivia, - ITypeSymbol exceptionSymbol, - IParameterSymbol parameterSymbol, - SemanticModel semanticModel, - ref StringBuilder sb) - { - sb.Append("/// ') - { - sb.Append('}'); - } - else + sb.Append("/// ') + { + sb.Append('}'); + } + else + { + sb.Append(ch); + } } - } - sb.Append("\">"); + sb.Append("\">"); - if (parameterSymbol != null) - { - sb.Append(""); + if (parameterSymbol is not null) + { + sb.Append(""); - if (exceptionSymbol.HasMetadataName(MetadataNames.System_ArgumentNullException)) - sb.Append(" is null."); - } + if (exceptionSymbol.HasMetadataName(MetadataNames.System_ArgumentNullException)) + sb.Append(" is null."); + } - sb.Append(""); - sb.AppendLine(); + sb.Append(""); + sb.AppendLine(); + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/AddParameterToInterfaceMemberRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/AddParameterToInterfaceMemberRefactoring.cs index b153d84e77..302de00766 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/AddParameterToInterfaceMemberRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/AddParameterToInterfaceMemberRefactoring.cs @@ -11,420 +11,421 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class AddParameterToInterfaceMemberRefactoring +namespace Roslynator.CSharp.Refactorings { - public static CodeAction ComputeRefactoringForExplicitImplementation( - CommonFixContext context, - MemberDeclarationSyntax memberDeclaration) + internal static class AddParameterToInterfaceMemberRefactoring { - switch (memberDeclaration) + public static CodeAction ComputeRefactoringForExplicitImplementation( + CommonFixContext context, + MemberDeclarationSyntax memberDeclaration) { - case MethodDeclarationSyntax methodDeclaration: - { - return ComputeRefactoringForExplicitImplementation( - context, - methodDeclaration, - methodDeclaration.ExplicitInterfaceSpecifier, - methodDeclaration.ParameterList?.Parameters ?? default); - } - case IndexerDeclarationSyntax indexerDeclaration: - { - return ComputeRefactoringForExplicitImplementation( - context, - indexerDeclaration, - indexerDeclaration.ExplicitInterfaceSpecifier, - indexerDeclaration.ParameterList?.Parameters ?? default); - } + switch (memberDeclaration) + { + case MethodDeclarationSyntax methodDeclaration: + { + return ComputeRefactoringForExplicitImplementation( + context, + methodDeclaration, + methodDeclaration.ExplicitInterfaceSpecifier, + methodDeclaration.ParameterList?.Parameters ?? default); + } + case IndexerDeclarationSyntax indexerDeclaration: + { + return ComputeRefactoringForExplicitImplementation( + context, + indexerDeclaration, + indexerDeclaration.ExplicitInterfaceSpecifier, + indexerDeclaration.ParameterList?.Parameters ?? default); + } + } + + return default; } - return default; - } + public static OneOrMany ComputeRefactoringForImplicitImplementation( + CommonFixContext context, + MethodDeclarationSyntax methodDeclaration) + { + return ComputeRefactoringForImplicitImplementation( + context, + methodDeclaration, + methodDeclaration.Modifiers, + methodDeclaration.ExplicitInterfaceSpecifier, + methodDeclaration.ParameterList?.Parameters ?? default); + } - public static OneOrMany ComputeRefactoringForImplicitImplementation( - CommonFixContext context, - MethodDeclarationSyntax methodDeclaration) - { - return ComputeRefactoringForImplicitImplementation( - context, - methodDeclaration, - methodDeclaration.Modifiers, - methodDeclaration.ExplicitInterfaceSpecifier, - methodDeclaration.ParameterList?.Parameters ?? default); - } + public static OneOrMany ComputeRefactoringForImplicitImplementation( + CommonFixContext context, + IndexerDeclarationSyntax indexerDeclaration) + { + return ComputeRefactoringForImplicitImplementation( + context, + indexerDeclaration, + indexerDeclaration.Modifiers, + indexerDeclaration.ExplicitInterfaceSpecifier, + indexerDeclaration.ParameterList?.Parameters ?? default); + } - public static OneOrMany ComputeRefactoringForImplicitImplementation( - CommonFixContext context, - IndexerDeclarationSyntax indexerDeclaration) - { - return ComputeRefactoringForImplicitImplementation( - context, - indexerDeclaration, - indexerDeclaration.Modifiers, - indexerDeclaration.ExplicitInterfaceSpecifier, - indexerDeclaration.ParameterList?.Parameters ?? default); - } + private static OneOrMany ComputeRefactoringForImplicitImplementation( + CommonFixContext context, + MemberDeclarationSyntax memberDeclaration, + SyntaxTokenList modifiers, + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, + SeparatedSyntaxList parameters) + { + if (!parameters.Any()) + return default; - private static OneOrMany ComputeRefactoringForImplicitImplementation( - CommonFixContext context, - MemberDeclarationSyntax memberDeclaration, - SyntaxTokenList modifiers, - ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, - SeparatedSyntaxList parameters) - { - if (!parameters.Any()) - return default; + if (modifiers.Contains(SyntaxKind.StaticKeyword)) + return default; - if (modifiers.Contains(SyntaxKind.StaticKeyword)) - return default; + if (explicitInterfaceSpecifier is not null) + return default; - if (explicitInterfaceSpecifier != null) - return default; + return ComputeRefactoringForImplicitImplementation( + context, + memberDeclaration, + modifiers); + } - return ComputeRefactoringForImplicitImplementation( - context, - memberDeclaration, - modifiers); - } + public static CodeAction ComputeRefactoringForExplicitImplementation( + CommonFixContext context, + MemberDeclarationSyntax memberDeclaration, + ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, + SeparatedSyntaxList parameters) + { + if (!parameters.Any()) + return default; - public static CodeAction ComputeRefactoringForExplicitImplementation( - CommonFixContext context, - MemberDeclarationSyntax memberDeclaration, - ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, - SeparatedSyntaxList parameters) - { - if (!parameters.Any()) - return default; + NameSyntax explicitInterfaceName = explicitInterfaceSpecifier?.Name; - NameSyntax explicitInterfaceName = explicitInterfaceSpecifier?.Name; + if (explicitInterfaceName is null) + return default; - if (explicitInterfaceName == null) - return default; + var interfaceSymbol = (INamedTypeSymbol)context.SemanticModel.GetTypeSymbol(explicitInterfaceName, context.CancellationToken); - var interfaceSymbol = (INamedTypeSymbol)context.SemanticModel.GetTypeSymbol(explicitInterfaceName, context.CancellationToken); + if (interfaceSymbol?.TypeKind != TypeKind.Interface) + return default; - if (interfaceSymbol?.TypeKind != TypeKind.Interface) - return default; + if (interfaceSymbol.GetSyntaxOrDefault(context.CancellationToken) is not InterfaceDeclarationSyntax _) + return default; - if (interfaceSymbol.GetSyntaxOrDefault(context.CancellationToken) is not InterfaceDeclarationSyntax _) - return default; + ISymbol memberSymbol = context.SemanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); - ISymbol memberSymbol = context.SemanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); + if (memberSymbol is null) + return default; - if (memberSymbol == null) - return default; + ISymbol interfaceMemberSymbol = FindInterfaceMember(memberSymbol, interfaceSymbol); - ISymbol interfaceMemberSymbol = FindInterfaceMember(memberSymbol, interfaceSymbol); + if (interfaceMemberSymbol is null) + return default; - if (interfaceMemberSymbol == null) - return default; + return ComputeCodeAction(context, memberDeclaration, memberSymbol, interfaceMemberSymbol); + } - return ComputeCodeAction(context, memberDeclaration, memberSymbol, interfaceMemberSymbol); - } + private static OneOrMany ComputeRefactoringForImplicitImplementation( + CommonFixContext context, + MemberDeclarationSyntax memberDeclaration, + SyntaxTokenList modifiers) + { + if (!modifiers.Contains(SyntaxKind.PublicKeyword)) + return default; - private static OneOrMany ComputeRefactoringForImplicitImplementation( - CommonFixContext context, - MemberDeclarationSyntax memberDeclaration, - SyntaxTokenList modifiers) - { - if (!modifiers.Contains(SyntaxKind.PublicKeyword)) - return default; + BaseListSyntax baseList = GetBaseList(memberDeclaration.Parent); - BaseListSyntax baseList = GetBaseList(memberDeclaration.Parent); + if (baseList is null) + return default; - if (baseList == null) - return default; + SeparatedSyntaxList baseTypes = baseList.Types; - SeparatedSyntaxList baseTypes = baseList.Types; + ISymbol memberSymbol = context.SemanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); - ISymbol memberSymbol = context.SemanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); + if (memberSymbol is null) + return default; - if (memberSymbol == null) - return default; + if (memberSymbol.ImplementsInterfaceMember()) + return default; - if (memberSymbol.ImplementsInterfaceMember()) - return default; + int count = 0; - int count = 0; + CodeAction singleCodeAction = null; + List codeActions = default; - CodeAction singleCodeAction = null; - List codeActions = default; + for (int i = 0; i < baseTypes.Count; i++) + { + BaseTypeSyntax baseType = baseTypes[i]; - for (int i = 0; i < baseTypes.Count; i++) - { - BaseTypeSyntax baseType = baseTypes[i]; + Diagnostic diagnostic = context.SemanticModel.GetDiagnostic("CS0535", baseType.Type.Span, context.CancellationToken); - Diagnostic diagnostic = context.SemanticModel.GetDiagnostic("CS0535", baseType.Type.Span, context.CancellationToken); + if (diagnostic?.Location.SourceSpan != baseType.Type.Span) + continue; - if (diagnostic?.Location.SourceSpan != baseType.Type.Span) - continue; + var interfaceSymbol = context.SemanticModel.GetTypeSymbol(baseType.Type, context.CancellationToken) as INamedTypeSymbol; - var interfaceSymbol = context.SemanticModel.GetTypeSymbol(baseType.Type, context.CancellationToken) as INamedTypeSymbol; + if (interfaceSymbol?.TypeKind != TypeKind.Interface) + continue; - if (interfaceSymbol?.TypeKind != TypeKind.Interface) - continue; + if (interfaceSymbol.GetSyntaxOrDefault(context.CancellationToken) is not InterfaceDeclarationSyntax _) + continue; - if (interfaceSymbol.GetSyntaxOrDefault(context.CancellationToken) is not InterfaceDeclarationSyntax _) - continue; + ISymbol interfaceMemberSymbol = FindInterfaceMember(memberSymbol, interfaceSymbol); - ISymbol interfaceMemberSymbol = FindInterfaceMember(memberSymbol, interfaceSymbol); + if (interfaceMemberSymbol is not null) + { + CodeAction codeAction = ComputeCodeAction(context, memberDeclaration, memberSymbol, interfaceMemberSymbol); - if (interfaceMemberSymbol != null) - { - CodeAction codeAction = ComputeCodeAction(context, memberDeclaration, memberSymbol, interfaceMemberSymbol); + if (singleCodeAction is null) + { + singleCodeAction = codeAction; + } + else + { + (codeActions ??= new List() { singleCodeAction }).Add(codeAction); + } - if (singleCodeAction == null) - { - singleCodeAction = codeAction; - } - else - { - (codeActions ??= new List() { singleCodeAction }).Add(codeAction); - } + count++; - count++; + if (count == 10) + break; + } + } - if (count == 10) - break; + if (codeActions is not null) + { + return OneOrMany.Create(codeActions.ToImmutableArray()); + } + else if (singleCodeAction is not null) + { + return OneOrMany.Create(singleCodeAction); } - } - if (codeActions != null) - { - return OneOrMany.Create(codeActions.ToImmutableArray()); - } - else if (singleCodeAction != null) - { - return OneOrMany.Create(singleCodeAction); + return default; } - return default; - } - - private static ISymbol FindInterfaceMember( - ISymbol memberSymbol, - INamedTypeSymbol interfaceSymbol) - { - switch (memberSymbol.Kind) + private static ISymbol FindInterfaceMember( + ISymbol memberSymbol, + INamedTypeSymbol interfaceSymbol) { - case SymbolKind.Method: - { - return FindInterfaceMethod((IMethodSymbol)memberSymbol, interfaceSymbol); - } - case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)memberSymbol; - - if (propertySymbol.IsIndexer) - return FindInterfaceIndexer(propertySymbol, interfaceSymbol); + switch (memberSymbol.Kind) + { + case SymbolKind.Method: + { + return FindInterfaceMethod((IMethodSymbol)memberSymbol, interfaceSymbol); + } + case SymbolKind.Property: + { + var propertySymbol = (IPropertySymbol)memberSymbol; + + if (propertySymbol.IsIndexer) + return FindInterfaceIndexer(propertySymbol, interfaceSymbol); + + break; + } + } - break; - } + return null; } - return null; - } + private static ISymbol FindInterfaceMethod( + IMethodSymbol methodSymbol, + INamedTypeSymbol interfaceSymbol) + { + ImmutableArray members = interfaceSymbol.GetMembers(); - private static ISymbol FindInterfaceMethod( - IMethodSymbol methodSymbol, - INamedTypeSymbol interfaceSymbol) - { - ImmutableArray members = interfaceSymbol.GetMembers(); + for (int i = 0; i < members.Length; i++) + { + ISymbol memberSymbol = members[i]; - for (int i = 0; i < members.Length; i++) - { - ISymbol memberSymbol = members[i]; + if (memberSymbol.Kind != SymbolKind.Method) + continue; - if (memberSymbol.Kind != SymbolKind.Method) - continue; + var methodSymbol2 = (IMethodSymbol)memberSymbol; - var methodSymbol2 = (IMethodSymbol)memberSymbol; + if (methodSymbol2.MethodKind != MethodKind.Ordinary) + continue; - if (methodSymbol2.MethodKind != MethodKind.Ordinary) - continue; + if (methodSymbol.MethodKind == MethodKind.ExplicitInterfaceImplementation) + { + int dotIndex = methodSymbol.Name.LastIndexOf('.'); - if (methodSymbol.MethodKind == MethodKind.ExplicitInterfaceImplementation) - { - int dotIndex = methodSymbol.Name.LastIndexOf('.'); + if (string.Compare(methodSymbol.Name, dotIndex + 1, methodSymbol2.Name, 0, methodSymbol2.Name.Length) != 0) + continue; + } + else if (methodSymbol.Name != methodSymbol2.Name) + { + continue; + } - if (string.Compare(methodSymbol.Name, dotIndex + 1, methodSymbol2.Name, 0, methodSymbol2.Name.Length) != 0) + if (methodSymbol.TypeParameters.Length != methodSymbol2.TypeParameters.Length) continue; - } - else if (methodSymbol.Name != methodSymbol2.Name) - { - continue; - } - if (methodSymbol.TypeParameters.Length != methodSymbol2.TypeParameters.Length) - continue; + ImmutableArray parameters = methodSymbol.Parameters; + ImmutableArray parameters2 = methodSymbol2.Parameters; - ImmutableArray parameters = methodSymbol.Parameters; - ImmutableArray parameters2 = methodSymbol2.Parameters; + if (parameters.Length != parameters2.Length + 1) + continue; - if (parameters.Length != parameters2.Length + 1) - continue; + if (!SymbolEqualityComparer.Default.Equals(methodSymbol.ReturnType, methodSymbol2.ReturnType)) + continue; - if (!SymbolEqualityComparer.Default.Equals(methodSymbol.ReturnType, methodSymbol2.ReturnType)) - continue; + if (!ParametersEqual(parameters, parameters2)) + continue; - if (!ParametersEqual(parameters, parameters2)) - continue; + return memberSymbol; + } - return memberSymbol; + return null; } - return null; - } - - private static ISymbol FindInterfaceIndexer( - IPropertySymbol propertySymbol, - INamedTypeSymbol interfaceSymbol) - { - ImmutableArray members = interfaceSymbol.GetMembers(); - - for (int i = 0; i < members.Length; i++) + private static ISymbol FindInterfaceIndexer( + IPropertySymbol propertySymbol, + INamedTypeSymbol interfaceSymbol) { - ISymbol memberSymbol = members[i]; + ImmutableArray members = interfaceSymbol.GetMembers(); - if (memberSymbol.Kind != SymbolKind.Property) - continue; - - var propertySymbol2 = (IPropertySymbol)memberSymbol; + for (int i = 0; i < members.Length; i++) + { + ISymbol memberSymbol = members[i]; - if (!propertySymbol2.IsIndexer) - continue; + if (memberSymbol.Kind != SymbolKind.Property) + continue; - ImmutableArray parameters = propertySymbol.Parameters; - ImmutableArray parameters2 = propertySymbol2.Parameters; + var propertySymbol2 = (IPropertySymbol)memberSymbol; - if (parameters.Length != parameters2.Length + 1) - continue; + if (!propertySymbol2.IsIndexer) + continue; - if (!SymbolEqualityComparer.Default.Equals(propertySymbol.Type, propertySymbol2.Type)) - continue; + ImmutableArray parameters = propertySymbol.Parameters; + ImmutableArray parameters2 = propertySymbol2.Parameters; - if (!ParametersEqual(parameters, parameters2)) - continue; + if (parameters.Length != parameters2.Length + 1) + continue; - return memberSymbol; - } + if (!SymbolEqualityComparer.Default.Equals(propertySymbol.Type, propertySymbol2.Type)) + continue; - return null; - } + if (!ParametersEqual(parameters, parameters2)) + continue; - private static bool ParametersEqual(ImmutableArray parameters, ImmutableArray parameters2) - { - for (int j = 0; j < parameters.Length - 1; j++) - { - if (parameters[j].RefKind != parameters2[j].RefKind) - return false; + return memberSymbol; + } - if (!SymbolEqualityComparer.Default.Equals(parameters[j].Type, parameters2[j].Type)) - return false; + return null; } - return true; - } + private static bool ParametersEqual(ImmutableArray parameters, ImmutableArray parameters2) + { + for (int j = 0; j < parameters.Length - 1; j++) + { + if (parameters[j].RefKind != parameters2[j].RefKind) + return false; - private static CodeAction ComputeCodeAction( - CommonFixContext context, - MemberDeclarationSyntax memberDeclaration, - ISymbol memberSymbol, - ISymbol interfaceMemberSymbol) - { - IParameterSymbol parameterSymbol = memberSymbol.GetParameters().Last(); + if (!SymbolEqualityComparer.Default.Equals(parameters[j].Type, parameters2[j].Type)) + return false; + } - string title = $"Add parameter '{parameterSymbol.Name}' to '{SymbolDisplay.ToMinimalDisplayString(interfaceMemberSymbol.OriginalDefinition, context.SemanticModel, memberDeclaration.SpanStart, SymbolDisplayFormat.CSharpShortErrorMessageFormat)}'"; + return true; + } - string equivalenceKey = EquivalenceKey.Join(context.EquivalenceKey, interfaceMemberSymbol.OriginalDefinition.GetDocumentationCommentId()); + private static CodeAction ComputeCodeAction( + CommonFixContext context, + MemberDeclarationSyntax memberDeclaration, + ISymbol memberSymbol, + ISymbol interfaceMemberSymbol) + { + IParameterSymbol parameterSymbol = memberSymbol.GetParameters().Last(); - var interfaceMemberDeclaration = (MemberDeclarationSyntax)interfaceMemberSymbol.GetSyntax(); + string title = $"Add parameter '{parameterSymbol.Name}' to '{SymbolDisplay.ToMinimalDisplayString(interfaceMemberSymbol.OriginalDefinition, context.SemanticModel, memberDeclaration.SpanStart, SymbolDisplayFormat.CSharpShortErrorMessageFormat)}'"; - if (memberDeclaration.SyntaxTree == interfaceMemberDeclaration.SyntaxTree) - { - return CodeAction.Create( - title, - ct => - { - MemberDeclarationSyntax newNode = AddParameter(interfaceMemberDeclaration, parameterSymbol).WithFormatterAnnotation(); + string equivalenceKey = EquivalenceKey.Join(context.EquivalenceKey, interfaceMemberSymbol.OriginalDefinition.GetDocumentationCommentId()); - return context.Document.ReplaceNodeAsync(interfaceMemberDeclaration, newNode, ct); - }, - equivalenceKey); - } - else - { - return CodeAction.Create( - title, - ct => - { - MemberDeclarationSyntax newNode = AddParameter(interfaceMemberDeclaration, parameterSymbol).WithFormatterAnnotation(); + var interfaceMemberDeclaration = (MemberDeclarationSyntax)interfaceMemberSymbol.GetSyntax(); - return context.Document.Solution().ReplaceNodeAsync(interfaceMemberDeclaration, newNode, ct); - }, - equivalenceKey); + if (memberDeclaration.SyntaxTree == interfaceMemberDeclaration.SyntaxTree) + { + return CodeAction.Create( + title, + ct => + { + MemberDeclarationSyntax newNode = AddParameter(interfaceMemberDeclaration, parameterSymbol).WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(interfaceMemberDeclaration, newNode, ct); + }, + equivalenceKey); + } + else + { + return CodeAction.Create( + title, + ct => + { + MemberDeclarationSyntax newNode = AddParameter(interfaceMemberDeclaration, parameterSymbol).WithFormatterAnnotation(); + + return context.Document.Solution().ReplaceNodeAsync(interfaceMemberDeclaration, newNode, ct); + }, + equivalenceKey); + } } - } - private static MemberDeclarationSyntax AddParameter(MemberDeclarationSyntax memberDeclaration, IParameterSymbol parameterSymbol) - { - ParameterSyntax parameter = CreateParameter(parameterSymbol); - - switch (memberDeclaration) + private static MemberDeclarationSyntax AddParameter(MemberDeclarationSyntax memberDeclaration, IParameterSymbol parameterSymbol) { - case MethodDeclarationSyntax methodDeclaration: - return methodDeclaration.AddParameterListParameters(parameter); - case IndexerDeclarationSyntax indexerDeclaration: - return indexerDeclaration.AddParameterListParameters(parameter); - default: - throw new InvalidOperationException(); + ParameterSyntax parameter = CreateParameter(parameterSymbol); + + switch (memberDeclaration) + { + case MethodDeclarationSyntax methodDeclaration: + return methodDeclaration.AddParameterListParameters(parameter); + case IndexerDeclarationSyntax indexerDeclaration: + return indexerDeclaration.AddParameterListParameters(parameter); + default: + throw new InvalidOperationException(); + } } - } - private static BaseListSyntax GetBaseList(SyntaxNode node) - { - switch (node.Kind()) + private static BaseListSyntax GetBaseList(SyntaxNode node) { - case SyntaxKind.ClassDeclaration: - return ((ClassDeclarationSyntax)node).BaseList; - case SyntaxKind.RecordDeclaration: - return ((RecordDeclarationSyntax)node).BaseList; - case SyntaxKind.InterfaceDeclaration: - return ((InterfaceDeclarationSyntax)node).BaseList; - default: - return null; + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return ((ClassDeclarationSyntax)node).BaseList; + case SyntaxKind.RecordDeclaration: + return ((RecordDeclarationSyntax)node).BaseList; + case SyntaxKind.InterfaceDeclaration: + return ((InterfaceDeclarationSyntax)node).BaseList; + default: + return null; + } } - } - private static ParameterSyntax CreateParameter(IParameterSymbol parameterSymbol) - { - ExpressionSyntax defaultValue = (parameterSymbol.HasExplicitDefaultValue) - ? parameterSymbol.GetDefaultValueSyntax() - : null; - - return Parameter( - default(SyntaxList), - GetModifiers(), - parameterSymbol.Type.ToTypeSyntax().WithSimplifierAnnotation(), - Identifier(parameterSymbol.Name), - (defaultValue != null) ? EqualsValueClause(defaultValue) : default); - - SyntaxTokenList GetModifiers() + private static ParameterSyntax CreateParameter(IParameterSymbol parameterSymbol) { - switch (parameterSymbol.RefKind) + ExpressionSyntax defaultValue = (parameterSymbol.HasExplicitDefaultValue) + ? parameterSymbol.GetDefaultValueSyntax() + : null; + + return Parameter( + default(SyntaxList), + GetModifiers(), + parameterSymbol.Type.ToTypeSyntax().WithSimplifierAnnotation(), + Identifier(parameterSymbol.Name), + (defaultValue is not null) ? EqualsValueClause(defaultValue) : default); + + SyntaxTokenList GetModifiers() { - case RefKind.Ref: - return TokenList(Token(SyntaxKind.RefKeyword)); - case RefKind.Out: - return TokenList(Token(SyntaxKind.OutKeyword)); - case RefKind.None: - return default; - } + switch (parameterSymbol.RefKind) + { + case RefKind.Ref: + return TokenList(Token(SyntaxKind.RefKeyword)); + case RefKind.Out: + return TokenList(Token(SyntaxKind.OutKeyword)); + case RefKind.None: + return default; + } - Debug.Fail(parameterSymbol.RefKind.ToString()); + Debug.Fail(parameterSymbol.RefKind.ToString()); - return default; + return default; + } } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/ChangeAccessibilityRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ChangeAccessibilityRefactoring.cs index afabb69703..d615fa2f61 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ChangeAccessibilityRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ChangeAccessibilityRefactoring.cs @@ -12,216 +12,217 @@ using Microsoft.CodeAnalysis.FindSymbols; using Roslynator.CSharp.Syntax; -namespace Roslynator.CSharp.Refactorings; - -internal static class ChangeAccessibilityRefactoring +namespace Roslynator.CSharp.Refactorings { - public static ImmutableArray AvailableAccessibilities { get; } = ImmutableArray.Create( - Accessibility.Public, - Accessibility.Internal, - Accessibility.Protected, - Accessibility.Private); - - public static string GetTitle(Accessibility accessibility) - { - return $"Change accessibility to '{SyntaxFacts.GetText(accessibility)}'"; - } - - public static ISymbol GetBaseSymbolOrDefault(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) + internal static class ChangeAccessibilityRefactoring { - ISymbol symbol = GetDeclaredSymbol(); + public static ImmutableArray AvailableAccessibilities { get; } = ImmutableArray.Create( + Accessibility.Public, + Accessibility.Internal, + Accessibility.Protected, + Accessibility.Private); - if (symbol != null) + public static string GetTitle(Accessibility accessibility) { - if (!symbol.IsOverride) - return symbol; + return $"Change accessibility to '{SyntaxFacts.GetText(accessibility)}'"; + } - symbol = symbol.BaseOverriddenSymbol(); + public static ISymbol GetBaseSymbolOrDefault(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) + { + ISymbol symbol = GetDeclaredSymbol(); - if (symbol != null) + if (symbol is not null) { - SyntaxNode syntax = symbol.GetSyntaxOrDefault(cancellationToken); + if (!symbol.IsOverride) + return symbol; - if (syntax != null) + symbol = symbol.BaseOverriddenSymbol(); + + if (symbol is not null) { - if (syntax is MemberDeclarationSyntax - || syntax.IsKind(SyntaxKind.VariableDeclarator)) + SyntaxNode syntax = symbol.GetSyntaxOrDefault(cancellationToken); + + if (syntax is not null) { - return symbol; + if (syntax is MemberDeclarationSyntax + || syntax.IsKind(SyntaxKind.VariableDeclarator)) + { + return symbol; + } } } } - } - return null; + return null; - ISymbol GetDeclaredSymbol() - { - if (node is EventFieldDeclarationSyntax eventFieldDeclaration) + ISymbol GetDeclaredSymbol() { - VariableDeclaratorSyntax declarator = eventFieldDeclaration.Declaration?.Variables.SingleOrDefault(shouldThrow: false); + if (node is EventFieldDeclarationSyntax eventFieldDeclaration) + { + VariableDeclaratorSyntax declarator = eventFieldDeclaration.Declaration?.Variables.SingleOrDefault(shouldThrow: false); - if (declarator != null) - return semanticModel.GetDeclaredSymbol(declarator, cancellationToken); + if (declarator is not null) + return semanticModel.GetDeclaredSymbol(declarator, cancellationToken); - return null; - } - else - { - return semanticModel.GetDeclaredSymbol(node, cancellationToken); + return null; + } + else + { + return semanticModel.GetDeclaredSymbol(node, cancellationToken); + } } } - } - - public static Task RefactorAsync( - Document document, - MemberDeclarationListSelection selectedMembers, - Accessibility newAccessibility, - CancellationToken cancellationToken) - { - SyntaxList newMembers = selectedMembers - .UnderlyingList - .ReplaceRange(selectedMembers.FirstIndex, selectedMembers.Count, selectedMembers.Select(f => SyntaxAccessibility.WithExplicitAccessibility(f, newAccessibility))); - MemberDeclarationListInfo info = SyntaxInfo.MemberDeclarationListInfo(selectedMembers); + public static Task RefactorAsync( + Document document, + MemberDeclarationListSelection selectedMembers, + Accessibility newAccessibility, + CancellationToken cancellationToken) + { + SyntaxList newMembers = selectedMembers + .UnderlyingList + .ReplaceRange(selectedMembers.FirstIndex, selectedMembers.Count, selectedMembers.Select(f => SyntaxAccessibility.WithExplicitAccessibility(f, newAccessibility))); - return document.ReplaceMembersAsync(info, newMembers, cancellationToken); - } + MemberDeclarationListInfo info = SyntaxInfo.MemberDeclarationListInfo(selectedMembers); - public static async Task RefactorAsync( - Solution solution, - MemberDeclarationListSelection selectedMembers, - Accessibility newAccessibility, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - var members = new HashSet(); + return document.ReplaceMembersAsync(info, newMembers, cancellationToken); + } - foreach (MemberDeclarationSyntax member in selectedMembers) + public static async Task RefactorAsync( + Solution solution, + MemberDeclarationListSelection selectedMembers, + Accessibility newAccessibility, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - ModifierFilter filter = SyntaxInfo.ModifierListInfo(member).GetFilter(); + var members = new HashSet(); - if (filter.HasAnyFlag(ModifierFilter.Partial)) + foreach (MemberDeclarationSyntax member in selectedMembers) { - ISymbol symbol = semanticModel.GetDeclaredSymbol(member, cancellationToken); + ModifierFilter filter = SyntaxInfo.ModifierListInfo(member).GetFilter(); - foreach (SyntaxReference reference in symbol.DeclaringSyntaxReferences) - members.Add((MemberDeclarationSyntax)reference.GetSyntax(cancellationToken)); - } - else if (filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) - { - ISymbol symbol = GetBaseSymbolOrDefault(member, semanticModel, cancellationToken); + if (filter.HasAnyFlag(ModifierFilter.Partial)) + { + ISymbol symbol = semanticModel.GetDeclaredSymbol(member, cancellationToken); - if (symbol != null) + foreach (SyntaxReference reference in symbol.DeclaringSyntaxReferences) + members.Add((MemberDeclarationSyntax)reference.GetSyntax(cancellationToken)); + } + else if (filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) { - foreach (MemberDeclarationSyntax member2 in GetMemberDeclarations(symbol, cancellationToken)) - members.Add(member2); + ISymbol symbol = GetBaseSymbolOrDefault(member, semanticModel, cancellationToken); + + if (symbol is not null) + { + foreach (MemberDeclarationSyntax member2 in GetMemberDeclarations(symbol, cancellationToken)) + members.Add(member2); - foreach (MemberDeclarationSyntax member2 in await FindOverridingMemberDeclarationsAsync(symbol, solution, cancellationToken).ConfigureAwait(false)) - members.Add(member2); + foreach (MemberDeclarationSyntax member2 in await FindOverridingMemberDeclarationsAsync(symbol, solution, cancellationToken).ConfigureAwait(false)) + members.Add(member2); + } + else + { + members.Add(member); + } } else { members.Add(member); } } - else - { - members.Add(member); - } - } - return await solution.ReplaceNodesAsync( - members, - (node, _) => SyntaxAccessibility.WithExplicitAccessibility(node, newAccessibility), - cancellationToken) - .ConfigureAwait(false); - } + return await solution.ReplaceNodesAsync( + members, + (node, _) => SyntaxAccessibility.WithExplicitAccessibility(node, newAccessibility), + cancellationToken) + .ConfigureAwait(false); + } - public static Task RefactorAsync( - Document document, - SyntaxNode node, - Accessibility newAccessibility, - CancellationToken cancellationToken) - { - SyntaxNode newNode = SyntaxAccessibility.WithExplicitAccessibility(node, newAccessibility); + public static Task RefactorAsync( + Document document, + SyntaxNode node, + Accessibility newAccessibility, + CancellationToken cancellationToken) + { + SyntaxNode newNode = SyntaxAccessibility.WithExplicitAccessibility(node, newAccessibility); - return document.ReplaceNodeAsync(node, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(node, newNode, cancellationToken); + } - public static async Task RefactorAsync( - Solution solution, - ISymbol symbol, - Accessibility newAccessibility, - CancellationToken cancellationToken = default) - { - ImmutableArray memberDeclarations = GetMemberDeclarations(symbol, cancellationToken) - .Concat(await FindOverridingMemberDeclarationsAsync(symbol, solution, cancellationToken).ConfigureAwait(false)) - .ToImmutableArray(); + public static async Task RefactorAsync( + Solution solution, + ISymbol symbol, + Accessibility newAccessibility, + CancellationToken cancellationToken = default) + { + ImmutableArray memberDeclarations = GetMemberDeclarations(symbol, cancellationToken) + .Concat(await FindOverridingMemberDeclarationsAsync(symbol, solution, cancellationToken).ConfigureAwait(false)) + .ToImmutableArray(); - return await RefactorAsync(solution, memberDeclarations, newAccessibility, cancellationToken).ConfigureAwait(false); - } + return await RefactorAsync(solution, memberDeclarations, newAccessibility, cancellationToken).ConfigureAwait(false); + } - private static async Task> FindOverridingMemberDeclarationsAsync( - ISymbol symbol, - Solution solution, - CancellationToken cancellationToken = default) - { - IEnumerable symbols = await SymbolFinder.FindOverridesAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); + private static async Task> FindOverridingMemberDeclarationsAsync( + ISymbol symbol, + Solution solution, + CancellationToken cancellationToken = default) + { + IEnumerable symbols = await SymbolFinder.FindOverridesAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); - return symbols.SelectMany(f => GetMemberDeclarations(f, cancellationToken)); - } + return symbols.SelectMany(f => GetMemberDeclarations(f, cancellationToken)); + } - private static IEnumerable GetMemberDeclarations( - ISymbol symbol, - CancellationToken cancellationToken = default) - { - foreach (SyntaxReference syntaxReference in symbol.DeclaringSyntaxReferences) + private static IEnumerable GetMemberDeclarations( + ISymbol symbol, + CancellationToken cancellationToken = default) { - switch (syntaxReference.GetSyntax(cancellationToken)) + foreach (SyntaxReference syntaxReference in symbol.DeclaringSyntaxReferences) { - case MemberDeclarationSyntax memberDeclaration: - { - yield return memberDeclaration; - break; - } - case VariableDeclaratorSyntax variableDeclarator: - { - if (variableDeclarator.Parent.Parent is MemberDeclarationSyntax memberDeclaration2) - yield return memberDeclaration2; - - break; - } - default: - { - Debug.Fail(syntaxReference.GetSyntax(cancellationToken).Kind().ToString()); - break; - } + switch (syntaxReference.GetSyntax(cancellationToken)) + { + case MemberDeclarationSyntax memberDeclaration: + { + yield return memberDeclaration; + break; + } + case VariableDeclaratorSyntax variableDeclarator: + { + if (variableDeclarator.Parent.Parent is MemberDeclarationSyntax memberDeclaration2) + yield return memberDeclaration2; + + break; + } + default: + { + Debug.Fail(syntaxReference.GetSyntax(cancellationToken).Kind().ToString()); + break; + } + } } } - } - public static Task RefactorAsync( - Solution solution, - ImmutableArray memberDeclarations, - Accessibility newAccessibility, - CancellationToken cancellationToken) - { - return solution.ReplaceNodesAsync( - memberDeclarations, - (node, _) => WithAccessibility(node, newAccessibility), - cancellationToken); - } + public static Task RefactorAsync( + Solution solution, + ImmutableArray memberDeclarations, + Accessibility newAccessibility, + CancellationToken cancellationToken) + { + return solution.ReplaceNodesAsync( + memberDeclarations, + (node, _) => WithAccessibility(node, newAccessibility), + cancellationToken); + } - private static SyntaxNode WithAccessibility(MemberDeclarationSyntax node, Accessibility newAccessibility) - { - ModifierListInfo info = SyntaxInfo.ModifierListInfo(node); + private static SyntaxNode WithAccessibility(MemberDeclarationSyntax node, Accessibility newAccessibility) + { + ModifierListInfo info = SyntaxInfo.ModifierListInfo(node); - if (info.ExplicitAccessibility == Accessibility.NotApplicable) - return node; + if (info.ExplicitAccessibility == Accessibility.NotApplicable) + return node; - ModifierListInfo newInfo = info.WithExplicitAccessibility(newAccessibility, ModifierKindComparer.Default); + ModifierListInfo newInfo = info.WithExplicitAccessibility(newAccessibility, ModifierKindComparer.Default); - return newInfo.Parent; + return newInfo.Parent; + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/ConvertBlockBodyToExpressionBodyRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ConvertBlockBodyToExpressionBodyRefactoring.cs index 4f494515f6..2db50c1fa7 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ConvertBlockBodyToExpressionBodyRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ConvertBlockBodyToExpressionBodyRefactoring.cs @@ -12,340 +12,341 @@ using Roslynator.CSharp.Analysis; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class ConvertBlockBodyToExpressionBodyRefactoring +namespace Roslynator.CSharp.Refactorings { - public const string Title = "Use expression-bodied member"; - - public static bool CanRefactor(SyntaxNode node) + internal static class ConvertBlockBodyToExpressionBodyRefactoring { - switch (node) - { - case MethodDeclarationSyntax methodDeclaration: - return CanRefactor(methodDeclaration); - case PropertyDeclarationSyntax propertyDeclaration: - return CanRefactor(propertyDeclaration); - case IndexerDeclarationSyntax indexerDeclaration: - return CanRefactor(indexerDeclaration); - case OperatorDeclarationSyntax operatorDeclaration: - return CanRefactor(operatorDeclaration); - case ConversionOperatorDeclarationSyntax conversionOperatorDeclaration: - return CanRefactor(conversionOperatorDeclaration); - case ConstructorDeclarationSyntax constructorDeclaration: - return CanRefactor(constructorDeclaration); - case DestructorDeclarationSyntax destructorDeclaration: - return CanRefactor(destructorDeclaration); - case AccessorDeclarationSyntax accessorDeclaration: - return CanRefactor(accessorDeclaration); - case LocalFunctionStatementSyntax localFunctionStatement: - return CanRefactor(localFunctionStatement); - } + public const string Title = "Use expression-bodied member"; - return false; - } - - public static bool CanRefactor(PropertyDeclarationSyntax propertyDeclaration, TextSpan? span = null) - { - AccessorListSyntax accessorList = propertyDeclaration.AccessorList; - - if (accessorList != null - && span?.IsEmptyAndContainedInSpanOrBetweenSpans(accessorList) != false) + public static bool CanRefactor(SyntaxNode node) { - AccessorDeclarationSyntax accessor = propertyDeclaration - .AccessorList? - .Accessors - .SingleOrDefault(shouldThrow: false); - - if (accessor?.AttributeLists.Any() == false - && accessor.IsKind(SyntaxKind.GetAccessorDeclaration) - && accessor.Body != null - && BlockExpressionAnalysis.SupportsExpressionBody(accessor.Body, allowExpressionStatement: false)) + switch (node) { - return true; + case MethodDeclarationSyntax methodDeclaration: + return CanRefactor(methodDeclaration); + case PropertyDeclarationSyntax propertyDeclaration: + return CanRefactor(propertyDeclaration); + case IndexerDeclarationSyntax indexerDeclaration: + return CanRefactor(indexerDeclaration); + case OperatorDeclarationSyntax operatorDeclaration: + return CanRefactor(operatorDeclaration); + case ConversionOperatorDeclarationSyntax conversionOperatorDeclaration: + return CanRefactor(conversionOperatorDeclaration); + case ConstructorDeclarationSyntax constructorDeclaration: + return CanRefactor(constructorDeclaration); + case DestructorDeclarationSyntax destructorDeclaration: + return CanRefactor(destructorDeclaration); + case AccessorDeclarationSyntax accessorDeclaration: + return CanRefactor(accessorDeclaration); + case LocalFunctionStatementSyntax localFunctionStatement: + return CanRefactor(localFunctionStatement); } + + return false; } - return false; - } + public static bool CanRefactor(PropertyDeclarationSyntax propertyDeclaration, TextSpan? span = null) + { + AccessorListSyntax accessorList = propertyDeclaration.AccessorList; - public static bool CanRefactor(MethodDeclarationSyntax methodDeclaration, TextSpan? span = null) - { - return methodDeclaration.Body != null - && span?.IsEmptyAndContainedInSpanOrBetweenSpans(methodDeclaration.Body) != false - && BlockExpressionAnalysis.SupportsExpressionBody(methodDeclaration.Body); - } + if (accessorList is not null + && span?.IsEmptyAndContainedInSpanOrBetweenSpans(accessorList) != false) + { + AccessorDeclarationSyntax accessor = propertyDeclaration + .AccessorList? + .Accessors + .SingleOrDefault(shouldThrow: false); + + if (accessor?.AttributeLists.Any() == false + && accessor.IsKind(SyntaxKind.GetAccessorDeclaration) + && accessor.Body is not null + && BlockExpressionAnalysis.SupportsExpressionBody(accessor.Body, allowExpressionStatement: false)) + { + return true; + } + } - public static bool CanRefactor(OperatorDeclarationSyntax operatorDeclaration, TextSpan? span = null) - { - return operatorDeclaration.Body != null - && span?.IsEmptyAndContainedInSpanOrBetweenSpans(operatorDeclaration.Body) != false - && BlockExpressionAnalysis.SupportsExpressionBody(operatorDeclaration.Body, allowExpressionStatement: false); - } + return false; + } - public static bool CanRefactor(ConversionOperatorDeclarationSyntax operatorDeclaration, TextSpan? span = null) - { - return operatorDeclaration.Body != null - && span?.IsEmptyAndContainedInSpanOrBetweenSpans(operatorDeclaration.Body) != false - && BlockExpressionAnalysis.SupportsExpressionBody(operatorDeclaration.Body, allowExpressionStatement: false); - } + public static bool CanRefactor(MethodDeclarationSyntax methodDeclaration, TextSpan? span = null) + { + return methodDeclaration.Body is not null + && span?.IsEmptyAndContainedInSpanOrBetweenSpans(methodDeclaration.Body) != false + && BlockExpressionAnalysis.SupportsExpressionBody(methodDeclaration.Body); + } - public static bool CanRefactor(LocalFunctionStatementSyntax localFunctionStatement, TextSpan? span = null) - { - return localFunctionStatement.Body != null - && span?.IsEmptyAndContainedInSpanOrBetweenSpans(localFunctionStatement.Body) != false - && BlockExpressionAnalysis.SupportsExpressionBody(localFunctionStatement.Body); - } + public static bool CanRefactor(OperatorDeclarationSyntax operatorDeclaration, TextSpan? span = null) + { + return operatorDeclaration.Body is not null + && span?.IsEmptyAndContainedInSpanOrBetweenSpans(operatorDeclaration.Body) != false + && BlockExpressionAnalysis.SupportsExpressionBody(operatorDeclaration.Body, allowExpressionStatement: false); + } - public static bool CanRefactor(IndexerDeclarationSyntax indexerDeclaration, TextSpan? span = null) - { - AccessorListSyntax accessorList = indexerDeclaration.AccessorList; + public static bool CanRefactor(ConversionOperatorDeclarationSyntax operatorDeclaration, TextSpan? span = null) + { + return operatorDeclaration.Body is not null + && span?.IsEmptyAndContainedInSpanOrBetweenSpans(operatorDeclaration.Body) != false + && BlockExpressionAnalysis.SupportsExpressionBody(operatorDeclaration.Body, allowExpressionStatement: false); + } - if (accessorList != null - && span?.IsEmptyAndContainedInSpanOrBetweenSpans(accessorList) != false) + public static bool CanRefactor(LocalFunctionStatementSyntax localFunctionStatement, TextSpan? span = null) { - AccessorDeclarationSyntax accessor = indexerDeclaration - .AccessorList? - .Accessors - .SingleOrDefault(shouldThrow: false); - - if (accessor?.AttributeLists.Any() == false - && accessor.IsKind(SyntaxKind.GetAccessorDeclaration) - && accessor.Body != null - && BlockExpressionAnalysis.SupportsExpressionBody(accessor.Body, allowExpressionStatement: false)) + return localFunctionStatement.Body is not null + && span?.IsEmptyAndContainedInSpanOrBetweenSpans(localFunctionStatement.Body) != false + && BlockExpressionAnalysis.SupportsExpressionBody(localFunctionStatement.Body); + } + + public static bool CanRefactor(IndexerDeclarationSyntax indexerDeclaration, TextSpan? span = null) + { + AccessorListSyntax accessorList = indexerDeclaration.AccessorList; + + if (accessorList is not null + && span?.IsEmptyAndContainedInSpanOrBetweenSpans(accessorList) != false) { - return true; + AccessorDeclarationSyntax accessor = indexerDeclaration + .AccessorList? + .Accessors + .SingleOrDefault(shouldThrow: false); + + if (accessor?.AttributeLists.Any() == false + && accessor.IsKind(SyntaxKind.GetAccessorDeclaration) + && accessor.Body is not null + && BlockExpressionAnalysis.SupportsExpressionBody(accessor.Body, allowExpressionStatement: false)) + { + return true; + } } - } - return false; - } + return false; + } - public static bool CanRefactor(DestructorDeclarationSyntax destructorDeclaration, TextSpan? span = null) - { - return destructorDeclaration.Body != null - && span?.IsEmptyAndContainedInSpanOrBetweenSpans(destructorDeclaration.Body) != false - && BlockExpressionAnalysis.SupportsExpressionBody(destructorDeclaration.Body); - } + public static bool CanRefactor(DestructorDeclarationSyntax destructorDeclaration, TextSpan? span = null) + { + return destructorDeclaration.Body is not null + && span?.IsEmptyAndContainedInSpanOrBetweenSpans(destructorDeclaration.Body) != false + && BlockExpressionAnalysis.SupportsExpressionBody(destructorDeclaration.Body); + } - public static bool CanRefactor(ConstructorDeclarationSyntax constructorDeclaration, TextSpan? span = null) - { - return constructorDeclaration.Body != null - && span?.IsEmptyAndContainedInSpanOrBetweenSpans(constructorDeclaration.Body) != false - && BlockExpressionAnalysis.SupportsExpressionBody(constructorDeclaration.Body); - } + public static bool CanRefactor(ConstructorDeclarationSyntax constructorDeclaration, TextSpan? span = null) + { + return constructorDeclaration.Body is not null + && span?.IsEmptyAndContainedInSpanOrBetweenSpans(constructorDeclaration.Body) != false + && BlockExpressionAnalysis.SupportsExpressionBody(constructorDeclaration.Body); + } - public static bool CanRefactor(AccessorDeclarationSyntax accessorDeclaration, TextSpan? span = null) - { - BlockSyntax body = accessorDeclaration.Body; - - return body != null - && (span?.IsEmptyAndContainedInSpanOrBetweenSpans(accessorDeclaration) != false - || span.Value.IsEmptyAndContainedInSpanOrBetweenSpans(body)) - && !accessorDeclaration.AttributeLists.Any() - && BlockExpressionAnalysis.SupportsExpressionBody(body, allowExpressionStatement: !accessorDeclaration.IsKind(SyntaxKind.GetAccessorDeclaration)) - && (accessorDeclaration.Parent as AccessorListSyntax)? - .Accessors - .SingleOrDefault(shouldThrow: false)? - .Kind() != SyntaxKind.GetAccessorDeclaration; - } + public static bool CanRefactor(AccessorDeclarationSyntax accessorDeclaration, TextSpan? span = null) + { + BlockSyntax body = accessorDeclaration.Body; + + return body is not null + && (span?.IsEmptyAndContainedInSpanOrBetweenSpans(accessorDeclaration) != false + || span.Value.IsEmptyAndContainedInSpanOrBetweenSpans(body)) + && !accessorDeclaration.AttributeLists.Any() + && BlockExpressionAnalysis.SupportsExpressionBody(body, allowExpressionStatement: !accessorDeclaration.IsKind(SyntaxKind.GetAccessorDeclaration)) + && (accessorDeclaration.Parent as AccessorListSyntax)? + .Accessors + .SingleOrDefault(shouldThrow: false)? + .Kind() != SyntaxKind.GetAccessorDeclaration; + } - public static Task RefactorAsync( - Document document, - MemberDeclarationListSelection selectedMembers, - CancellationToken cancellationToken) - { - IEnumerable newMembers = selectedMembers - .UnderlyingList - .ModifyRange( - selectedMembers.FirstIndex, - selectedMembers.Count, - member => - { - if (CanRefactor(member)) + public static Task RefactorAsync( + Document document, + MemberDeclarationListSelection selectedMembers, + CancellationToken cancellationToken) + { + IEnumerable newMembers = selectedMembers + .UnderlyingList + .ModifyRange( + selectedMembers.FirstIndex, + selectedMembers.Count, + member => { - var newMember = (MemberDeclarationSyntax)Refactor(member); + if (CanRefactor(member)) + { + var newMember = (MemberDeclarationSyntax)Refactor(member); - return newMember - .WithTrailingTrivia(member.GetTrailingTrivia()) - .WithFormatterAnnotation(); - } + return newMember + .WithTrailingTrivia(member.GetTrailingTrivia()) + .WithFormatterAnnotation(); + } - return member; - }); + return member; + }); - return document.ReplaceMembersAsync(SyntaxInfo.MemberDeclarationListInfo(selectedMembers.Parent), newMembers, cancellationToken); - } + return document.ReplaceMembersAsync(SyntaxInfo.MemberDeclarationListInfo(selectedMembers.Parent), newMembers, cancellationToken); + } - public static Task RefactorAsync( - Document document, - SyntaxNode node, - CancellationToken cancellationToken = default) - { - SyntaxNode newNode = Refactor(node).WithFormatterAnnotation(); + public static Task RefactorAsync( + Document document, + SyntaxNode node, + CancellationToken cancellationToken = default) + { + SyntaxNode newNode = Refactor(node).WithFormatterAnnotation(); - return document.ReplaceNodeAsync(node, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(node, newNode, cancellationToken); + } - private static SyntaxNode Refactor(SyntaxNode node) - { - switch (node.Kind()) + private static SyntaxNode Refactor(SyntaxNode node) { - case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(methodDeclaration.Body); + switch (node.Kind()) + { + case SyntaxKind.MethodDeclaration: + { + var methodDeclaration = (MethodDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(methodDeclaration.Body); - return methodDeclaration - .WithExpressionBody(CreateExpressionBody(analysis, methodDeclaration)) - .WithSemicolonToken(CreateSemicolonToken(methodDeclaration.Body, analysis)) - .WithBody(null); - } - case SyntaxKind.ConstructorDeclaration: - { - var constructorDeclaration = (ConstructorDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(constructorDeclaration.Body); + return methodDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, methodDeclaration)) + .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)) - .WithSemicolonToken(CreateSemicolonToken(constructorDeclaration.Body, analysis)) - .WithBody(null); - } - case SyntaxKind.DestructorDeclaration: - { - var destructorDeclaration = (DestructorDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(destructorDeclaration.Body); + return constructorDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, constructorDeclaration)) + .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)) - .WithSemicolonToken(CreateSemicolonToken(destructorDeclaration.Body, analysis)) - .WithBody(null); - } - case SyntaxKind.LocalFunctionStatement: - { - var localFunction = (LocalFunctionStatementSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(localFunction.Body); + return destructorDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, destructorDeclaration)) + .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)) - .WithSemicolonToken(CreateSemicolonToken(localFunction.Body, analysis)) - .WithBody(null); - } - case SyntaxKind.OperatorDeclaration: - { - var operatorDeclaration = (OperatorDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(operatorDeclaration.Body); + return localFunction + .WithExpressionBody(CreateExpressionBody(analysis, localFunction)) + .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)) - .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)) + .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)) - .WithSemicolonToken(CreateSemicolonToken(operatorDeclaration.Body, analysis)) - .WithBody(null); - } - case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(propertyDeclaration.AccessorList); + return operatorDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, operatorDeclaration)) + .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)) - .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) - .WithAccessorList(null); - } - case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(indexerDeclaration.AccessorList); + return propertyDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, propertyDeclaration)) + .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)) - .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 indexerDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, indexerDeclaration)) + .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)) - .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) - .WithBody(null); - } - default: - { - SyntaxDebug.Fail(node); - return node; - } + return accessor + .WithExpressionBody(CreateExpressionBody(analysis, accessor)) + .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) + .WithBody(null); + } + default: + { + SyntaxDebug.Fail(node); + return node; + } + } } - } - private static ArrowExpressionClauseSyntax CreateExpressionBody(BlockExpressionAnalysis analysis, SyntaxNode declaration) - { - SyntaxToken arrowToken = Token(SyntaxKind.EqualsGreaterThanToken); + private static ArrowExpressionClauseSyntax CreateExpressionBody(BlockExpressionAnalysis analysis, SyntaxNode declaration) + { + SyntaxToken arrowToken = Token(SyntaxKind.EqualsGreaterThanToken); - ExpressionSyntax expression = analysis.Expression; + ExpressionSyntax expression = analysis.Expression; - SyntaxToken keyword = analysis.ReturnOrThrowKeyword; + SyntaxToken keyword = analysis.ReturnOrThrowKeyword; - switch (keyword.Kind()) - { - case SyntaxKind.ThrowKeyword: - { - expression = ThrowExpression(keyword, expression); - break; - } - case SyntaxKind.ReturnKeyword: - { - SyntaxTriviaList leading = keyword.LeadingTrivia; + switch (keyword.Kind()) + { + case SyntaxKind.ThrowKeyword: + { + expression = ThrowExpression(keyword, expression); + break; + } + case SyntaxKind.ReturnKeyword: + { + 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); + expression = SyntaxTriviaAnalysis.SetIndentation(expression, declaration); - return ArrowExpressionClause(arrowToken, expression); - } + return ArrowExpressionClause(arrowToken, expression); + } - private static SyntaxToken CreateSemicolonToken(BlockSyntax block, BlockExpressionAnalysis analysis) - { - SyntaxTriviaList trivia = analysis.SemicolonToken.TrailingTrivia; + private static SyntaxToken CreateSemicolonToken(BlockSyntax block, BlockExpressionAnalysis analysis) + { + SyntaxTriviaList trivia = analysis.SemicolonToken.TrailingTrivia; - SyntaxTriviaList leading = block.CloseBraceToken.LeadingTrivia; + SyntaxTriviaList leading = block.CloseBraceToken.LeadingTrivia; - if (!leading.IsEmptyOrWhitespace()) - trivia = trivia.AddRange(leading); + if (!leading.IsEmptyOrWhitespace()) + trivia = trivia.AddRange(leading); - SyntaxTriviaList trailing = block.CloseBraceToken.TrailingTrivia; + SyntaxTriviaList trailing = block.CloseBraceToken.TrailingTrivia; - if (!trailing.IsEmptyOrWhitespace() - || !analysis.SemicolonToken.TrailingTrivia.LastOrDefault().IsEndOfLineTrivia()) - { - trivia = trivia.AddRange(trailing); - } + if (!trailing.IsEmptyOrWhitespace() + || !analysis.SemicolonToken.TrailingTrivia.LastOrDefault().IsEndOfLineTrivia()) + { + trivia = trivia.AddRange(trailing); + } - return analysis.SemicolonToken.WithTrailingTrivia(trivia); + return analysis.SemicolonToken.WithTrailingTrivia(trivia); + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/ConvertExpressionBodyToBlockBodyRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ConvertExpressionBodyToBlockBodyRefactoring.cs index 0879b34b9d..880b1e45ff 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ConvertExpressionBodyToBlockBodyRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ConvertExpressionBodyToBlockBodyRefactoring.cs @@ -12,300 +12,301 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class ConvertExpressionBodyToBlockBodyRefactoring +namespace Roslynator.CSharp.Refactorings { - public const string Title = "Use block body"; - - public static async Task RefactorAsync( - Document document, - MemberDeclarationListSelection selectedMembers, - CancellationToken cancellationToken) + internal static class ConvertExpressionBodyToBlockBodyRefactoring { - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - - IEnumerable newMembers = selectedMembers - .UnderlyingList - .ModifyRange( - selectedMembers.FirstIndex, - selectedMembers.Count, - member => - { - ArrowExpressionClauseSyntax expressionBody = CSharpUtility.GetExpressionBody(member); + public const string Title = "Use block body"; - if (expressionBody != null - && ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + public static async Task RefactorAsync( + Document document, + MemberDeclarationListSelection selectedMembers, + CancellationToken cancellationToken) + { + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + + IEnumerable newMembers = selectedMembers + .UnderlyingList + .ModifyRange( + selectedMembers.FirstIndex, + selectedMembers.Count, + member => { - return (MemberDeclarationSyntax)Refactor(expressionBody, semanticModel, cancellationToken); - } - - return member; - }); - - return await document.ReplaceMembersAsync(SyntaxInfo.MemberDeclarationListInfo(selectedMembers.Parent), newMembers, cancellationToken).ConfigureAwait(false); - } + ArrowExpressionClauseSyntax expressionBody = CSharpUtility.GetExpressionBody(member); - public static async Task RefactorAsync( - Document document, - ArrowExpressionClauseSyntax expressionBody, - CancellationToken cancellationToken = default) - { - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + if (expressionBody is not null + && ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + { + return (MemberDeclarationSyntax)Refactor(expressionBody, semanticModel, cancellationToken); + } - SyntaxNode newNode = Refactor(expressionBody, semanticModel, cancellationToken); + return member; + }); - SyntaxToken token = expressionBody.ArrowToken.GetPreviousToken(); + return await document.ReplaceMembersAsync(SyntaxInfo.MemberDeclarationListInfo(selectedMembers.Parent), newMembers, cancellationToken).ConfigureAwait(false); + } - if (SyntaxTriviaAnalysis.IsOptionalWhitespaceThenEndOfLineTrivia(token.TrailingTrivia)) + public static async Task RefactorAsync( + Document document, + ArrowExpressionClauseSyntax expressionBody, + CancellationToken cancellationToken = default) { - SyntaxToken newToken = token.WithTrailingTrivia(ElasticSpace); + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - newNode = newNode.ReplaceToken(token, newToken); - } + SyntaxNode newNode = Refactor(expressionBody, semanticModel, cancellationToken); - return await document.ReplaceNodeAsync(expressionBody.Parent, newNode, cancellationToken).ConfigureAwait(false); - } + SyntaxToken token = expressionBody.ArrowToken.GetPreviousToken(); - public static SyntaxNode Refactor( - ArrowExpressionClauseSyntax expressionBody, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - SyntaxNode node = expressionBody.Parent; + if (SyntaxTriviaAnalysis.IsOptionalWhitespaceThenEndOfLineTrivia(token.TrailingTrivia)) + { + SyntaxToken newToken = token.WithTrailingTrivia(ElasticSpace); + + newNode = newNode.ReplaceToken(token, newToken); + } - ExpressionSyntax expression = expressionBody.Expression; + return await document.ReplaceNodeAsync(expressionBody.Parent, newNode, cancellationToken).ConfigureAwait(false); + } - switch (node.Kind()) + public static SyntaxNode Refactor( + ArrowExpressionClauseSyntax expressionBody, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - case SyntaxKind.MethodDeclaration: - { - var method = (MethodDeclarationSyntax)node; + SyntaxNode node = expressionBody.Parent; - return method - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(method, expression, method.SemicolonToken, method.ReturnType, semanticModel, cancellationToken)); - } - case SyntaxKind.ConstructorDeclaration: - { - var constructor = (ConstructorDeclarationSyntax)node; + ExpressionSyntax expression = expressionBody.Expression; - return constructor - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlockWithExpressionStatement(constructor, expression, constructor.SemicolonToken)); - } - case SyntaxKind.DestructorDeclaration: - { - var destructor = (DestructorDeclarationSyntax)node; + switch (node.Kind()) + { + case SyntaxKind.MethodDeclaration: + { + var method = (MethodDeclarationSyntax)node; - return destructor - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlockWithExpressionStatement(destructor, expression, destructor.SemicolonToken)); - } - case SyntaxKind.OperatorDeclaration: - { - var operatorDeclaration = (OperatorDeclarationSyntax)node; + return method + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(method, expression, method.SemicolonToken, method.ReturnType, semanticModel, cancellationToken)); + } + case SyntaxKind.ConstructorDeclaration: + { + var constructor = (ConstructorDeclarationSyntax)node; - return operatorDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(operatorDeclaration, expression, operatorDeclaration.SemicolonToken)); - } - case SyntaxKind.ConversionOperatorDeclaration: - { - var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; + return constructor + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlockWithExpressionStatement(constructor, expression, constructor.SemicolonToken)); + } + case SyntaxKind.DestructorDeclaration: + { + var destructor = (DestructorDeclarationSyntax)node; - return conversionOperatorDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(conversionOperatorDeclaration, expression, conversionOperatorDeclaration.SemicolonToken)); - } - case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; + return destructor + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlockWithExpressionStatement(destructor, expression, destructor.SemicolonToken)); + } + case SyntaxKind.OperatorDeclaration: + { + var operatorDeclaration = (OperatorDeclarationSyntax)node; - return propertyDeclaration - .WithAccessorList(CreateAccessorList(propertyDeclaration, expression, propertyDeclaration.SemicolonToken)) - .WithExpressionBody(null) - .WithSemicolonToken(default); - } - case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)node; + return operatorDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(operatorDeclaration, expression, operatorDeclaration.SemicolonToken)); + } + case SyntaxKind.ConversionOperatorDeclaration: + { + var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; - return indexerDeclaration - .WithAccessorList(CreateAccessorList(indexerDeclaration, expression, indexerDeclaration.SemicolonToken)) - .WithExpressionBody(null) - .WithSemicolonToken(default); - } - case SyntaxKind.GetAccessorDeclaration: - { - var accessor = (AccessorDeclarationSyntax)node; + return conversionOperatorDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(conversionOperatorDeclaration, expression, conversionOperatorDeclaration.SemicolonToken)); + } + case SyntaxKind.PropertyDeclaration: + { + var propertyDeclaration = (PropertyDeclarationSyntax)node; - return accessor - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(accessor, expression, accessor.SemicolonToken)); - } - case SyntaxKind.SetAccessorDeclaration: - case SyntaxKind.InitAccessorDeclaration: - case SyntaxKind.AddAccessorDeclaration: - case SyntaxKind.RemoveAccessorDeclaration: - { - var accessor = (AccessorDeclarationSyntax)node; + return propertyDeclaration + .WithAccessorList(CreateAccessorList(propertyDeclaration, expression, propertyDeclaration.SemicolonToken)) + .WithExpressionBody(null) + .WithSemicolonToken(default); + } + case SyntaxKind.IndexerDeclaration: + { + var indexerDeclaration = (IndexerDeclarationSyntax)node; - return accessor - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlockWithExpressionStatement(accessor, expression, accessor.SemicolonToken)); - } - case SyntaxKind.LocalFunctionStatement: - { - var localFunction = (LocalFunctionStatementSyntax)node; + return indexerDeclaration + .WithAccessorList(CreateAccessorList(indexerDeclaration, expression, indexerDeclaration.SemicolonToken)) + .WithExpressionBody(null) + .WithSemicolonToken(default); + } + case SyntaxKind.GetAccessorDeclaration: + { + var accessor = (AccessorDeclarationSyntax)node; - return localFunction - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(localFunction, expression, localFunction.SemicolonToken, localFunction.ReturnType, semanticModel, cancellationToken)); - } - default: - { - SyntaxDebug.Fail(node); - return node; - } - } - } + return accessor + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(accessor, expression, accessor.SemicolonToken)); + } + case SyntaxKind.SetAccessorDeclaration: + case SyntaxKind.InitAccessorDeclaration: + case SyntaxKind.AddAccessorDeclaration: + case SyntaxKind.RemoveAccessorDeclaration: + { + var accessor = (AccessorDeclarationSyntax)node; - private static BlockSyntax CreateBlock(SyntaxNode declaration, ExpressionSyntax expression, SyntaxToken semicolon, int increaseCount = 1) - { - return (expression.IsKind(SyntaxKind.ThrowExpression)) - ? CreateBlockWithExpressionStatement(declaration, expression, semicolon, increaseCount) - : CreateBlockWithReturnStatement(declaration, expression, semicolon, increaseCount); - } + return accessor + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlockWithExpressionStatement(accessor, expression, accessor.SemicolonToken)); + } + case SyntaxKind.LocalFunctionStatement: + { + var localFunction = (LocalFunctionStatementSyntax)node; - private static BlockSyntax CreateBlock( - SyntaxNode declaration, - ExpressionSyntax expression, - SyntaxToken semicolon, - TypeSyntax returnType, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - return (ShouldCreateExpressionStatement(returnType, expression, semanticModel, cancellationToken)) - ? CreateBlockWithExpressionStatement(declaration, expression, semicolon) - : CreateBlockWithReturnStatement(declaration, expression, semicolon); + return localFunction + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(localFunction, expression, localFunction.SemicolonToken, localFunction.ReturnType, semanticModel, cancellationToken)); + } + default: + { + SyntaxDebug.Fail(node); + return node; + } + } + } - static bool ShouldCreateExpressionStatement( - TypeSyntax returnType, + private static BlockSyntax CreateBlock(SyntaxNode declaration, ExpressionSyntax expression, SyntaxToken semicolon, int increaseCount = 1) + { + return (expression.IsKind(SyntaxKind.ThrowExpression)) + ? CreateBlockWithExpressionStatement(declaration, expression, semicolon, increaseCount) + : CreateBlockWithReturnStatement(declaration, expression, semicolon, increaseCount); + } + + private static BlockSyntax CreateBlock( + SyntaxNode declaration, ExpressionSyntax expression, + SyntaxToken semicolon, + TypeSyntax returnType, SemanticModel semanticModel, CancellationToken cancellationToken) { - if (returnType == null) - return true; - - if (returnType.IsVoid()) - return true; - - switch (expression.Kind()) + return (ShouldCreateExpressionStatement(returnType, expression, semanticModel, cancellationToken)) + ? CreateBlockWithExpressionStatement(declaration, expression, semicolon) + : CreateBlockWithReturnStatement(declaration, expression, semicolon); + + static bool ShouldCreateExpressionStatement( + TypeSyntax returnType, + ExpressionSyntax expression, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - case SyntaxKind.ThrowExpression: - { - return true; - } - case SyntaxKind.AwaitExpression: - { - ITypeSymbol originalDefinition = semanticModel - .GetTypeSymbol(returnType, cancellationToken) - .OriginalDefinition; + if (returnType is null) + return true; + + if (returnType.IsVoid()) + return true; - if (!originalDefinition.HasMetadataName(MetadataNames.System_Threading_Tasks_ValueTask_T) - && !originalDefinition.EqualsOrInheritsFrom(MetadataNames.System_Threading_Tasks_Task_T)) + switch (expression.Kind()) + { + case SyntaxKind.ThrowExpression: { return true; } + case SyntaxKind.AwaitExpression: + { + ITypeSymbol originalDefinition = semanticModel + .GetTypeSymbol(returnType, cancellationToken) + .OriginalDefinition; - break; - } - } - - return false; - } - } + if (!originalDefinition.HasMetadataName(MetadataNames.System_Threading_Tasks_ValueTask_T) + && !originalDefinition.EqualsOrInheritsFrom(MetadataNames.System_Threading_Tasks_Task_T)) + { + return true; + } - private static AccessorListSyntax CreateAccessorList( - SyntaxNode declaration, - ExpressionSyntax expression, - SyntaxToken semicolon) - { - BlockSyntax block = CreateBlock(declaration, expression, semicolon, increaseCount: 2); + break; + } + } - AccessorListSyntax accessorList = AccessorList(GetAccessorDeclaration(block)); + return false; + } + } - if (expression.IsSingleLine()) + private static AccessorListSyntax CreateAccessorList( + SyntaxNode declaration, + ExpressionSyntax expression, + SyntaxToken semicolon) { - accessorList = accessorList - .RemoveWhitespace() - .WithCloseBraceToken(accessorList.CloseBraceToken.WithLeadingTrivia(NewLine())) - .WithFormatterAnnotation(); - } + BlockSyntax block = CreateBlock(declaration, expression, semicolon, increaseCount: 2); - return accessorList; - } + AccessorListSyntax accessorList = AccessorList(GetAccessorDeclaration(block)); - private static BlockSyntax CreateBlockWithExpressionStatement( - SyntaxNode declaration, - ExpressionSyntax expression, - SyntaxToken semicolon, - int increaseCount = 1) - { - return CreateBlock( - declaration, - expression, - semicolon, - (e, s) => + if (expression.IsSingleLine()) { - if (e is ThrowExpressionSyntax throwExpression) - { - return ThrowStatement(Token(SyntaxKind.ThrowKeyword), throwExpression.Expression, s); - } - else + accessorList = accessorList + .RemoveWhitespace() + .WithCloseBraceToken(accessorList.CloseBraceToken.WithLeadingTrivia(NewLine())) + .WithFormatterAnnotation(); + } + + return accessorList; + } + + private static BlockSyntax CreateBlockWithExpressionStatement( + SyntaxNode declaration, + ExpressionSyntax expression, + SyntaxToken semicolon, + int increaseCount = 1) + { + return CreateBlock( + declaration, + expression, + semicolon, + (e, s) => { - return ExpressionStatement(e, s); - } - }, - increaseCount: increaseCount); - } + if (e is ThrowExpressionSyntax throwExpression) + { + return ThrowStatement(Token(SyntaxKind.ThrowKeyword), throwExpression.Expression, s); + } + else + { + return ExpressionStatement(e, s); + } + }, + increaseCount: increaseCount); + } - private static BlockSyntax CreateBlockWithReturnStatement( - SyntaxNode declaration, - ExpressionSyntax expression, - SyntaxToken semicolon, - int increaseCount = 1) - { - return CreateBlock( - declaration, - expression, - semicolon, - (e, s) => ReturnStatement(Token(SyntaxKind.ReturnKeyword), e, s), - increaseCount: increaseCount); - } + private static BlockSyntax CreateBlockWithReturnStatement( + SyntaxNode declaration, + ExpressionSyntax expression, + SyntaxToken semicolon, + int increaseCount = 1) + { + return CreateBlock( + declaration, + expression, + semicolon, + (e, s) => ReturnStatement(Token(SyntaxKind.ReturnKeyword), e, s), + increaseCount: increaseCount); + } - private static BlockSyntax CreateBlock( - SyntaxNode declaration, - ExpressionSyntax expression, - SyntaxToken semicolon, - Func createStatement, - int increaseCount = 1) - { - expression = SyntaxTriviaAnalysis.SetIndentation(expression, declaration, increaseCount: increaseCount); + private static BlockSyntax CreateBlock( + SyntaxNode declaration, + ExpressionSyntax expression, + SyntaxToken semicolon, + Func createStatement, + int increaseCount = 1) + { + expression = SyntaxTriviaAnalysis.SetIndentation(expression, declaration, increaseCount: increaseCount); - return Block( - Token(SyntaxKind.OpenBraceToken).WithFormatterAnnotation(), - createStatement(expression, semicolon), - Token(SyntaxKind.CloseBraceToken).WithFormatterAnnotation()); + return Block( + Token(SyntaxKind.OpenBraceToken).WithFormatterAnnotation(), + createStatement(expression, semicolon), + Token(SyntaxKind.CloseBraceToken).WithFormatterAnnotation()); + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/ConvertInterpolatedStringToStringBuilderMethodRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ConvertInterpolatedStringToStringBuilderMethodRefactoring.cs index 81ccc2f36c..700c5dc13d 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ConvertInterpolatedStringToStringBuilderMethodRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ConvertInterpolatedStringToStringBuilderMethodRefactoring.cs @@ -9,77 +9,78 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class ConvertInterpolatedStringToStringBuilderMethodRefactoring +namespace Roslynator.CSharp.Refactorings { - public static (SyntaxKind contentKind, string methodName, ImmutableArray arguments) - Refactor(InterpolatedStringContentSyntax content, bool isVerbatim) + internal static class ConvertInterpolatedStringToStringBuilderMethodRefactoring { - if (content == null) - throw new ArgumentNullException(nameof(content)); - - SyntaxKind kind = content.Kind(); - - switch (kind) + public static (SyntaxKind contentKind, string methodName, ImmutableArray arguments) + Refactor(InterpolatedStringContentSyntax content, bool isVerbatim) { - case SyntaxKind.Interpolation: - { - var interpolation = (InterpolationSyntax)content; + if (content is null) + throw new ArgumentNullException(nameof(content)); - InterpolationAlignmentClauseSyntax alignmentClause = interpolation.AlignmentClause; - InterpolationFormatClauseSyntax formatClause = interpolation.FormatClause; + SyntaxKind kind = content.Kind(); - if (alignmentClause != null - || formatClause != null) + switch (kind) + { + case SyntaxKind.Interpolation: { - StringBuilder sb = StringBuilderCache.GetInstance(); + var interpolation = (InterpolationSyntax)content; - sb.Append("\"{0"); + InterpolationAlignmentClauseSyntax alignmentClause = interpolation.AlignmentClause; + InterpolationFormatClauseSyntax formatClause = interpolation.FormatClause; - if (alignmentClause != null) + if (alignmentClause is not null + || formatClause is not null) { - sb.Append(','); - sb.Append(alignmentClause.Value.ToString()); - } + StringBuilder sb = StringBuilderCache.GetInstance(); - if (formatClause != null) - { - sb.Append(':'); - sb.Append(formatClause.FormatStringToken.Text); - } + sb.Append("\"{0"); + + if (alignmentClause is not null) + { + sb.Append(','); + sb.Append(alignmentClause.Value.ToString()); + } + + if (formatClause is not null) + { + sb.Append(':'); + sb.Append(formatClause.FormatStringToken.Text); + } - sb.Append("}\""); + sb.Append("}\""); - ExpressionSyntax expression = ParseExpression(StringBuilderCache.GetStringAndFree(sb)); + ExpressionSyntax expression = ParseExpression(StringBuilderCache.GetStringAndFree(sb)); - return (kind, "AppendFormat", ImmutableArray.Create(Argument(expression), Argument(interpolation.Expression))); + return (kind, "AppendFormat", ImmutableArray.Create(Argument(expression), Argument(interpolation.Expression))); + } + else + { + return (kind, "Append", ImmutableArray.Create(Argument(interpolation.Expression))); + } } - else + case SyntaxKind.InterpolatedStringText: { - return (kind, "Append", ImmutableArray.Create(Argument(interpolation.Expression))); - } - } - case SyntaxKind.InterpolatedStringText: - { - var interpolatedStringText = (InterpolatedStringTextSyntax)content; + var interpolatedStringText = (InterpolatedStringTextSyntax)content; - string text = interpolatedStringText.TextToken.Text; + string text = interpolatedStringText.TextToken.Text; - text = StringUtility.ReplaceDoubleBracesWithSingleBrace(text); + text = StringUtility.ReplaceDoubleBracesWithSingleBrace(text); - text = (isVerbatim) - ? "@\"" + text + "\"" - : "\"" + text + "\""; + text = (isVerbatim) + ? "@\"" + text + "\"" + : "\"" + text + "\""; - ExpressionSyntax stringLiteral = ParseExpression(text); + ExpressionSyntax stringLiteral = ParseExpression(text); - return (kind, "Append", ImmutableArray.Create(Argument(stringLiteral))); - } - default: - { - throw new ArgumentException("", nameof(content)); - } + return (kind, "Append", ImmutableArray.Create(Argument(stringLiteral))); + } + default: + { + throw new ArgumentException("", nameof(content)); + } + } } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/CopyMemberDeclarationRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/CopyMemberDeclarationRefactoring.cs index 47342fc865..a0446d4d5f 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/CopyMemberDeclarationRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/CopyMemberDeclarationRefactoring.cs @@ -11,180 +11,181 @@ using Roslynator.CSharp.Syntax; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class CopyMemberDeclarationRefactoring +namespace Roslynator.CSharp.Refactorings { - public static async Task RefactorAsync( - Document document, - MemberDeclarationSyntax member, - bool copyAfter = true, - CancellationToken cancellationToken = default) + internal static class CopyMemberDeclarationRefactoring { - MemberDeclarationSyntax newMember = member; - - SyntaxToken identifier = GetIdentifier(member); - - if (identifier != default) + public static async Task RefactorAsync( + Document document, + MemberDeclarationSyntax member, + bool copyAfter = true, + CancellationToken cancellationToken = default) { - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + MemberDeclarationSyntax newMember = member; - string newName = identifier.ValueText; + SyntaxToken identifier = GetIdentifier(member); - if (!member.IsKind(SyntaxKind.ConstructorDeclaration)) + if (identifier != default) { - newName = NameGenerator.Default.EnsureUniqueName(newName, semanticModel, member.SpanStart); + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - ISymbol symbol = semanticModel.GetDeclaredSymbol(member, cancellationToken); + string newName = identifier.ValueText; - ImmutableArray references = await SyntaxFinder.FindReferencesAsync(symbol, document.Solution(), documents: ImmutableHashSet.Create(document), cancellationToken: cancellationToken).ConfigureAwait(false); + if (!member.IsKind(SyntaxKind.ConstructorDeclaration)) + { + newName = NameGenerator.Default.EnsureUniqueName(newName, semanticModel, member.SpanStart); - SyntaxToken newIdentifier = SyntaxFactory.Identifier(newName); + ISymbol symbol = semanticModel.GetDeclaredSymbol(member, cancellationToken); - newMember = member.ReplaceNodes( - references.Where(n => member.Contains(n)), - (n, _) => - { - if (n is IdentifierNameSyntax identifierName) - { - return identifierName.WithIdentifier(newIdentifier.WithTriviaFrom(identifierName.Identifier)); - } - else - { - SyntaxDebug.Assert(n.IsKind(SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer), n); + ImmutableArray references = await SyntaxFinder.FindReferencesAsync(symbol, document.Solution(), documents: ImmutableHashSet.Create(document), cancellationToken: cancellationToken).ConfigureAwait(false); - return n; - } - }); + SyntaxToken newIdentifier = SyntaxFactory.Identifier(newName); - newMember = SetIdentifier(newMember, newIdentifier.WithRenameAnnotation()); + newMember = member.ReplaceNodes( + references.Where(n => member.Contains(n)), + (n, _) => + { + if (n is IdentifierNameSyntax identifierName) + { + return identifierName.WithIdentifier(newIdentifier.WithTriviaFrom(identifierName.Identifier)); + } + else + { + SyntaxDebug.Assert(n.IsKind(SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer), n); + + return n; + } + }); + + newMember = SetIdentifier(newMember, newIdentifier.WithRenameAnnotation()); + } + } + else + { + newMember = newMember.WithNavigationAnnotation(); } - } - else - { - newMember = newMember.WithNavigationAnnotation(); - } - MemberDeclarationListInfo memberList = SyntaxInfo.MemberDeclarationListInfo(member.Parent); + MemberDeclarationListInfo memberList = SyntaxInfo.MemberDeclarationListInfo(member.Parent); - int index = memberList.IndexOf(member); + int index = memberList.IndexOf(member); - if (index == 0) - { - if (copyAfter) + if (index == 0) { - SyntaxToken? openBrace = memberList.OpenBraceToken; - - if (openBrace != null - && openBrace.Value.GetFullSpanEndLine() == member.GetFullSpanStartLine()) + if (copyAfter) { - newMember = newMember.WithLeadingTrivia(member.GetLeadingTrivia().Insert(0, NewLine())); + SyntaxToken? openBrace = memberList.OpenBraceToken; + + if (openBrace is not null + && openBrace.Value.GetFullSpanEndLine() == member.GetFullSpanStartLine()) + { + newMember = newMember.WithLeadingTrivia(member.GetLeadingTrivia().Insert(0, NewLine())); + } } - } - else - { - SyntaxToken? closeBrace = memberList.CloseBraceToken; + else + { + SyntaxToken? closeBrace = memberList.CloseBraceToken; - if (closeBrace != null) - newMember = newMember.WithTrailingTrivia(member.GetTrailingTrivia().Add(NewLine())); + if (closeBrace is not null) + newMember = newMember.WithTrailingTrivia(member.GetTrailingTrivia().Add(NewLine())); + } } - } - int insertIndex = (copyAfter) ? index + 1 : index; + int insertIndex = (copyAfter) ? index + 1 : index; - return await document.ReplaceMembersAsync(memberList, memberList.Members.Insert(insertIndex, newMember), cancellationToken).ConfigureAwait(false); - } + return await document.ReplaceMembersAsync(memberList, memberList.Members.Insert(insertIndex, newMember), cancellationToken).ConfigureAwait(false); + } - public static Task RefactorAsync( - Document document, - LocalFunctionStatementSyntax localFunction, - bool copyAfter = true, - CancellationToken cancellationToken = default) - { - StatementListInfo statementsInfos = SyntaxInfo.StatementListInfo(localFunction); + public static Task RefactorAsync( + Document document, + LocalFunctionStatementSyntax localFunction, + bool copyAfter = true, + CancellationToken cancellationToken = default) + { + StatementListInfo statementsInfos = SyntaxInfo.StatementListInfo(localFunction); - SyntaxList statements = statementsInfos.Statements; - int index = statements.IndexOf(localFunction); + SyntaxList statements = statementsInfos.Statements; + int index = statements.IndexOf(localFunction); - if (index == 0) - { - if (copyAfter) + if (index == 0) { - if (statementsInfos.ParentAsBlock.OpenBraceToken.GetFullSpanEndLine() == localFunction.GetFullSpanStartLine()) + if (copyAfter) { - localFunction = localFunction.WithLeadingTrivia(localFunction.GetLeadingTrivia().Insert(0, NewLine())); + if (statementsInfos.ParentAsBlock.OpenBraceToken.GetFullSpanEndLine() == localFunction.GetFullSpanStartLine()) + { + localFunction = localFunction.WithLeadingTrivia(localFunction.GetLeadingTrivia().Insert(0, NewLine())); + } + } + else + { + localFunction = localFunction.WithTrailingTrivia(localFunction.GetTrailingTrivia().Add(NewLine())); } } - else - { - localFunction = localFunction.WithTrailingTrivia(localFunction.GetTrailingTrivia().Add(NewLine())); - } - } - int insertIndex = (copyAfter) ? index + 1 : index; + int insertIndex = (copyAfter) ? index + 1 : index; - SyntaxList newStatements = statements.Insert(insertIndex, localFunction.WithNavigationAnnotation()); + SyntaxList newStatements = statements.Insert(insertIndex, localFunction.WithNavigationAnnotation()); - return document.ReplaceStatementsAsync(statementsInfos, newStatements, cancellationToken); - } + return document.ReplaceStatementsAsync(statementsInfos, newStatements, cancellationToken); + } - private static SyntaxToken GetIdentifier(SyntaxNode node) - { - switch (node.Kind()) + private static SyntaxToken GetIdentifier(SyntaxNode node) { - case SyntaxKind.ClassDeclaration: - return ((ClassDeclarationSyntax)node).Identifier; - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return ((RecordDeclarationSyntax)node).Identifier; - case SyntaxKind.StructDeclaration: - return ((StructDeclarationSyntax)node).Identifier; - case SyntaxKind.InterfaceDeclaration: - return ((InterfaceDeclarationSyntax)node).Identifier; - case SyntaxKind.EnumDeclaration: - return ((EnumDeclarationSyntax)node).Identifier; - case SyntaxKind.DelegateDeclaration: - return ((DelegateDeclarationSyntax)node).Identifier; - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)node).Identifier; - case SyntaxKind.ConstructorDeclaration: - return ((ConstructorDeclarationSyntax)node).Identifier; - case SyntaxKind.PropertyDeclaration: - return ((PropertyDeclarationSyntax)node).Identifier; - case SyntaxKind.EventDeclaration: - return ((EventDeclarationSyntax)node).Identifier; - } + switch (node.Kind()) + { + case SyntaxKind.ClassDeclaration: + return ((ClassDeclarationSyntax)node).Identifier; + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((RecordDeclarationSyntax)node).Identifier; + case SyntaxKind.StructDeclaration: + return ((StructDeclarationSyntax)node).Identifier; + case SyntaxKind.InterfaceDeclaration: + return ((InterfaceDeclarationSyntax)node).Identifier; + case SyntaxKind.EnumDeclaration: + return ((EnumDeclarationSyntax)node).Identifier; + case SyntaxKind.DelegateDeclaration: + return ((DelegateDeclarationSyntax)node).Identifier; + case SyntaxKind.MethodDeclaration: + return ((MethodDeclarationSyntax)node).Identifier; + case SyntaxKind.ConstructorDeclaration: + return ((ConstructorDeclarationSyntax)node).Identifier; + case SyntaxKind.PropertyDeclaration: + return ((PropertyDeclarationSyntax)node).Identifier; + case SyntaxKind.EventDeclaration: + return ((EventDeclarationSyntax)node).Identifier; + } - return default; - } + return default; + } - private static MemberDeclarationSyntax SetIdentifier(MemberDeclarationSyntax member, SyntaxToken identifier) - { - switch (member.Kind()) + private static MemberDeclarationSyntax SetIdentifier(MemberDeclarationSyntax member, SyntaxToken identifier) { - case SyntaxKind.ClassDeclaration: - return ((ClassDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.RecordDeclaration: - case SyntaxKind.RecordStructDeclaration: - return ((RecordDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.StructDeclaration: - return ((StructDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.InterfaceDeclaration: - return ((InterfaceDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.EnumDeclaration: - return ((EnumDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.DelegateDeclaration: - return ((DelegateDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.MethodDeclaration: - return ((MethodDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.ConstructorDeclaration: - return ((ConstructorDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.PropertyDeclaration: - return ((PropertyDeclarationSyntax)member).WithIdentifier(identifier); - case SyntaxKind.EventDeclaration: - return ((EventDeclarationSyntax)member).WithIdentifier(identifier); - } + switch (member.Kind()) + { + case SyntaxKind.ClassDeclaration: + return ((ClassDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.RecordDeclaration: + case SyntaxKind.RecordStructDeclaration: + return ((RecordDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.StructDeclaration: + return ((StructDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.InterfaceDeclaration: + return ((InterfaceDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.EnumDeclaration: + return ((EnumDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.DelegateDeclaration: + return ((DelegateDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.MethodDeclaration: + return ((MethodDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.ConstructorDeclaration: + return ((ConstructorDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.PropertyDeclaration: + return ((PropertyDeclarationSyntax)member).WithIdentifier(identifier); + case SyntaxKind.EventDeclaration: + return ((EventDeclarationSyntax)member).WithIdentifier(identifier); + } - throw new InvalidOperationException(); + throw new InvalidOperationException(); + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/GenerateBaseConstructorsRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/GenerateBaseConstructorsRefactoring.cs index 9fa1c2ea9c..f448892c70 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/GenerateBaseConstructorsRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/GenerateBaseConstructorsRefactoring.cs @@ -11,141 +11,142 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class GenerateBaseConstructorsRefactoring +namespace Roslynator.CSharp.Refactorings { - public static Task RefactorAsync( - Document document, - ClassDeclarationSyntax classDeclaration, - IMethodSymbol[] constructorSymbols, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) + internal static class GenerateBaseConstructorsRefactoring { - SyntaxList members = classDeclaration.Members; - - string className = classDeclaration.Identifier.ValueText; + public static Task RefactorAsync( + Document document, + ClassDeclarationSyntax classDeclaration, + IMethodSymbol[] constructorSymbols, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + SyntaxList members = classDeclaration.Members; - bool isSealedClass = classDeclaration.Modifiers.Contains(SyntaxKind.SealedKeyword); + string className = classDeclaration.Identifier.ValueText; - int insertIndex = MemberDeclarationInserter.Default.GetInsertIndex(members, SyntaxKind.ConstructorDeclaration); + bool isSealedClass = classDeclaration.Modifiers.Contains(SyntaxKind.SealedKeyword); - int position = (insertIndex == 0) - ? classDeclaration.OpenBraceToken.FullSpan.End - : members[insertIndex - 1].FullSpan.End; + int insertIndex = MemberDeclarationInserter.Default.GetInsertIndex(members, SyntaxKind.ConstructorDeclaration); - IEnumerable constructors = constructorSymbols - .Select(symbol => CreateConstructor(symbol, className, isSealedClass, semanticModel, position)); + int position = (insertIndex == 0) + ? classDeclaration.OpenBraceToken.FullSpan.End + : members[insertIndex - 1].FullSpan.End; - ClassDeclarationSyntax newClassDeclaration = classDeclaration - .WithMembers(members.InsertRange(insertIndex, constructors)); + IEnumerable constructors = constructorSymbols + .Select(symbol => CreateConstructor(symbol, className, isSealedClass, semanticModel, position)); - return document.ReplaceNodeAsync(classDeclaration, newClassDeclaration, cancellationToken); - } + ClassDeclarationSyntax newClassDeclaration = classDeclaration + .WithMembers(members.InsertRange(insertIndex, constructors)); - public static Task RefactorAsync( - Document document, - RecordDeclarationSyntax recordDeclaration, - IMethodSymbol[] constructorSymbols, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - SyntaxList members = recordDeclaration.Members; + return document.ReplaceNodeAsync(classDeclaration, newClassDeclaration, cancellationToken); + } - string recordName = recordDeclaration.Identifier.ValueText; + public static Task RefactorAsync( + Document document, + RecordDeclarationSyntax recordDeclaration, + IMethodSymbol[] constructorSymbols, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) + { + SyntaxList members = recordDeclaration.Members; - bool isSealedClass = recordDeclaration.Modifiers.Contains(SyntaxKind.SealedKeyword); + string recordName = recordDeclaration.Identifier.ValueText; - int insertIndex = MemberDeclarationInserter.Default.GetInsertIndex(members, SyntaxKind.ConstructorDeclaration); + bool isSealedClass = recordDeclaration.Modifiers.Contains(SyntaxKind.SealedKeyword); - int position = (insertIndex == 0) - ? recordDeclaration.OpenBraceToken.FullSpan.End - : members[insertIndex - 1].FullSpan.End; + int insertIndex = MemberDeclarationInserter.Default.GetInsertIndex(members, SyntaxKind.ConstructorDeclaration); - IEnumerable constructors = constructorSymbols - .Select(symbol => CreateConstructor(symbol, recordName, isSealedClass, semanticModel, position)); + int position = (insertIndex == 0) + ? recordDeclaration.OpenBraceToken.FullSpan.End + : members[insertIndex - 1].FullSpan.End; - RecordDeclarationSyntax newRecordDeclaration = recordDeclaration - .WithMembers(members.InsertRange(insertIndex, constructors)); + IEnumerable constructors = constructorSymbols + .Select(symbol => CreateConstructor(symbol, recordName, isSealedClass, semanticModel, position)); - return document.ReplaceNodeAsync(recordDeclaration, newRecordDeclaration, cancellationToken); - } + RecordDeclarationSyntax newRecordDeclaration = recordDeclaration + .WithMembers(members.InsertRange(insertIndex, constructors)); - private static ConstructorDeclarationSyntax CreateConstructor( - IMethodSymbol methodSymbol, - string className, - bool isSealedClass, - SemanticModel semanticModel, - int position) - { - var parameters = new List(); - var arguments = new List(); + return document.ReplaceNodeAsync(recordDeclaration, newRecordDeclaration, cancellationToken); + } - foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) + private static ConstructorDeclarationSyntax CreateConstructor( + IMethodSymbol methodSymbol, + string className, + bool isSealedClass, + SemanticModel semanticModel, + int position) { - EqualsValueClauseSyntax @default = null; + var parameters = new List(); + var arguments = new List(); - if (parameterSymbol.HasExplicitDefaultValue) + foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) { - ExpressionSyntax defaultValue = parameterSymbol.GetDefaultValueMinimalSyntax(semanticModel, position); + EqualsValueClauseSyntax @default = null; - if (defaultValue != null) - @default = EqualsValueClause(defaultValue.WithSimplifierAnnotation()); - } + if (parameterSymbol.HasExplicitDefaultValue) + { + ExpressionSyntax defaultValue = parameterSymbol.GetDefaultValueMinimalSyntax(semanticModel, position); - parameters.Add(Parameter( - default(SyntaxList), - CreateModifiers(parameterSymbol), - parameterSymbol.Type.ToTypeSyntax().WithSimplifierAnnotation(), - Identifier(parameterSymbol.Name), - @default)); + if (defaultValue is not null) + @default = EqualsValueClause(defaultValue.WithSimplifierAnnotation()); + } - arguments.Add(Argument(IdentifierName(parameterSymbol.Name))); - } - - Accessibility accessibility = methodSymbol.DeclaredAccessibility; + parameters.Add(Parameter( + default(SyntaxList), + CreateModifiers(parameterSymbol), + parameterSymbol.Type.ToTypeSyntax().WithSimplifierAnnotation(), + Identifier(parameterSymbol.Name), + @default)); - if (isSealedClass) - { - if (accessibility == Accessibility.ProtectedOrInternal) - { - accessibility = Accessibility.Internal; + arguments.Add(Argument(IdentifierName(parameterSymbol.Name))); } - else if (accessibility == Accessibility.Protected - || accessibility == Accessibility.ProtectedAndInternal) + + Accessibility accessibility = methodSymbol.DeclaredAccessibility; + + if (isSealedClass) { - accessibility = Accessibility.Private; + if (accessibility == Accessibility.ProtectedOrInternal) + { + accessibility = Accessibility.Internal; + } + else if (accessibility == Accessibility.Protected + || accessibility == Accessibility.ProtectedAndInternal) + { + accessibility = Accessibility.Private; + } } - } - ConstructorDeclarationSyntax constructor = ConstructorDeclaration( - default(SyntaxList), - TokenList(accessibility), - Identifier(className), - ParameterList(SeparatedList(parameters)), - BaseConstructorInitializer(ArgumentList(arguments.ToArray())), - Block()); - - return constructor.WithFormatterAnnotation(); - } + ConstructorDeclarationSyntax constructor = ConstructorDeclaration( + default(SyntaxList), + TokenList(accessibility), + Identifier(className), + ParameterList(SeparatedList(parameters)), + BaseConstructorInitializer(ArgumentList(arguments.ToArray())), + Block()); - private static SyntaxTokenList CreateModifiers(IParameterSymbol parameterSymbol) - { - if (parameterSymbol.IsParams) - return TokenList(SyntaxKind.ParamsKeyword); + return constructor.WithFormatterAnnotation(); + } - switch (parameterSymbol.RefKind) + private static SyntaxTokenList CreateModifiers(IParameterSymbol parameterSymbol) { - case RefKind.None: - return default; - case RefKind.Ref: - return TokenList(SyntaxKind.RefKeyword); - case RefKind.Out: - return TokenList(SyntaxKind.OutKeyword); - } + if (parameterSymbol.IsParams) + return TokenList(SyntaxKind.ParamsKeyword); - Debug.Fail(parameterSymbol.RefKind.ToString()); + switch (parameterSymbol.RefKind) + { + case RefKind.None: + return default; + case RefKind.Ref: + return TokenList(SyntaxKind.RefKeyword); + case RefKind.Out: + return TokenList(SyntaxKind.OutKeyword); + } + + Debug.Fail(parameterSymbol.RefKind.ToString()); - return default; + return default; + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/IfRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/IfRefactoring.cs index 3e506891af..6ab20338bd 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/IfRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/IfRefactoring.cs @@ -13,538 +13,539 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class IfRefactoring +namespace Roslynator.CSharp.Refactorings { - public static Task RefactorAsync(Document document, IfAnalysis ifAnalysis, CancellationToken cancellationToken = default) + internal static class IfRefactoring { - switch (ifAnalysis.Kind) + public static Task RefactorAsync(Document document, IfAnalysis ifAnalysis, CancellationToken cancellationToken = default) { - case IfAnalysisKind.IfElseToAssignmentWithCoalesceExpression: - { - return IfElseToAssignmentWithCoalesceExpressionAsync(document, (IfElseToAssignmentWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfElseToAssignmentWithConditionalExpression: - { - return IfElseToAssignmentWithConditionalExpressionAsync(document, (IfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.AssignmentAndIfToAssignmentWithConditionalExpression: - { - var analysis = (AssignmentAndIfToAssignmentWithConditionalExpressionAnalysis)ifAnalysis; + switch (ifAnalysis.Kind) + { + case IfAnalysisKind.IfElseToAssignmentWithCoalesceExpression: + { + return IfElseToAssignmentWithCoalesceExpressionAsync(document, (IfElseToAssignmentWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfElseToAssignmentWithConditionalExpression: + { + return IfElseToAssignmentWithConditionalExpressionAsync(document, (IfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.AssignmentAndIfToAssignmentWithConditionalExpression: + { + 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); - } - case IfAnalysisKind.LocalDeclarationAndIfElseAssignmentWithConditionalExpression: - { - var analysis = (LocalDeclarationAndIfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis; + return ToAssignmentWithConditionalExpressionAsync(document, analysis, newStatement, cancellationToken); + } + case IfAnalysisKind.LocalDeclarationAndIfElseAssignmentWithConditionalExpression: + { + 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 != 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); - } - case IfAnalysisKind.IfElseToAssignmentWithExpression: - { - return IfElseToAssignmentWithExpressionAsync(document, (IfElseToAssignmentWithExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfElseToAssignmentWithCondition: - { - return IfElseToAssignmentWithConditionAsync(document, (IfElseToAssignmentWithConditionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfElseToReturnWithCoalesceExpression: - case IfAnalysisKind.IfElseToYieldReturnWithCoalesceExpression: - case IfAnalysisKind.IfReturnToReturnWithCoalesceExpression: - { - return IfToReturnWithCoalesceExpressionAsync(document, (IfToReturnWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfElseToReturnWithConditionalExpression: - { - return IfElseToReturnWithConditionalExpressionAsync(document, (IfElseToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfElseToReturnWithBooleanExpression: - { - return IfElseToReturnWithBooleanExpressionAsync(document, (IfElseToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfElseToReturnWithExpression: - case IfAnalysisKind.IfElseToYieldReturnWithExpression: - case IfAnalysisKind.IfReturnToReturnWithExpression: - { - return IfToReturnWithExpressionAsync(document, (IfToReturnWithExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfElseToYieldReturnWithConditionalExpression: - { - return IfElseToYieldReturnWithConditionalExpressionAsync(document, (IfElseToYieldReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfElseToYieldReturnWithBooleanExpression: - { - return IfElseToYieldReturnWithBooleanExpressionAsync(document, (IfElseToYieldReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfReturnToReturnWithConditionalExpression: - { - return IfReturnToReturnWithConditionalExpressionAsync(document, (IfReturnToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); - } - case IfAnalysisKind.IfReturnToReturnWithBooleanExpression: - { - return IfReturnToReturnWithBooleanExpressionAsync(document, (IfReturnToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); - } - default: - { - throw new InvalidOperationException(); - } + return ToAssignmentWithConditionalExpressionAsync(document, analysis, newStatement, cancellationToken); + } + case IfAnalysisKind.IfElseToAssignmentWithExpression: + { + return IfElseToAssignmentWithExpressionAsync(document, (IfElseToAssignmentWithExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfElseToAssignmentWithCondition: + { + return IfElseToAssignmentWithConditionAsync(document, (IfElseToAssignmentWithConditionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfElseToReturnWithCoalesceExpression: + case IfAnalysisKind.IfElseToYieldReturnWithCoalesceExpression: + case IfAnalysisKind.IfReturnToReturnWithCoalesceExpression: + { + return IfToReturnWithCoalesceExpressionAsync(document, (IfToReturnWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfElseToReturnWithConditionalExpression: + { + return IfElseToReturnWithConditionalExpressionAsync(document, (IfElseToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfElseToReturnWithBooleanExpression: + { + return IfElseToReturnWithBooleanExpressionAsync(document, (IfElseToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfElseToReturnWithExpression: + case IfAnalysisKind.IfElseToYieldReturnWithExpression: + case IfAnalysisKind.IfReturnToReturnWithExpression: + { + return IfToReturnWithExpressionAsync(document, (IfToReturnWithExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfElseToYieldReturnWithConditionalExpression: + { + return IfElseToYieldReturnWithConditionalExpressionAsync(document, (IfElseToYieldReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfElseToYieldReturnWithBooleanExpression: + { + return IfElseToYieldReturnWithBooleanExpressionAsync(document, (IfElseToYieldReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfReturnToReturnWithConditionalExpression: + { + return IfReturnToReturnWithConditionalExpressionAsync(document, (IfReturnToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); + } + case IfAnalysisKind.IfReturnToReturnWithBooleanExpression: + { + return IfReturnToReturnWithBooleanExpressionAsync(document, (IfReturnToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); + } + default: + { + throw new InvalidOperationException(); + } + } } - } - - private static Task IfElseToAssignmentWithCoalesceExpressionAsync( - Document document, - IfElseToAssignmentWithCoalesceExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - IfStatementSyntax ifStatement = analysis.IfStatement; - - BinaryExpressionSyntax coalesceExpression = CreateCoalesceExpression( - analysis.Right1.WithoutTrivia(), - analysis.Right2.WithoutTrivia(), - analysis.SemanticModel.GetTypeSymbol(analysis.Left, cancellationToken), - ifStatement.SpanStart, - analysis.SemanticModel); - - ExpressionStatementSyntax newNode = SimpleAssignmentStatement(analysis.Left.WithoutTrivia(), coalesceExpression) - .WithTriviaFrom(ifStatement) - .WithFormatterAnnotation(); - - return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); - } - private static Task IfElseToAssignmentWithConditionalExpressionAsync( - Document document, - IfElseToAssignmentWithConditionalExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - IfStatementSyntax ifStatement = analysis.IfStatement; + private static Task IfElseToAssignmentWithCoalesceExpressionAsync( + Document document, + IfElseToAssignmentWithCoalesceExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + IfStatementSyntax ifStatement = analysis.IfStatement; - ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.WhenTrue, analysis.WhenFalse); + BinaryExpressionSyntax coalesceExpression = CreateCoalesceExpression( + analysis.Right1.WithoutTrivia(), + analysis.Right2.WithoutTrivia(), + analysis.SemanticModel.GetTypeSymbol(analysis.Left, cancellationToken), + ifStatement.SpanStart, + analysis.SemanticModel); - ExpressionStatementSyntax newNode = SimpleAssignmentStatement(analysis.Left, conditionalExpression) - .WithTriviaFrom(ifStatement) - .WithFormatterAnnotation(); + ExpressionStatementSyntax newNode = SimpleAssignmentStatement(analysis.Left.WithoutTrivia(), coalesceExpression) + .WithTriviaFrom(ifStatement) + .WithFormatterAnnotation(); - return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); + } - private static Task ToAssignmentWithConditionalExpressionAsync( - Document document, - ToAssignmentWithConditionalExpressionAnalysis analysis, - StatementSyntax newStatement, - CancellationToken cancellationToken = default) - { - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(analysis.IfStatement); + private static Task IfElseToAssignmentWithConditionalExpressionAsync( + Document document, + IfElseToAssignmentWithConditionalExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + IfStatementSyntax ifStatement = analysis.IfStatement; - SyntaxList statements = statementsInfo.Statements; + ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.WhenTrue, analysis.WhenFalse); - int index = statements.IndexOf(analysis.IfStatement); + ExpressionStatementSyntax newNode = SimpleAssignmentStatement(analysis.Left, conditionalExpression) + .WithTriviaFrom(ifStatement) + .WithFormatterAnnotation(); - SyntaxList newStatements = statements - .RemoveAt(index) - .ReplaceAt(index - 1, newStatement); + return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); + } - return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); - } + private static Task ToAssignmentWithConditionalExpressionAsync( + Document document, + ToAssignmentWithConditionalExpressionAnalysis analysis, + StatementSyntax newStatement, + CancellationToken cancellationToken = default) + { + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(analysis.IfStatement); - private static Task IfElseToAssignmentWithExpressionAsync( - Document document, - IfElseToAssignmentWithExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - ExpressionStatementSyntax newNode = analysis.ExpressionStatement - .WithTriviaFrom(analysis.IfStatement) - .WithFormatterAnnotation(); + SyntaxList statements = statementsInfo.Statements; - return document.ReplaceNodeAsync(analysis.IfStatement, newNode, cancellationToken); - } + int index = statements.IndexOf(analysis.IfStatement); - private static Task IfElseToAssignmentWithConditionAsync( - Document document, - IfElseToAssignmentWithConditionAnalysis analysis, - CancellationToken cancellationToken = default) - { - ExpressionSyntax right = analysis.Right; + SyntaxList newStatements = statements + .RemoveAt(index) + .ReplaceAt(index - 1, newStatement); - if (analysis.Invert) - right = SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(right, analysis.SemanticModel, cancellationToken); + return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); + } - ExpressionStatementSyntax newNode = SimpleAssignmentStatement(analysis.Left.WithoutTrivia(), right.WithoutTrivia()) - .WithTriviaFrom(analysis.IfStatement) - .WithFormatterAnnotation(); + private static Task IfElseToAssignmentWithExpressionAsync( + Document document, + IfElseToAssignmentWithExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + ExpressionStatementSyntax newNode = analysis.ExpressionStatement + .WithTriviaFrom(analysis.IfStatement) + .WithFormatterAnnotation(); - return document.ReplaceNodeAsync(analysis.IfStatement, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(analysis.IfStatement, newNode, cancellationToken); + } - private static Task IfToReturnWithCoalesceExpressionAsync( - Document document, - IfToReturnWithCoalesceExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - IfStatementSyntax ifStatement = analysis.IfStatement; - int position = ifStatement.SpanStart; + private static Task IfElseToAssignmentWithConditionAsync( + Document document, + IfElseToAssignmentWithConditionAnalysis analysis, + CancellationToken cancellationToken = default) + { + ExpressionSyntax right = analysis.Right; - ITypeSymbol targetType = GetTargetType(); + if (analysis.Invert) + right = SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(right, analysis.SemanticModel, cancellationToken); - BinaryExpressionSyntax coalesceExpression = CreateCoalesceExpression( - analysis.Left.WithoutTrivia(), - analysis.Right.WithoutTrivia(), - targetType, - position, - analysis.SemanticModel); + ExpressionStatementSyntax newNode = SimpleAssignmentStatement(analysis.Left.WithoutTrivia(), right.WithoutTrivia()) + .WithTriviaFrom(analysis.IfStatement) + .WithFormatterAnnotation(); - StatementSyntax statement; - if (analysis.IsYield) - { - statement = YieldReturnStatement(coalesceExpression); - } - else - { - statement = ReturnStatement(coalesceExpression); + return document.ReplaceNodeAsync(analysis.IfStatement, newNode, cancellationToken); } - if (ifStatement.IsSimpleIf()) + private static Task IfToReturnWithCoalesceExpressionAsync( + Document document, + IfToReturnWithCoalesceExpressionAnalysis analysis, + CancellationToken cancellationToken = default) { - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement); + IfStatementSyntax ifStatement = analysis.IfStatement; + int position = ifStatement.SpanStart; - SyntaxList statements = statementsInfo.Statements; + ITypeSymbol targetType = GetTargetType(); - int index = statements.IndexOf(ifStatement); + BinaryExpressionSyntax coalesceExpression = CreateCoalesceExpression( + analysis.Left.WithoutTrivia(), + analysis.Right.WithoutTrivia(), + targetType, + position, + analysis.SemanticModel); - StatementSyntax newNode = statement - .WithLeadingTrivia(ifStatement.GetLeadingTrivia()) - .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia()) - .WithFormatterAnnotation(); + StatementSyntax statement; + if (analysis.IsYield) + { + statement = YieldReturnStatement(coalesceExpression); + } + else + { + statement = ReturnStatement(coalesceExpression); + } - SyntaxList newStatements = statements - .RemoveAt(index) - .ReplaceAt(index, newNode); + if (ifStatement.IsSimpleIf()) + { + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement); - return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); - } - else - { - StatementSyntax newNode = statement - .WithTriviaFrom(ifStatement) - .WithFormatterAnnotation(); + SyntaxList statements = statementsInfo.Statements; - return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); - } + int index = statements.IndexOf(ifStatement); - ITypeSymbol GetTargetType() - { - IMethodSymbol methodSymbol = analysis.SemanticModel.GetEnclosingSymbol(position, cancellationToken); + StatementSyntax newNode = statement + .WithLeadingTrivia(ifStatement.GetLeadingTrivia()) + .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia()) + .WithFormatterAnnotation(); + + SyntaxList newStatements = statements + .RemoveAt(index) + .ReplaceAt(index, newNode); + + return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); + } + else + { + StatementSyntax newNode = statement + .WithTriviaFrom(ifStatement) + .WithFormatterAnnotation(); - Debug.Assert(methodSymbol != null, ""); + return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); + } - if (methodSymbol?.IsErrorType() == false) + ITypeSymbol GetTargetType() { - ITypeSymbol returnType = methodSymbol.ReturnType; + IMethodSymbol methodSymbol = analysis.SemanticModel.GetEnclosingSymbol(position, cancellationToken); - if (!returnType.IsErrorType()) + Debug.Assert(methodSymbol is not null, ""); + + if (methodSymbol?.IsErrorType() == false) { - if (methodSymbol.IsAsync) + ITypeSymbol returnType = methodSymbol.ReturnType; + + if (!returnType.IsErrorType()) { - if (returnType.OriginalDefinition.EqualsOrInheritsFrom(MetadataNames.System_Threading_Tasks_Task_T)) + if (methodSymbol.IsAsync) + { + if (returnType.OriginalDefinition.EqualsOrInheritsFrom(MetadataNames.System_Threading_Tasks_Task_T)) + return ((INamedTypeSymbol)returnType).TypeArguments[0]; + } + else if (!analysis.IsYield) + { + return returnType; + } + else if (returnType.SpecialType == SpecialType.System_Collections_IEnumerable) + { + return analysis.SemanticModel.Compilation.ObjectType; + } + else if (returnType.OriginalDefinition.IsIEnumerableOfT()) + { return ((INamedTypeSymbol)returnType).TypeArguments[0]; - } - else if (!analysis.IsYield) - { - return returnType; - } - else if (returnType.SpecialType == SpecialType.System_Collections_IEnumerable) - { - return analysis.SemanticModel.Compilation.ObjectType; - } - else if (returnType.OriginalDefinition.IsIEnumerableOfT()) - { - return ((INamedTypeSymbol)returnType).TypeArguments[0]; + } } } - } - return null; + return null; + } } - } - private static Task IfElseToReturnWithConditionalExpressionAsync( - Document document, - IfElseToReturnWithConditionalExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - IfStatementSyntax ifStatement = analysis.IfStatement; + private static Task IfElseToReturnWithConditionalExpressionAsync( + Document document, + IfElseToReturnWithConditionalExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + IfStatementSyntax ifStatement = analysis.IfStatement; - ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2); + ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2); - StatementSyntax newNode = ReturnStatement(conditionalExpression) - .WithTriviaFrom(ifStatement) - .WithFormatterAnnotation(); + StatementSyntax newNode = ReturnStatement(conditionalExpression) + .WithTriviaFrom(ifStatement) + .WithFormatterAnnotation(); - return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); + } - private static Task IfElseToReturnWithBooleanExpressionAsync( - Document document, - IfToReturnWithBooleanExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - IfStatementSyntax ifStatement = analysis.IfStatement; + private static Task IfElseToReturnWithBooleanExpressionAsync( + Document document, + IfToReturnWithBooleanExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + IfStatementSyntax ifStatement = analysis.IfStatement; - ExpressionSyntax expression = GetBooleanExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2, document, analysis.SemanticModel, cancellationToken); + ExpressionSyntax expression = GetBooleanExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2, document, analysis.SemanticModel, cancellationToken); - StatementSyntax newNode = ReturnStatement(expression) - .WithTriviaFrom(ifStatement) - .WithFormatterAnnotation(); + StatementSyntax newNode = ReturnStatement(expression) + .WithTriviaFrom(ifStatement) + .WithFormatterAnnotation(); - return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); + } - private static Task IfToReturnWithExpressionAsync( - Document document, - IfToReturnWithExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - ExpressionSyntax expression = analysis.Expression; + private static Task IfToReturnWithExpressionAsync( + Document document, + IfToReturnWithExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + ExpressionSyntax expression = analysis.Expression; - if (analysis.Invert) - expression = SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(expression, analysis.SemanticModel, cancellationToken); + if (analysis.Invert) + expression = SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(expression, analysis.SemanticModel, cancellationToken); - StatementSyntax statement; - if (analysis.IsYield) - { - statement = YieldReturnStatement(expression); - } - else - { - statement = ReturnStatement(expression); - } + StatementSyntax statement; + if (analysis.IsYield) + { + statement = YieldReturnStatement(expression); + } + else + { + statement = ReturnStatement(expression); + } - IfStatementSyntax ifStatement = analysis.IfStatement; + IfStatementSyntax ifStatement = analysis.IfStatement; - if (ifStatement.IsSimpleIf()) - { - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement); + if (ifStatement.IsSimpleIf()) + { + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement); - SyntaxList statements = statementsInfo.Statements; + SyntaxList statements = statementsInfo.Statements; - int index = statements.IndexOf(ifStatement); + int index = statements.IndexOf(ifStatement); - StatementSyntax newNode = statement - .WithLeadingTrivia(ifStatement.GetLeadingTrivia()) - .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia()) - .WithFormatterAnnotation(); + StatementSyntax newNode = statement + .WithLeadingTrivia(ifStatement.GetLeadingTrivia()) + .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia()) + .WithFormatterAnnotation(); - SyntaxList newStatements = statements - .RemoveAt(index) - .ReplaceAt(index, newNode); + SyntaxList newStatements = statements + .RemoveAt(index) + .ReplaceAt(index, newNode); - return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); + return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); + } + else + { + StatementSyntax newNode = statement + .WithTriviaFrom(ifStatement) + .WithFormatterAnnotation(); + + return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); + } } - else + + private static Task IfElseToYieldReturnWithConditionalExpressionAsync( + Document document, + IfElseToYieldReturnWithConditionalExpressionAnalysis analysis, + CancellationToken cancellationToken = default) { - StatementSyntax newNode = statement + IfStatementSyntax ifStatement = analysis.IfStatement; + ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2); + + StatementSyntax newNode = YieldReturnStatement(conditionalExpression) .WithTriviaFrom(ifStatement) .WithFormatterAnnotation(); return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); } - } - - private static Task IfElseToYieldReturnWithConditionalExpressionAsync( - Document document, - IfElseToYieldReturnWithConditionalExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - IfStatementSyntax ifStatement = analysis.IfStatement; - ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2); - - StatementSyntax newNode = YieldReturnStatement(conditionalExpression) - .WithTriviaFrom(ifStatement) - .WithFormatterAnnotation(); - return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); - } - - private static Task IfElseToYieldReturnWithBooleanExpressionAsync( - Document document, - IfToReturnWithBooleanExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - IfStatementSyntax ifStatement = analysis.IfStatement; + private static Task IfElseToYieldReturnWithBooleanExpressionAsync( + Document document, + IfToReturnWithBooleanExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + IfStatementSyntax ifStatement = analysis.IfStatement; - ExpressionSyntax expression = GetBooleanExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2, document, analysis.SemanticModel, cancellationToken); + ExpressionSyntax expression = GetBooleanExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2, document, analysis.SemanticModel, cancellationToken); - StatementSyntax newNode = YieldReturnStatement(expression) - .WithTriviaFrom(ifStatement) - .WithFormatterAnnotation(); + StatementSyntax newNode = YieldReturnStatement(expression) + .WithTriviaFrom(ifStatement) + .WithFormatterAnnotation(); - return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken); + } - private static Task IfReturnToReturnWithConditionalExpressionAsync( - Document document, - IfReturnToReturnWithConditionalExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - IfStatementSyntax ifStatement = analysis.IfStatement; + private static Task IfReturnToReturnWithConditionalExpressionAsync( + Document document, + IfReturnToReturnWithConditionalExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + IfStatementSyntax ifStatement = analysis.IfStatement; - 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); - ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2); + ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(ifStatement.Condition, analysis.Expression1, analysis.Expression2); - StatementSyntax newStatement = ReturnStatement(conditionalExpression) - .WithLeadingTrivia(ifStatement.GetLeadingTrivia()) - .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia()) - .WithFormatterAnnotation(); + StatementSyntax newStatement = ReturnStatement(conditionalExpression) + .WithLeadingTrivia(ifStatement.GetLeadingTrivia()) + .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia()) + .WithFormatterAnnotation(); - SyntaxList newStatements = statements - .RemoveAt(index) - .ReplaceAt(index, newStatement); + SyntaxList newStatements = statements + .RemoveAt(index) + .ReplaceAt(index, newStatement); - return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); - } + return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); + } - private static Task IfReturnToReturnWithBooleanExpressionAsync( - Document document, - IfReturnToReturnWithBooleanExpressionAnalysis analysis, - CancellationToken cancellationToken = default) - { - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(analysis.IfStatement); + private static Task IfReturnToReturnWithBooleanExpressionAsync( + Document document, + IfReturnToReturnWithBooleanExpressionAnalysis analysis, + CancellationToken cancellationToken = default) + { + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(analysis.IfStatement); - SyntaxList statements = statementsInfo.Statements; + SyntaxList statements = statementsInfo.Statements; - int index = statements.IndexOf(analysis.IfStatement); + int index = statements.IndexOf(analysis.IfStatement); - ExpressionSyntax expression = GetBooleanExpression( - analysis.IfStatement.Condition, - analysis.Expression1, - analysis.Expression2, - document, - analysis.SemanticModel, - cancellationToken); + ExpressionSyntax expression = GetBooleanExpression( + analysis.IfStatement.Condition, + analysis.Expression1, + analysis.Expression2, + document, + analysis.SemanticModel, + cancellationToken); - StatementSyntax newStatement = ReturnStatement(expression) - .WithLeadingTrivia(analysis.IfStatement.GetLeadingTrivia()) - .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia()) - .WithFormatterAnnotation(); + StatementSyntax newStatement = ReturnStatement(expression) + .WithLeadingTrivia(analysis.IfStatement.GetLeadingTrivia()) + .WithTrailingTrivia(statements[index + 1].GetTrailingTrivia()) + .WithFormatterAnnotation(); - SyntaxList newStatements = statements - .RemoveAt(index) - .ReplaceAt(index, newStatement); + SyntaxList newStatements = statements + .RemoveAt(index) + .ReplaceAt(index, newStatement); - return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); - } + return document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken); + } - private static ConditionalExpressionSyntax CreateConditionalExpression(ExpressionSyntax condition, ExpressionSyntax whenTrue, ExpressionSyntax whenFalse) - { - if (condition.Kind() != SyntaxKind.ParenthesizedExpression) + private static ConditionalExpressionSyntax CreateConditionalExpression(ExpressionSyntax condition, ExpressionSyntax whenTrue, ExpressionSyntax whenFalse) { - condition = ParenthesizedExpression(condition.WithoutTrivia()) - .WithTriviaFrom(condition); - } + if (condition.Kind() != SyntaxKind.ParenthesizedExpression) + { + condition = ParenthesizedExpression(condition.WithoutTrivia()) + .WithTriviaFrom(condition); + } - return ConditionalExpression(condition, whenTrue, whenFalse); - } + return ConditionalExpression(condition, whenTrue, whenFalse); + } - private static ExpressionSyntax GetBooleanExpression( - ExpressionSyntax condition, - ExpressionSyntax expression1, - ExpressionSyntax expression2, - Document document, - SemanticModel semanticModel, - CancellationToken cancellationToken = default) - { - switch (expression1.Kind()) + private static ExpressionSyntax GetBooleanExpression( + ExpressionSyntax condition, + ExpressionSyntax expression1, + ExpressionSyntax expression2, + Document document, + SemanticModel semanticModel, + CancellationToken cancellationToken = default) { - case SyntaxKind.TrueLiteralExpression: - { - switch (expression2.Kind()) + switch (expression1.Kind()) + { + case SyntaxKind.TrueLiteralExpression: { - case SyntaxKind.TrueLiteralExpression: - return expression2; - case SyntaxKind.FalseLiteralExpression: - return condition; - default: - return LogicalOrExpression(condition, expression2); + switch (expression2.Kind()) + { + case SyntaxKind.TrueLiteralExpression: + return expression2; + case SyntaxKind.FalseLiteralExpression: + return condition; + default: + return LogicalOrExpression(condition, expression2); + } } - } - case SyntaxKind.FalseLiteralExpression: - { - switch (expression2.Kind()) + case SyntaxKind.FalseLiteralExpression: { - 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); + 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); + } } - } - default: - { - switch (expression2.Kind()) + default: { - case SyntaxKind.TrueLiteralExpression: - return LogicalOrExpression(SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(condition, semanticModel, cancellationToken), expression1); - case SyntaxKind.FalseLiteralExpression: - return LogicalAndExpression(condition, expression1); - default: - throw new InvalidOperationException(); + 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(); + } } - } - } + } - static BinaryExpressionSyntax LogicalAndExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return CSharpFactory.LogicalAndExpression( - left.Parenthesize(), - right.Parenthesize()); - } + static BinaryExpressionSyntax LogicalAndExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return CSharpFactory.LogicalAndExpression( + left.Parenthesize(), + right.Parenthesize()); + } - static BinaryExpressionSyntax LogicalOrExpression(ExpressionSyntax left, ExpressionSyntax right) - { - return CSharpFactory.LogicalOrExpression( - left.Parenthesize(), - right.Parenthesize()); + static BinaryExpressionSyntax LogicalOrExpression(ExpressionSyntax left, ExpressionSyntax right) + { + return CSharpFactory.LogicalOrExpression( + left.Parenthesize(), + right.Parenthesize()); + } } - } - private static BinaryExpressionSyntax CreateCoalesceExpression( - ExpressionSyntax left, - ExpressionSyntax right, - ITypeSymbol targetType, - int position, - SemanticModel semanticModel) - { - if (targetType?.SupportsExplicitDeclaration() == true) + private static BinaryExpressionSyntax CreateCoalesceExpression( + ExpressionSyntax left, + ExpressionSyntax right, + ITypeSymbol targetType, + int position, + SemanticModel semanticModel) { - right = CastExpression( - targetType.ToMinimalTypeSyntax(semanticModel, position), - right.Parenthesize()) - .WithSimplifierAnnotation(); - } + if (targetType?.SupportsExplicitDeclaration() == true) + { + right = CastExpression( + targetType.ToMinimalTypeSyntax(semanticModel, position), + right.Parenthesize()) + .WithSimplifierAnnotation(); + } - return CoalesceExpression(left.Parenthesize(), right.Parenthesize()); + return CoalesceExpression(left.Parenthesize(), right.Parenthesize()); + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/IntroduceFieldToLockOnRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/IntroduceFieldToLockOnRefactoring.cs index 8638f3e6ce..0aced6f242 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/IntroduceFieldToLockOnRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/IntroduceFieldToLockOnRefactoring.cs @@ -9,68 +9,69 @@ using static Roslynator.CSharp.CSharpFactory; using static Roslynator.CSharp.CSharpTypeFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class IntroduceFieldToLockOnRefactoring +namespace Roslynator.CSharp.Refactorings { - private const string LockObjectName = "_lockObject"; - - public static async Task RefactorAsync( - Document document, - LockStatementSyntax lockStatement, - CancellationToken cancellationToken = default) + internal static class IntroduceFieldToLockOnRefactoring { - MemberDeclarationSyntax containingMember = lockStatement.FirstAncestor(); + private const string LockObjectName = "_lockObject"; - Debug.Assert(containingMember != null); + public static async Task RefactorAsync( + Document document, + LockStatementSyntax lockStatement, + CancellationToken cancellationToken = default) + { + MemberDeclarationSyntax containingMember = lockStatement.FirstAncestor(); - if (containingMember == null) - return document; + Debug.Assert(containingMember is not null); - TypeDeclarationSyntax containingType = containingMember.FirstAncestor(); + if (containingMember is null) + return document; - Debug.Assert(containingType != null); + TypeDeclarationSyntax containingType = containingMember.FirstAncestor(); - if (containingType == null) - return document; + Debug.Assert(containingType is not null); - SyntaxList members = containingType.Members; + if (containingType is null) + return document; - int index = members.IndexOf(containingMember); + SyntaxList members = containingType.Members; - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + int index = members.IndexOf(containingMember); - string name = NameGenerator.Default.EnsureUniqueLocalName( - LockObjectName, - semanticModel, - lockStatement.Expression.SpanStart, - cancellationToken: cancellationToken); + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - LockStatementSyntax newLockStatement = lockStatement - .WithExpression(IdentifierName(Identifier(name).WithRenameAnnotation())); + string name = NameGenerator.Default.EnsureUniqueLocalName( + LockObjectName, + semanticModel, + lockStatement.Expression.SpanStart, + cancellationToken: cancellationToken); - MemberDeclarationSyntax newContainingMember = containingMember - .ReplaceNode(lockStatement, newLockStatement); + LockStatementSyntax newLockStatement = lockStatement + .WithExpression(IdentifierName(Identifier(name).WithRenameAnnotation())); - bool isStatic = SyntaxInfo.ModifierListInfo(containingMember).IsStatic; + MemberDeclarationSyntax newContainingMember = containingMember + .ReplaceNode(lockStatement, newLockStatement); - FieldDeclarationSyntax field = CreateFieldDeclaration(name, isStatic).WithFormatterAnnotation(); + bool isStatic = SyntaxInfo.ModifierListInfo(containingMember).IsStatic; - SyntaxList newMembers = members.ReplaceAt(index, newContainingMember); + FieldDeclarationSyntax field = CreateFieldDeclaration(name, isStatic).WithFormatterAnnotation(); - newMembers = MemberDeclarationInserter.Default.Insert(newMembers, field); + SyntaxList newMembers = members.ReplaceAt(index, newContainingMember); - MemberDeclarationSyntax newNode = containingType.WithMembers(newMembers); + newMembers = MemberDeclarationInserter.Default.Insert(newMembers, field); - return await document.ReplaceNodeAsync(containingType, newNode, cancellationToken).ConfigureAwait(false); - } + MemberDeclarationSyntax newNode = containingType.WithMembers(newMembers); - private static FieldDeclarationSyntax CreateFieldDeclaration(string name, bool isStatic) - { - return FieldDeclaration( - (isStatic) ? Modifiers.Private_Static_ReadOnly() : Modifiers.Private_ReadOnly(), - ObjectType(), - Identifier(name), - ObjectCreationExpression(ObjectType(), ArgumentList())); + return await document.ReplaceNodeAsync(containingType, newNode, cancellationToken).ConfigureAwait(false); + } + + private static FieldDeclarationSyntax CreateFieldDeclaration(string name, bool isStatic) + { + return FieldDeclaration( + (isStatic) ? Modifiers.Private_Static_ReadOnly() : Modifiers.Private_ReadOnly(), + ObjectType(), + Identifier(name), + ObjectCreationExpression(ObjectType(), ArgumentList())); + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/ReduceIfNesting/ReduceIfNestingRewriter.cs b/src/Workspaces.Common/CSharp/Refactorings/ReduceIfNesting/ReduceIfNestingRewriter.cs index 2cc673ec31..01ec244c67 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ReduceIfNesting/ReduceIfNestingRewriter.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ReduceIfNesting/ReduceIfNestingRewriter.cs @@ -11,120 +11,103 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; -namespace Roslynator.CSharp.Refactorings.ReduceIfNesting; - -internal static partial class ReduceIfNestingRefactoring +namespace Roslynator.CSharp.Refactorings.ReduceIfNesting { - private class ReduceIfStatementRewriter : CSharpSyntaxRewriter + internal static partial class ReduceIfNestingRefactoring { - private readonly StatementSyntax _jumpStatement; - private readonly bool _recursive; - private readonly SyntaxLogicalInverter _logicalInverter; - private readonly SyntaxKind _jumpKind; - private StatementListInfo _statementsInfo; - private readonly SemanticModel _semanticModel; - private readonly CancellationToken _cancellationToken; - - public ReduceIfStatementRewriter( - SyntaxKind jumpKind, - bool recursive, - SyntaxLogicalInverter logicalInverter, - SemanticModel semanticModel, - CancellationToken cancellationToken) - { - _jumpKind = jumpKind; - _recursive = recursive; - _logicalInverter = logicalInverter; - _jumpStatement = CreateJumpStatement(jumpKind); - _semanticModel = semanticModel; - _cancellationToken = cancellationToken; - } - - private static StatementSyntax CreateJumpStatement(SyntaxKind jumpKind) + private class ReduceIfStatementRewriter : CSharpSyntaxRewriter { - switch (jumpKind) + private readonly StatementSyntax _jumpStatement; + private readonly bool _recursive; + private readonly SyntaxLogicalInverter _logicalInverter; + private readonly SyntaxKind _jumpKind; + private StatementListInfo _statementsInfo; + private readonly SemanticModel _semanticModel; + private readonly CancellationToken _cancellationToken; + + public ReduceIfStatementRewriter( + SyntaxKind jumpKind, + bool recursive, + SyntaxLogicalInverter logicalInverter, + SemanticModel semanticModel, + CancellationToken cancellationToken) { - case SyntaxKind.ReturnStatement: - return ReturnStatement(); - case SyntaxKind.NullLiteralExpression: - return ReturnStatement(NullLiteralExpression()); - case SyntaxKind.FalseLiteralExpression: - return ReturnStatement(FalseLiteralExpression()); - case SyntaxKind.TrueLiteralExpression: - return ReturnStatement(TrueLiteralExpression()); - case SyntaxKind.DefaultLiteralExpression: - return ReturnStatement(DefaultLiteralExpression()); - case SyntaxKind.BreakStatement: - return BreakStatement(); - case SyntaxKind.ContinueStatement: - return ContinueStatement(); - case SyntaxKind.ThrowStatement: - return ThrowStatement(); - case SyntaxKind.YieldBreakStatement: - return YieldBreakStatement(); - default: - throw new ArgumentException(jumpKind.ToString(), nameof(jumpKind)); + _jumpKind = jumpKind; + _recursive = recursive; + _logicalInverter = logicalInverter; + _jumpStatement = CreateJumpStatement(jumpKind); + _semanticModel = semanticModel; + _cancellationToken = cancellationToken; } - } - public override SyntaxNode VisitIfStatement(IfStatementSyntax node) - { - if (node.Parent == _statementsInfo.Parent) + private static StatementSyntax CreateJumpStatement(SyntaxKind jumpKind) { - return base.VisitIfStatement(node); + switch (jumpKind) + { + case SyntaxKind.ReturnStatement: + return ReturnStatement(); + case SyntaxKind.NullLiteralExpression: + return ReturnStatement(NullLiteralExpression()); + case SyntaxKind.FalseLiteralExpression: + return ReturnStatement(FalseLiteralExpression()); + case SyntaxKind.TrueLiteralExpression: + return ReturnStatement(TrueLiteralExpression()); + case SyntaxKind.DefaultLiteralExpression: + return ReturnStatement(DefaultLiteralExpression()); + case SyntaxKind.BreakStatement: + return BreakStatement(); + case SyntaxKind.ContinueStatement: + return ContinueStatement(); + case SyntaxKind.ThrowStatement: + return ThrowStatement(); + case SyntaxKind.YieldBreakStatement: + return YieldBreakStatement(); + default: + throw new ArgumentException(jumpKind.ToString(), nameof(jumpKind)); + } } - return node; - } - - public override SyntaxNode VisitSwitchSection(SwitchSectionSyntax node) - { - if (_statementsInfo.Parent == null) + public override SyntaxNode VisitIfStatement(IfStatementSyntax node) { - return Rewrite(new StatementListInfo(node)); - } + if (node.Parent == _statementsInfo.Parent) + { + return base.VisitIfStatement(node); + } - return node; - } + return node; + } - public override SyntaxNode VisitBlock(BlockSyntax node) - { - if (_statementsInfo.Parent == null - && node.IsParentKind(SyntaxKind.SwitchSection)) + public override SyntaxNode VisitSwitchSection(SwitchSectionSyntax node) { - return Rewrite(new StatementListInfo(node)); - } + if (_statementsInfo.Parent is null) + { + return Rewrite(new StatementListInfo(node)); + } - _statementsInfo = new StatementListInfo(node); + return node; + } - IfStatementSyntax ifStatement = FindFixableIfStatement(_statementsInfo.Statements, _jumpKind); + public override SyntaxNode VisitBlock(BlockSyntax node) + { + if (_statementsInfo.Parent is null + && node.IsParentKind(SyntaxKind.SwitchSection)) + { + return Rewrite(new StatementListInfo(node)); + } - if (ReduceIfNestingAnalysis.IsFixable(ifStatement)) - return Rewrite(_statementsInfo, ifStatement); + _statementsInfo = new StatementListInfo(node); - return node; - } + IfStatementSyntax ifStatement = FindFixableIfStatement(_statementsInfo.Statements, _jumpKind); - private static IfStatementSyntax FindFixableIfStatement(SyntaxList statements, SyntaxKind jumpKind) - { - int i = statements.Count - 1; + if (ReduceIfNestingAnalysis.IsFixable(ifStatement)) + return Rewrite(_statementsInfo, ifStatement); - while (i >= 0 - && statements[i].Kind() == SyntaxKind.LocalFunctionStatement) - { - i--; + return node; } - if (i == -1) - return null; - - if (statements[i] is IfStatementSyntax ifStatement) - { - return ifStatement; - } - else if (ReduceIfNestingAnalysis.GetJumpKind(statements[i]) == jumpKind) + private static IfStatementSyntax FindFixableIfStatement(SyntaxList statements, SyntaxKind jumpKind) { - i--; + int i = statements.Count - 1; while (i >= 0 && statements[i].Kind() == SyntaxKind.LocalFunctionStatement) @@ -135,63 +118,81 @@ private static IfStatementSyntax FindFixableIfStatement(SyntaxList= 0 + && statements[i].Kind() == SyntaxKind.LocalFunctionStatement) + { + i--; + } - private SyntaxNode Rewrite(in StatementListInfo statementsInfo) - { - _statementsInfo = statementsInfo; + if (i == -1) + return null; - var ifStatement = (IfStatementSyntax)_statementsInfo.Statements.LastButOne(); + if (statements[i] is IfStatementSyntax ifStatement2) + { + return ifStatement2; + } + } - return Rewrite(_statementsInfo, ifStatement); - } + return null; + } - private SyntaxNode Rewrite(in StatementListInfo statementsInfo, IfStatementSyntax ifStatement) - { - SyntaxList statements = statementsInfo.Statements; + private SyntaxNode Rewrite(in StatementListInfo statementsInfo) + { + _statementsInfo = statementsInfo; - int index = statements.IndexOf(ifStatement); + var ifStatement = (IfStatementSyntax)_statementsInfo.Statements.LastButOne(); - ExpressionSyntax newCondition = _logicalInverter.LogicallyInvert(ifStatement.Condition, _semanticModel, _cancellationToken); + return Rewrite(_statementsInfo, ifStatement); + } - if (_recursive) - ifStatement = (IfStatementSyntax)VisitIfStatement(ifStatement); + private SyntaxNode Rewrite(in StatementListInfo statementsInfo, IfStatementSyntax ifStatement) + { + SyntaxList statements = statementsInfo.Statements; - var block = (BlockSyntax)ifStatement.Statement; + int index = statements.IndexOf(ifStatement); - BlockSyntax newBlock = block.WithStatements(SingletonList(_jumpStatement)); + ExpressionSyntax newCondition = _logicalInverter.LogicallyInvert(ifStatement.Condition, _semanticModel, _cancellationToken); - if (!block - .Statements[0] - .GetLeadingTrivia() - .Any(f => f.IsEndOfLineTrivia())) - { - newBlock = newBlock.WithCloseBraceToken(newBlock.CloseBraceToken.AppendToTrailingTrivia(NewLine())); - } + if (_recursive) + ifStatement = (IfStatementSyntax)VisitIfStatement(ifStatement); - IfStatementSyntax newIfStatement = ifStatement - .WithCondition(newCondition) - .WithStatement(newBlock) - .WithFormatterAnnotation(); + var block = (BlockSyntax)ifStatement.Statement; - if (CSharpFacts.IsJumpStatementOrYieldBreakStatement(statements.Last().Kind()) - && CSharpFacts.IsJumpStatementOrYieldBreakStatement(block.Statements.Last().Kind())) - { - statements = statements.RemoveAt(statements.Count - 1); - } + BlockSyntax newBlock = block.WithStatements(SingletonList(_jumpStatement)); + + if (!block + .Statements[0] + .GetLeadingTrivia() + .Any(f => f.IsEndOfLineTrivia())) + { + newBlock = newBlock.WithCloseBraceToken(newBlock.CloseBraceToken.AppendToTrailingTrivia(NewLine())); + } - SyntaxList newStatements = statements - .ReplaceAt(index, newIfStatement) - .InsertRange(index + 1, block.Statements.Select(f => f.WithFormatterAnnotation())); + IfStatementSyntax newIfStatement = ifStatement + .WithCondition(newCondition) + .WithStatement(newBlock) + .WithFormatterAnnotation(); - return statementsInfo.WithStatements(newStatements).Parent; + if (CSharpFacts.IsJumpStatementOrYieldBreakStatement(statements.Last().Kind()) + && CSharpFacts.IsJumpStatementOrYieldBreakStatement(block.Statements.Last().Kind())) + { + statements = statements.RemoveAt(statements.Count - 1); + } + + SyntaxList newStatements = statements + .ReplaceAt(index, newIfStatement) + .InsertRange(index + 1, block.Statements.Select(f => f.WithFormatterAnnotation())); + + return statementsInfo.WithStatements(newStatements).Parent; + } } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/RemoveAsyncAwait.cs b/src/Workspaces.Common/CSharp/Refactorings/RemoveAsyncAwait.cs index e13cb4a13b..d8d517dfd1 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/RemoveAsyncAwait.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/RemoveAsyncAwait.cs @@ -8,150 +8,151 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -namespace Roslynator.CSharp.Refactorings; - -internal static class RemoveAsyncAwait +namespace Roslynator.CSharp.Refactorings { - public static async Task RefactorAsync( - Document document, - SyntaxToken asyncKeyword, - CancellationToken cancellationToken = default) + internal static class RemoveAsyncAwait { - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + public static async Task RefactorAsync( + Document document, + SyntaxToken asyncKeyword, + CancellationToken cancellationToken = default) + { + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - SyntaxNode node = asyncKeyword.Parent; + SyntaxNode node = asyncKeyword.Parent; - var remover = new AwaitRemover(semanticModel, cancellationToken); + var remover = new AwaitRemover(semanticModel, cancellationToken); - SyntaxNode newNode = GetNewNode(); + SyntaxNode newNode = GetNewNode(); - return await document.ReplaceNodeAsync(node, newNode, cancellationToken).ConfigureAwait(false); + return await document.ReplaceNodeAsync(node, newNode, cancellationToken).ConfigureAwait(false); - SyntaxNode GetNewNode() - { - switch (node) + SyntaxNode GetNewNode() { - case MethodDeclarationSyntax methodDeclaration: - { - return remover - .VisitMethodDeclaration(methodDeclaration) - .RemoveModifier(SyntaxKind.AsyncKeyword); - } - case LocalFunctionStatementSyntax localFunction: - { - BlockSyntax body = localFunction.Body; - - if (body != null) + switch (node) + { + case MethodDeclarationSyntax methodDeclaration: { - localFunction = localFunction.WithBody((BlockSyntax)remover.VisitBlock(body)); + return remover + .VisitMethodDeclaration(methodDeclaration) + .RemoveModifier(SyntaxKind.AsyncKeyword); } - else + case LocalFunctionStatementSyntax localFunction: { - ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; + BlockSyntax body = localFunction.Body; - if (expressionBody != null) - localFunction = localFunction.WithExpressionBody((ArrowExpressionClauseSyntax)remover.VisitArrowExpressionClause(expressionBody)); - } + if (body is not null) + { + localFunction = localFunction.WithBody((BlockSyntax)remover.VisitBlock(body)); + } + else + { + ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; - return localFunction.RemoveModifier(SyntaxKind.AsyncKeyword); - } - case SimpleLambdaExpressionSyntax lambda: - { - 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)); - } - case AnonymousMethodExpressionSyntax anonymousMethod: - { - return anonymousMethod - .WithBody((CSharpSyntaxNode)remover.Visit(anonymousMethod.Body)) - .WithAsyncKeyword(GetMissingAsyncKeyword(anonymousMethod.AsyncKeyword)); - } - default: - { - throw new InvalidOperationException(); - } + 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)); + } + case ParenthesizedLambdaExpressionSyntax lambda: + { + 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)); + } + default: + { + throw new InvalidOperationException(); + } + } } } - } - private static SyntaxToken GetMissingAsyncKeyword(SyntaxToken asyncKeyword) - { - if (asyncKeyword.TrailingTrivia.All(f => f.IsWhitespaceTrivia())) + private static SyntaxToken GetMissingAsyncKeyword(SyntaxToken asyncKeyword) { - return MissingToken(SyntaxKind.AsyncKeyword).WithLeadingTrivia(asyncKeyword.LeadingTrivia); - } - else - { - return MissingToken(SyntaxKind.AsyncKeyword).WithTriviaFrom(asyncKeyword); + if (asyncKeyword.TrailingTrivia.All(f => f.IsWhitespaceTrivia())) + { + return MissingToken(SyntaxKind.AsyncKeyword).WithLeadingTrivia(asyncKeyword.LeadingTrivia); + } + else + { + return MissingToken(SyntaxKind.AsyncKeyword).WithTriviaFrom(asyncKeyword); + } } - } - private class AwaitRemover : CSharpSyntaxRewriter - { - public AwaitRemover(SemanticModel semanticModel, CancellationToken cancellationToken) + private class AwaitRemover : CSharpSyntaxRewriter { - SemanticModel = semanticModel; - CancellationToken = cancellationToken; - } - - public SemanticModel SemanticModel { get; } + public AwaitRemover(SemanticModel semanticModel, CancellationToken cancellationToken) + { + SemanticModel = semanticModel; + CancellationToken = cancellationToken; + } - public CancellationToken CancellationToken { get; } + public SemanticModel SemanticModel { get; } - private static ExpressionSyntax ExtractExpressionFromAwait(AwaitExpressionSyntax awaitExpression, SemanticModel semanticModel, CancellationToken cancellationToken) - { - ExpressionSyntax expression = awaitExpression.Expression; + public CancellationToken CancellationToken { get; } - if (semanticModel.GetTypeSymbol(expression, cancellationToken) is INamedTypeSymbol typeSymbol) + private static ExpressionSyntax ExtractExpressionFromAwait(AwaitExpressionSyntax awaitExpression, SemanticModel semanticModel, CancellationToken cancellationToken) { - if (typeSymbol.HasMetadataName(MetadataNames.System_Runtime_CompilerServices_ConfiguredTaskAwaitable) - || typeSymbol.OriginalDefinition.HasMetadataName(MetadataNames.System_Runtime_CompilerServices_ConfiguredTaskAwaitable_T)) + ExpressionSyntax expression = awaitExpression.Expression; + + if (semanticModel.GetTypeSymbol(expression, cancellationToken) is INamedTypeSymbol typeSymbol) { - if (expression is InvocationExpressionSyntax invocation) + if (typeSymbol.HasMetadataName(MetadataNames.System_Runtime_CompilerServices_ConfiguredTaskAwaitable) + || typeSymbol.OriginalDefinition.HasMetadataName(MetadataNames.System_Runtime_CompilerServices_ConfiguredTaskAwaitable_T)) { - var memberAccess = invocation.Expression as MemberAccessExpressionSyntax; + if (expression is InvocationExpressionSyntax invocation) + { + var memberAccess = invocation.Expression as MemberAccessExpressionSyntax; - if (string.Equals(memberAccess?.Name?.Identifier.ValueText, "ConfigureAwait", StringComparison.Ordinal)) - expression = memberAccess.Expression; + if (string.Equals(memberAccess?.Name?.Identifier.ValueText, "ConfigureAwait", StringComparison.Ordinal)) + expression = memberAccess.Expression; + } } } - } - return expression.WithTriviaFrom(awaitExpression); - } + return expression.WithTriviaFrom(awaitExpression); + } - public override SyntaxNode VisitAwaitExpression(AwaitExpressionSyntax node) - { - node = (AwaitExpressionSyntax)base.VisitAwaitExpression(node); + public override SyntaxNode VisitAwaitExpression(AwaitExpressionSyntax node) + { + node = (AwaitExpressionSyntax)base.VisitAwaitExpression(node); - return ExtractExpressionFromAwait(node, SemanticModel, CancellationToken); - } + return ExtractExpressionFromAwait(node, SemanticModel, CancellationToken); + } - public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) - { - return node; - } + public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) + { + return node; + } - public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) - { - return node; - } + public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) + { + return node; + } - public override SyntaxNode VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) - { - return node; - } + public override SyntaxNode VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) + { + return node; + } - public override SyntaxNode VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) - { - return node; + public override SyntaxNode VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + return node; + } } } } diff --git a/src/Workspaces.Common/CodeFixes/AbstractCodeFixProvider.cs b/src/Workspaces.Common/CodeFixes/AbstractCodeFixProvider.cs index 1197152099..d357165dd6 100644 --- a/src/Workspaces.Common/CodeFixes/AbstractCodeFixProvider.cs +++ b/src/Workspaces.Common/CodeFixes/AbstractCodeFixProvider.cs @@ -7,132 +7,133 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; -namespace Roslynator.CodeFixes; - -[DebuggerDisplay("{DebuggerDisplay,nq}")] -public abstract class AbstractCodeFixProvider : CodeFixProvider +namespace Roslynator.CodeFixes { - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay + [DebuggerDisplay("{DebuggerDisplay,nq}")] + public abstract class AbstractCodeFixProvider : CodeFixProvider { - get { return $"{GetType()} {{{string.Join(", ", FixableDiagnosticIds)}}}"; } - } - - public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay + { + get { return $"{GetType()} {{{string.Join(", ", FixableDiagnosticIds)}}}"; } + } - protected string GetEquivalenceKey(Diagnostic diagnostic, string additionalKey1 = null, string additionalKey2 = null) - { - return EquivalenceKey.Create(diagnostic, additionalKey1, additionalKey2); - } + public override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } - protected string GetEquivalenceKey(string key, string additionalKey1 = null, string additionalKey2 = null) - { - return EquivalenceKey.Create(key, additionalKey1, additionalKey2); - } + protected string GetEquivalenceKey(Diagnostic diagnostic, string additionalKey1 = null, string additionalKey2 = null) + { + return EquivalenceKey.Create(diagnostic, additionalKey1, additionalKey2); + } - protected static bool TryFindFirstAncestorOrSelf( - SyntaxNode root, - TextSpan span, - out TNode node, - bool findInsideTrivia = false, - bool getInnermostNodeForTie = true, - Func predicate = null, - bool ascendOutOfTrivia = true) where TNode : SyntaxNode - { - node = root - .FindNode(span, findInsideTrivia: findInsideTrivia, getInnermostNodeForTie: getInnermostNodeForTie)? - .FirstAncestorOrSelf(predicate, ascendOutOfTrivia: ascendOutOfTrivia); + protected string GetEquivalenceKey(string key, string additionalKey1 = null, string additionalKey2 = null) + { + return EquivalenceKey.Create(key, additionalKey1, additionalKey2); + } - Assert.NotNull(node); + protected static bool TryFindFirstAncestorOrSelf( + SyntaxNode root, + TextSpan span, + out TNode node, + bool findInsideTrivia = false, + bool getInnermostNodeForTie = true, + Func predicate = null, + bool ascendOutOfTrivia = true) where TNode : SyntaxNode + { + node = root + .FindNode(span, findInsideTrivia: findInsideTrivia, getInnermostNodeForTie: getInnermostNodeForTie)? + .FirstAncestorOrSelf(predicate, ascendOutOfTrivia: ascendOutOfTrivia); - return node != null; - } + Assert.NotNull(node); - protected static bool TryFindFirstDescendantOrSelf( - SyntaxNode root, - TextSpan span, - out TNode node, - bool findInsideTrivia = false, - bool getInnermostNodeForTie = true, - Func descendIntoChildren = null, - bool descendIntoTrivia = true) where TNode : SyntaxNode - { - node = root - .FindNode(span, findInsideTrivia: findInsideTrivia, getInnermostNodeForTie: getInnermostNodeForTie)? - .FirstDescendantOrSelf(span, descendIntoChildren: descendIntoChildren, descendIntoTrivia: descendIntoTrivia); + return node is not null; + } - Assert.NotNull(node); + protected static bool TryFindFirstDescendantOrSelf( + SyntaxNode root, + TextSpan span, + out TNode node, + bool findInsideTrivia = false, + bool getInnermostNodeForTie = true, + Func descendIntoChildren = null, + bool descendIntoTrivia = true) where TNode : SyntaxNode + { + node = root + .FindNode(span, findInsideTrivia: findInsideTrivia, getInnermostNodeForTie: getInnermostNodeForTie)? + .FirstDescendantOrSelf(span, descendIntoChildren: descendIntoChildren, descendIntoTrivia: descendIntoTrivia); - return node != null; - } + Assert.NotNull(node); - protected static bool TryFindNode( - SyntaxNode root, - TextSpan span, - out TNode node, - bool findInsideTrivia = false, - bool getInnermostNodeForTie = true, - Func predicate = null) where TNode : SyntaxNode - { - node = root.FindNode(span, findInsideTrivia: findInsideTrivia, getInnermostNodeForTie: getInnermostNodeForTie) as TNode; + return node is not null; + } - if (node != null - && predicate != null - && !predicate(node)) + protected static bool TryFindNode( + SyntaxNode root, + TextSpan span, + out TNode node, + bool findInsideTrivia = false, + bool getInnermostNodeForTie = true, + Func predicate = null) where TNode : SyntaxNode { - node = null; - } + node = root.FindNode(span, findInsideTrivia: findInsideTrivia, getInnermostNodeForTie: getInnermostNodeForTie) as TNode; - Assert.NotNull(node); + if (node is not null + && predicate is not null + && !predicate(node)) + { + node = null; + } - return node != null; - } + Assert.NotNull(node); - protected static bool TryFindToken( - SyntaxNode root, - int position, - out SyntaxToken token, - bool findInsideTrivia = true) - { - token = root.FindToken(position, findInsideTrivia: findInsideTrivia); + return node is not null; + } - bool success = token != default; + protected static bool TryFindToken( + SyntaxNode root, + int position, + out SyntaxToken token, + bool findInsideTrivia = true) + { + token = root.FindToken(position, findInsideTrivia: findInsideTrivia); - Assert.True(success, nameof(token)); + bool success = token != default; - return success; - } + Assert.True(success, nameof(token)); - protected static bool TryFindTrivia( - SyntaxNode root, - int position, - out SyntaxTrivia trivia, - bool findInsideTrivia = true) - { - trivia = root.FindTrivia(position, findInsideTrivia: findInsideTrivia); + return success; + } - bool success = trivia != default; + protected static bool TryFindTrivia( + SyntaxNode root, + int position, + out SyntaxTrivia trivia, + bool findInsideTrivia = true) + { + trivia = root.FindTrivia(position, findInsideTrivia: findInsideTrivia); - Assert.True(success, nameof(trivia)); + bool success = trivia != default; - return success; - } + Assert.True(success, nameof(trivia)); - private static class Assert - { - [Conditional("DEBUG")] - public static void True(bool condition, string name, SyntaxKind kind = SyntaxKind.None) - { - Debug.Assert(condition, (kind == SyntaxKind.None) ? $"{name} is {kind}" : $"{name} is not {kind}"); + return success; } - [Conditional("DEBUG")] - public static void NotNull(T value) where T : class + private static class Assert { - Debug.Assert(value != null, $"{nameof(value)} is null"); + [Conditional("DEBUG")] + public static void True(bool condition, string name, SyntaxKind kind = SyntaxKind.None) + { + Debug.Assert(condition, (kind == SyntaxKind.None) ? $"{name} is {kind}" : $"{name} is not {kind}"); + } + + [Conditional("DEBUG")] + public static void NotNull(T value) where T : class + { + Debug.Assert(value is not null, $"{nameof(value)} is null"); + } } } } diff --git a/src/Workspaces.Core/AnalyzerAssembly.cs b/src/Workspaces.Core/AnalyzerAssembly.cs index 962ac24722..668813ca8b 100644 --- a/src/Workspaces.Core/AnalyzerAssembly.cs +++ b/src/Workspaces.Core/AnalyzerAssembly.cs @@ -10,183 +10,184 @@ using Microsoft.CodeAnalysis.Diagnostics; using static Roslynator.Logger; -namespace Roslynator; - -[DebuggerDisplay("{DebuggerDisplay,nq}")] -internal sealed class AnalyzerAssembly : IEquatable +namespace Roslynator { - private AnalyzerAssembly( - Assembly assembly, - ImmutableDictionary> analyzersByLanguage, - ImmutableDictionary> fixersByLanguage) + [DebuggerDisplay("{DebuggerDisplay,nq}")] + internal sealed class AnalyzerAssembly : IEquatable { - Assembly = assembly; - - AnalyzersByLanguage = analyzersByLanguage; - FixersByLanguage = fixersByLanguage; - } - - public Assembly Assembly { get; } - - internal string FullName => Assembly.FullName; + private AnalyzerAssembly( + Assembly assembly, + ImmutableDictionary> analyzersByLanguage, + ImmutableDictionary> fixersByLanguage) + { + Assembly = assembly; - internal string Name => Assembly.GetName().Name; + AnalyzersByLanguage = analyzersByLanguage; + FixersByLanguage = fixersByLanguage; + } - public bool HasAnalyzers => AnalyzersByLanguage.Count > 0; + public Assembly Assembly { get; } - public bool HasFixers => FixersByLanguage.Count > 0; + internal string FullName => Assembly.FullName; - internal bool IsEmpty => !HasAnalyzers && !HasFixers; + internal string Name => Assembly.GetName().Name; - public ImmutableDictionary> AnalyzersByLanguage { get; } + public bool HasAnalyzers => AnalyzersByLanguage.Count > 0; - public ImmutableDictionary> FixersByLanguage { get; } + public bool HasFixers => FixersByLanguage.Count > 0; - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay => FullName; + internal bool IsEmpty => !HasAnalyzers && !HasFixers; - internal IEnumerable GetAnalyzers() - { - return AnalyzersByLanguage - .SelectMany(f => f.Value) - .Distinct(); - } + public ImmutableDictionary> AnalyzersByLanguage { get; } - internal IEnumerable GetFixers() - { - return FixersByLanguage - .SelectMany(f => f.Value) - .Distinct(); - } + public ImmutableDictionary> FixersByLanguage { get; } - public static AnalyzerAssembly Load( - Assembly analyzerAssembly, - bool loadAnalyzers = true, - bool loadFixers = true, - string language = null) - { - Debug.Assert(loadAnalyzers || loadFixers); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay => FullName; - Dictionary.Builder> analyzers = null; - Dictionary.Builder> fixers = null; + internal IEnumerable GetAnalyzers() + { + return AnalyzersByLanguage + .SelectMany(f => f.Value) + .Distinct(); + } - TypeInfo[] types = null; - try + internal IEnumerable GetFixers() { - types = analyzerAssembly.DefinedTypes.ToArray(); + return FixersByLanguage + .SelectMany(f => f.Value) + .Distinct(); } - catch (ReflectionTypeLoadException ex) + + public static AnalyzerAssembly Load( + Assembly analyzerAssembly, + bool loadAnalyzers = true, + bool loadFixers = true, + string language = null) { - types = ex.Types.OfType().ToArray(); + Debug.Assert(loadAnalyzers || loadFixers); - int count = ex.Types.Count(f => f == null); - string message = $"Cannot load {count} type{((count == 1) ? "" : "s")} from assembly '{analyzerAssembly.FullName}'"; + Dictionary.Builder> analyzers = null; + Dictionary.Builder> fixers = null; - if (!string.IsNullOrEmpty(analyzerAssembly.Location)) - message += $" at '{analyzerAssembly.Location}'"; + TypeInfo[] types = null; + try + { + types = analyzerAssembly.DefinedTypes.ToArray(); + } + catch (ReflectionTypeLoadException ex) + { + types = ex.Types.OfType().ToArray(); - WriteLine(message, ConsoleColors.DarkGray, Verbosity.Diagnostic); + int count = ex.Types.Count(f => f is null); + string message = $"Cannot load {count} type{((count == 1) ? "" : "s")} from assembly '{analyzerAssembly.FullName}'"; - foreach (Exception loadeException in ex.LoaderExceptions) - WriteLine($" {loadeException.Message}", ConsoleColors.DarkGray, Verbosity.Diagnostic); - } + if (!string.IsNullOrEmpty(analyzerAssembly.Location)) + message += $" at '{analyzerAssembly.Location}'"; - foreach (TypeInfo typeInfo in types) - { - if (loadAnalyzers - && !typeInfo.IsAbstract - && typeInfo.IsSubclassOf(typeof(DiagnosticAnalyzer))) - { - DiagnosticAnalyzerAttribute attribute = typeInfo.GetCustomAttribute(); + WriteLine(message, ConsoleColors.DarkGray, Verbosity.Diagnostic); - if (attribute != null) + foreach (Exception loadeException in ex.LoaderExceptions) + WriteLine($" {loadeException.Message}", ConsoleColors.DarkGray, Verbosity.Diagnostic); + } + + foreach (TypeInfo typeInfo in types) + { + if (loadAnalyzers + && !typeInfo.IsAbstract + && typeInfo.IsSubclassOf(typeof(DiagnosticAnalyzer))) { - DiagnosticAnalyzer analyzer = CreateInstanceAndCatchIfThrows(typeInfo); + DiagnosticAnalyzerAttribute attribute = typeInfo.GetCustomAttribute(); - if (analyzer != null) + if (attribute is not null) { - if (analyzers == null) - analyzers = new Dictionary.Builder>(); + DiagnosticAnalyzer analyzer = CreateInstanceAndCatchIfThrows(typeInfo); - foreach (string language2 in attribute.Languages) + if (analyzer is not null) { - if (language == null - || language == language2) - { - if (!analyzers.TryGetValue(language2, out ImmutableArray.Builder value)) - analyzers[language2] = ImmutableArray.CreateBuilder(); + if (analyzers is null) + analyzers = new Dictionary.Builder>(); - analyzers[language2].Add(analyzer); + foreach (string language2 in attribute.Languages) + { + if (language is null + || language == language2) + { + if (!analyzers.TryGetValue(language2, out ImmutableArray.Builder value)) + analyzers[language2] = ImmutableArray.CreateBuilder(); + + analyzers[language2].Add(analyzer); + } } } } } - } - else if (loadFixers - && !typeInfo.IsAbstract - && typeInfo.IsSubclassOf(typeof(CodeFixProvider))) - { - ExportCodeFixProviderAttribute attribute = typeInfo.GetCustomAttribute(); - - if (attribute != null) + else if (loadFixers + && !typeInfo.IsAbstract + && typeInfo.IsSubclassOf(typeof(CodeFixProvider))) { - CodeFixProvider fixer = CreateInstanceAndCatchIfThrows(typeInfo); + ExportCodeFixProviderAttribute attribute = typeInfo.GetCustomAttribute(); - if (fixer != null) + if (attribute is not null) { - if (fixers == null) - fixers = new Dictionary.Builder>(); + CodeFixProvider fixer = CreateInstanceAndCatchIfThrows(typeInfo); - foreach (string language2 in attribute.Languages) + if (fixer is not null) { - if (language == null - || language == language2) - { - if (!fixers.TryGetValue(language2, out ImmutableArray.Builder value)) - fixers[language2] = ImmutableArray.CreateBuilder(); + if (fixers is null) + fixers = new Dictionary.Builder>(); - fixers[language2].Add(fixer); + foreach (string language2 in attribute.Languages) + { + if (language is null + || language == language2) + { + if (!fixers.TryGetValue(language2, out ImmutableArray.Builder value)) + fixers[language2] = ImmutableArray.CreateBuilder(); + + fixers[language2].Add(fixer); + } } } } } } - } - return new AnalyzerAssembly( - analyzerAssembly, - analyzers?.ToImmutableDictionary(f => f.Key, f => f.Value.ToImmutableArray()) ?? ImmutableDictionary>.Empty, - fixers?.ToImmutableDictionary(f => f.Key, f => f.Value.ToImmutableArray()) ?? ImmutableDictionary>.Empty); - } + return new AnalyzerAssembly( + analyzerAssembly, + analyzers?.ToImmutableDictionary(f => f.Key, f => f.Value.ToImmutableArray()) ?? ImmutableDictionary>.Empty, + fixers?.ToImmutableDictionary(f => f.Key, f => f.Value.ToImmutableArray()) ?? ImmutableDictionary>.Empty); + } - private static T CreateInstanceAndCatchIfThrows(TypeInfo typeInfo) - { - try + private static T CreateInstanceAndCatchIfThrows(TypeInfo typeInfo) { - return (T)Activator.CreateInstance(typeInfo.AsType()); + try + { + return (T)Activator.CreateInstance(typeInfo.AsType()); + } + catch (TargetInvocationException ex) + { + WriteLine($"Cannot create instance of type '{typeInfo.FullName}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); + WriteLine(ex.ToString(), ConsoleColors.DarkGray, Verbosity.Diagnostic); + } + + return default; } - catch (TargetInvocationException ex) + + public override int GetHashCode() { - WriteLine($"Cannot create instance of type '{typeInfo.FullName}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); - WriteLine(ex.ToString(), ConsoleColors.DarkGray, Verbosity.Diagnostic); + return StringComparer.Ordinal.GetHashCode(FullName); } - return default; - } - - public override int GetHashCode() - { - return StringComparer.Ordinal.GetHashCode(FullName); - } - - public override bool Equals(object obj) - { - return Equals(obj as AnalyzerAssembly); - } + public override bool Equals(object obj) + { + return Equals(obj as AnalyzerAssembly); + } - public bool Equals(AnalyzerAssembly other) - { - return other != null - && StringComparer.Ordinal.Equals(FullName, other.FullName); + public bool Equals(AnalyzerAssembly other) + { + return other is not null + && StringComparer.Ordinal.Equals(FullName, other.FullName); + } } } diff --git a/src/Workspaces.Core/AnalyzerLoader.cs b/src/Workspaces.Core/AnalyzerLoader.cs index 3a88cf71c6..3b9d99694f 100644 --- a/src/Workspaces.Core/AnalyzerLoader.cs +++ b/src/Workspaces.Core/AnalyzerLoader.cs @@ -9,198 +9,199 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; -namespace Roslynator; - -internal class AnalyzerLoader +namespace Roslynator { - private readonly Dictionary _cache = new(); - private readonly Dictionary _defaultAssemblies = new(); - private readonly Dictionary> _defaultAnalyzers = new(); - private readonly Dictionary> _defaultFixers = new(); - - public AnalyzerLoader(IEnumerable defaultAssemblies, CodeAnalysisOptions options) + internal class AnalyzerLoader { - DefaultAssemblies = ImmutableArray.Empty; + private readonly Dictionary _cache = new(); + private readonly Dictionary _defaultAssemblies = new(); + private readonly Dictionary> _defaultAnalyzers = new(); + private readonly Dictionary> _defaultFixers = new(); - if (defaultAssemblies != null) + public AnalyzerLoader(IEnumerable defaultAssemblies, CodeAnalysisOptions options) { - foreach (AnalyzerAssembly analyzerAssembly in defaultAssemblies) + DefaultAssemblies = ImmutableArray.Empty; + + if (defaultAssemblies is not null) { - if (!_defaultAssemblies.ContainsKey(analyzerAssembly.FullName)) + foreach (AnalyzerAssembly analyzerAssembly in defaultAssemblies) { - _defaultAssemblies.Add(analyzerAssembly.FullName, analyzerAssembly); - OnAnalyzerAssemblyAdded(new AnalyzerAssemblyEventArgs(analyzerAssembly)); + if (!_defaultAssemblies.ContainsKey(analyzerAssembly.FullName)) + { + _defaultAssemblies.Add(analyzerAssembly.FullName, analyzerAssembly); + OnAnalyzerAssemblyAdded(new AnalyzerAssemblyEventArgs(analyzerAssembly)); + } } + + DefaultAssemblies = _defaultAssemblies.Select(f => f.Value).ToImmutableArray(); } - DefaultAssemblies = _defaultAssemblies.Select(f => f.Value).ToImmutableArray(); + Options = options; } - Options = options; - } - - public ImmutableArray DefaultAssemblies { get; } + public ImmutableArray DefaultAssemblies { get; } - public CodeAnalysisOptions Options { get; } + public CodeAnalysisOptions Options { get; } - public event EventHandler AnalyzerAssemblyAdded; + public event EventHandler AnalyzerAssemblyAdded; - protected virtual void OnAnalyzerAssemblyAdded(AnalyzerAssemblyEventArgs e) - { - AnalyzerAssemblyAdded?.Invoke(this, e); - } - - public ImmutableArray GetAnalyzers(Project project) - { - (ImmutableArray analyzers, ImmutableArray _) = GetAnalyzersAndFixers(project: project, loadFixers: false); - - return analyzers; - } - - public (ImmutableArray analyzers, ImmutableArray fixers) GetAnalyzersAndFixers(Project project) - { - return GetAnalyzersAndFixers(project: project, loadFixers: true); - } + protected virtual void OnAnalyzerAssemblyAdded(AnalyzerAssemblyEventArgs e) + { + AnalyzerAssemblyAdded?.Invoke(this, e); + } - private (ImmutableArray analyzers, ImmutableArray fixers) GetAnalyzersAndFixers( - Project project, - bool loadFixers = true) - { - string language = project.Language; + public ImmutableArray GetAnalyzers(Project project) + { + (ImmutableArray analyzers, ImmutableArray _) = GetAnalyzersAndFixers(project: project, loadFixers: false); - ImmutableArray.Builder analyzers = ImmutableArray.CreateBuilder(); - ImmutableArray.Builder fixers = ImmutableArray.CreateBuilder(); + return analyzers; + } - if (_defaultAnalyzers.TryGetValue(language, out ImmutableArray defaultAnalyzers)) + public (ImmutableArray analyzers, ImmutableArray fixers) GetAnalyzersAndFixers(Project project) { - analyzers.AddRange(defaultAnalyzers); + return GetAnalyzersAndFixers(project: project, loadFixers: true); } - else + + private (ImmutableArray analyzers, ImmutableArray fixers) GetAnalyzersAndFixers( + Project project, + bool loadFixers = true) { - foreach (AnalyzerAssembly analyzerAssembly in DefaultAssemblies) - LoadAnalyzers(analyzerAssembly, language, ref analyzers); + string language = project.Language; - _defaultAnalyzers.Add(language, analyzers.ToImmutableArray()); - } + ImmutableArray.Builder analyzers = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder fixers = ImmutableArray.CreateBuilder(); - if (loadFixers) - { - if (_defaultFixers.TryGetValue(language, out ImmutableArray defaultFixers)) + if (_defaultAnalyzers.TryGetValue(language, out ImmutableArray defaultAnalyzers)) { - fixers.AddRange(defaultFixers); + analyzers.AddRange(defaultAnalyzers); } else { foreach (AnalyzerAssembly analyzerAssembly in DefaultAssemblies) - LoadFixers(analyzerAssembly, language, ref fixers); + LoadAnalyzers(analyzerAssembly, language, ref analyzers); - _defaultFixers.Add(language, fixers.ToImmutableArray()); + _defaultAnalyzers.Add(language, analyzers.ToImmutableArray()); } - } - if (!Options.IgnoreAnalyzerReferences) - { - foreach (Assembly assembly in project.AnalyzerReferences - .Distinct() - .OfType() - .Select(f => f.GetAssembly()) - .Where(f => !_defaultAssemblies.ContainsKey(f.FullName))) + if (loadFixers) { - if (!_cache.TryGetValue(assembly.FullName, out AnalyzerAssembly analyzerAssembly)) + if (_defaultFixers.TryGetValue(language, out ImmutableArray defaultFixers)) + { + fixers.AddRange(defaultFixers); + } + else { - analyzerAssembly = AnalyzerAssembly.Load(assembly); - _cache.Add(analyzerAssembly.FullName, analyzerAssembly); + foreach (AnalyzerAssembly analyzerAssembly in DefaultAssemblies) + LoadFixers(analyzerAssembly, language, ref fixers); - OnAnalyzerAssemblyAdded(new AnalyzerAssemblyEventArgs(analyzerAssembly)); + _defaultFixers.Add(language, fixers.ToImmutableArray()); } + } - LoadAnalyzers(analyzerAssembly, language, ref analyzers); + if (!Options.IgnoreAnalyzerReferences) + { + foreach (Assembly assembly in project.AnalyzerReferences + .Distinct() + .OfType() + .Select(f => f.GetAssembly()) + .Where(f => !_defaultAssemblies.ContainsKey(f.FullName))) + { + if (!_cache.TryGetValue(assembly.FullName, out AnalyzerAssembly analyzerAssembly)) + { + analyzerAssembly = AnalyzerAssembly.Load(assembly); + _cache.Add(analyzerAssembly.FullName, analyzerAssembly); + + OnAnalyzerAssemblyAdded(new AnalyzerAssemblyEventArgs(analyzerAssembly)); + } - if (loadFixers) - LoadFixers(analyzerAssembly, language, ref fixers); + LoadAnalyzers(analyzerAssembly, language, ref analyzers); + + if (loadFixers) + LoadFixers(analyzerAssembly, language, ref fixers); + } } - } - return (analyzers.ToImmutableArray(), fixers.ToImmutableArray()); - } + return (analyzers.ToImmutableArray(), fixers.ToImmutableArray()); + } - private void LoadAnalyzers(AnalyzerAssembly analyzerAssembly, string language, ref ImmutableArray.Builder builder) - { - if (analyzerAssembly.AnalyzersByLanguage.TryGetValue(language, out ImmutableArray analyzers)) + private void LoadAnalyzers(AnalyzerAssembly analyzerAssembly, string language, ref ImmutableArray.Builder builder) { - foreach (DiagnosticAnalyzer analyzer in analyzers) + if (analyzerAssembly.AnalyzersByLanguage.TryGetValue(language, out ImmutableArray analyzers)) { - if (ShouldIncludeAnalyzer(analyzer)) - builder.Add(analyzer); + foreach (DiagnosticAnalyzer analyzer in analyzers) + { + if (ShouldIncludeAnalyzer(analyzer)) + builder.Add(analyzer); + } } } - } - private bool ShouldIncludeAnalyzer(DiagnosticAnalyzer analyzer) - { - if (Options.SupportedDiagnosticIds.Count > 0) + private bool ShouldIncludeAnalyzer(DiagnosticAnalyzer analyzer) { - foreach (DiagnosticDescriptor supportedDiagnostic in analyzer.SupportedDiagnostics) + if (Options.SupportedDiagnosticIds.Count > 0) { - if (Options.SupportedDiagnosticIds.Contains(supportedDiagnostic.Id)) - return true; + foreach (DiagnosticDescriptor supportedDiagnostic in analyzer.SupportedDiagnostics) + { + if (Options.SupportedDiagnosticIds.Contains(supportedDiagnostic.Id)) + return true; + } + + return false; } + else if (Options.IgnoredDiagnosticIds.Count > 0) + { + foreach (DiagnosticDescriptor supportedDiagnostic in analyzer.SupportedDiagnostics) + { + if (!Options.IgnoredDiagnosticIds.Contains(supportedDiagnostic.Id)) + return true; + } - return false; - } - else if (Options.IgnoredDiagnosticIds.Count > 0) - { - foreach (DiagnosticDescriptor supportedDiagnostic in analyzer.SupportedDiagnostics) + return false; + } + else { - if (!Options.IgnoredDiagnosticIds.Contains(supportedDiagnostic.Id)) - return true; + return true; } - - return false; - } - else - { - return true; } - } - private void LoadFixers(AnalyzerAssembly analyzerAssembly, string language, ref ImmutableArray.Builder builder) - { - if (analyzerAssembly.FixersByLanguage.TryGetValue(language, out ImmutableArray fixers)) + private void LoadFixers(AnalyzerAssembly analyzerAssembly, string language, ref ImmutableArray.Builder builder) { - foreach (CodeFixProvider fixer in fixers) + if (analyzerAssembly.FixersByLanguage.TryGetValue(language, out ImmutableArray fixers)) { - if (ShouldIncludeFixer(fixer)) - builder.Add(fixer); + foreach (CodeFixProvider fixer in fixers) + { + if (ShouldIncludeFixer(fixer)) + builder.Add(fixer); + } } } - } - private bool ShouldIncludeFixer(CodeFixProvider fixer) - { - if (Options.SupportedDiagnosticIds.Count > 0) + private bool ShouldIncludeFixer(CodeFixProvider fixer) { - foreach (string fixableDiagnosticId in fixer.FixableDiagnosticIds) + if (Options.SupportedDiagnosticIds.Count > 0) { - if (Options.SupportedDiagnosticIds.Contains(fixableDiagnosticId)) - return true; + foreach (string fixableDiagnosticId in fixer.FixableDiagnosticIds) + { + if (Options.SupportedDiagnosticIds.Contains(fixableDiagnosticId)) + return true; + } + + return false; } + else if (Options.IgnoredDiagnosticIds.Count > 0) + { + foreach (string fixableDiagnosticId in fixer.FixableDiagnosticIds) + { + if (!Options.IgnoredDiagnosticIds.Contains(fixableDiagnosticId)) + return true; + } - return false; - } - else if (Options.IgnoredDiagnosticIds.Count > 0) - { - foreach (string fixableDiagnosticId in fixer.FixableDiagnosticIds) + return false; + } + else { - if (!Options.IgnoredDiagnosticIds.Contains(fixableDiagnosticId)) - return true; + return true; } - - return false; - } - else - { - return true; } } } diff --git a/src/Workspaces.Core/CodeActions/CodeActionData.cs b/src/Workspaces.Core/CodeActions/CodeActionData.cs index 8c0ddc0428..3c109f9caa 100644 --- a/src/Workspaces.Core/CodeActions/CodeActionData.cs +++ b/src/Workspaces.Core/CodeActions/CodeActionData.cs @@ -6,29 +6,30 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; -namespace Roslynator.CodeActions; - -internal readonly struct CodeActionData +namespace Roslynator.CodeActions { - public CodeActionData(string title, string equivalenceKey = null) + internal readonly struct CodeActionData { - Title = title ?? throw new ArgumentNullException(nameof(title)); - EquivalenceKey = equivalenceKey; - } + public CodeActionData(string title, string equivalenceKey = null) + { + Title = title ?? throw new ArgumentNullException(nameof(title)); + EquivalenceKey = equivalenceKey; + } - public string Title { get; } + public string Title { get; } - public string EquivalenceKey { get; } + public string EquivalenceKey { get; } - public bool IsDefault => Title == null; + public bool IsDefault => Title is null; - public CodeAction ToCodeAction(Func> createChangedDocument) - { - return CodeAction.Create(Title, createChangedDocument, EquivalenceKey); - } + public CodeAction ToCodeAction(Func> createChangedDocument) + { + return CodeAction.Create(Title, createChangedDocument, EquivalenceKey); + } - public CodeAction ToCodeAction(Func> createChangedDocument) - { - return CodeAction.Create(Title, createChangedDocument, EquivalenceKey); + public CodeAction ToCodeAction(Func> createChangedDocument) + { + return CodeAction.Create(Title, createChangedDocument, EquivalenceKey); + } } } diff --git a/src/Workspaces.Core/CodeFixes/CodeFixer.cs b/src/Workspaces.Core/CodeFixes/CodeFixer.cs index 68aba81f1a..7048d6554c 100644 --- a/src/Workspaces.Core/CodeFixes/CodeFixer.cs +++ b/src/Workspaces.Core/CodeFixes/CodeFixer.cs @@ -16,652 +16,653 @@ using Roslynator.Host.Mef; using static Roslynator.Logger; -namespace Roslynator.CodeFixes; - -internal class CodeFixer +namespace Roslynator.CodeFixes { - private readonly AnalyzerLoader _analyzerLoader; - - public CodeFixer( - Solution solution, - AnalyzerLoader analyzerLoader, - IFormatProvider formatProvider = null, - CodeFixerOptions options = null) + internal class CodeFixer { - _analyzerLoader = analyzerLoader; - - Workspace = solution.Workspace; - FormatProvider = formatProvider; - Options = options ?? CodeFixerOptions.Default; - } + private readonly AnalyzerLoader _analyzerLoader; - public Workspace Workspace { get; } - - public CodeFixerOptions Options { get; } - - public IFormatProvider FormatProvider { get; } + public CodeFixer( + Solution solution, + AnalyzerLoader analyzerLoader, + IFormatProvider formatProvider = null, + CodeFixerOptions options = null) + { + _analyzerLoader = analyzerLoader; - private Solution CurrentSolution => Workspace.CurrentSolution; + Workspace = solution.Workspace; + FormatProvider = formatProvider; + Options = options ?? CodeFixerOptions.Default; + } - public async Task> FixSolutionAsync(Func predicate, CancellationToken cancellationToken = default) - { - ImmutableArray projects = CurrentSolution - .GetProjectDependencyGraph() - .GetTopologicallySortedProjects(cancellationToken) - .ToImmutableArray(); + public Workspace Workspace { get; } - var results = new List(); + public CodeFixerOptions Options { get; } - Stopwatch stopwatch = Stopwatch.StartNew(); + public IFormatProvider FormatProvider { get; } - TimeSpan lastElapsed = TimeSpan.Zero; + private Solution CurrentSolution => Workspace.CurrentSolution; - for (int i = 0; i < projects.Length; i++) + public async Task> FixSolutionAsync(Func predicate, CancellationToken cancellationToken = default) { - cancellationToken.ThrowIfCancellationRequested(); - - Project project = CurrentSolution.GetProject(projects[i]); + ImmutableArray projects = CurrentSolution + .GetProjectDependencyGraph() + .GetTopologicallySortedProjects(cancellationToken) + .ToImmutableArray(); - if (predicate == null || predicate(project)) - { - WriteLine($"Fix '{project.Name}' {$"{i + 1}/{projects.Length}"}", ConsoleColors.Cyan, Verbosity.Minimal); + var results = new List(); - ProjectFixResult result = await FixProjectAsync(project, cancellationToken).ConfigureAwait(false); + Stopwatch stopwatch = Stopwatch.StartNew(); - results.Add(result); + TimeSpan lastElapsed = TimeSpan.Zero; - if (result.Kind == ProjectFixKind.CompilerError) - break; - } - else + for (int i = 0; i < projects.Length; i++) { - WriteLine($"Skip '{project.Name}' {$"{i + 1}/{projects.Length}"}", ConsoleColors.DarkGray, Verbosity.Minimal); + cancellationToken.ThrowIfCancellationRequested(); - results.Add(ProjectFixResult.Skipped); - } + Project project = CurrentSolution.GetProject(projects[i]); - TimeSpan elapsed = stopwatch.Elapsed; + if (predicate is null || predicate(project)) + { + WriteLine($"Fix '{project.Name}' {$"{i + 1}/{projects.Length}"}", ConsoleColors.Cyan, Verbosity.Minimal); - WriteLine($"Done fixing '{project.Name}' in {elapsed - lastElapsed:mm\\:ss\\.ff}", Verbosity.Normal); + ProjectFixResult result = await FixProjectAsync(project, cancellationToken).ConfigureAwait(false); - lastElapsed = elapsed; - } + results.Add(result); - stopwatch.Stop(); + if (result.Kind == ProjectFixKind.CompilerError) + break; + } + else + { + WriteLine($"Skip '{project.Name}' {$"{i + 1}/{projects.Length}"}", ConsoleColors.DarkGray, Verbosity.Minimal); - WriteLine($"Done fixing solution '{CurrentSolution.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal); + results.Add(ProjectFixResult.Skipped); + } - return results.ToImmutableArray(); - } + TimeSpan elapsed = stopwatch.Elapsed; - public async Task FixProjectAsync(Project project, CancellationToken cancellationToken = default) - { - (ImmutableArray analyzers, ImmutableArray fixers) = _analyzerLoader.GetAnalyzersAndFixers(project: project); - - FixResult fixResult = await FixProjectAsync(project, analyzers, fixers, cancellationToken).ConfigureAwait(false); - - project = CurrentSolution.GetProject(project.Id); - - Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - - Dictionary> fixersById = fixers - .SelectMany(f => f.FixableDiagnosticIds.Select(id => (id, fixer: f))) - .GroupBy(f => f.id) - .ToDictionary(f => f.Key, g => g.Select(f => f.fixer).Distinct().ToImmutableArray()); - - ImmutableArray unfixableDiagnostics = await GetDiagnosticsAsync( - analyzers, - fixResult.FixedDiagnostics, - compilation, - project.AnalyzerOptions, - f => !fixersById.ContainsKey(f.id), - cancellationToken) - .ConfigureAwait(false); - - ImmutableArray unfixedDiagnostics = await GetDiagnosticsAsync( - analyzers, - fixResult.FixedDiagnostics.Concat(unfixableDiagnostics), - compilation, - project.AnalyzerOptions, - f => fixersById.ContainsKey(f.id), - cancellationToken) - .ConfigureAwait(false); - - int numberOfAddedFileBanners = 0; - - if (Options.FileBannerLines.Any()) - numberOfAddedFileBanners = await AddFileBannerAsync(CurrentSolution.GetProject(project.Id), Options.FileBannerLines, cancellationToken).ConfigureAwait(false); - - ImmutableArray formattedDocuments = ImmutableArray.Empty; - - if (Options.Format) - formattedDocuments = await FormatProjectAsync(CurrentSolution.GetProject(project.Id), cancellationToken).ConfigureAwait(false); - - var result = new ProjectFixResult( - kind: fixResult.Kind, - fixedDiagnostics: fixResult.FixedDiagnostics.Select(f => DiagnosticInfo.Create(f)), - unfixedDiagnostics: unfixedDiagnostics.Select(f => DiagnosticInfo.Create(f)), - unfixableDiagnostics: unfixableDiagnostics.Select(f => DiagnosticInfo.Create(f)), - numberOfFormattedDocuments: (Options.FileBannerLines.Any()) ? formattedDocuments.Length : -1, - numberOfAddedFileBanners: (Options.Format) ? numberOfAddedFileBanners : -1); - - LogHelpers.WriteFixSummary( - fixResult.FixedDiagnostics, - unfixedDiagnostics, - unfixableDiagnostics, - baseDirectoryPath: Path.GetDirectoryName(project.FilePath), - indentation: " ", - formatProvider: FormatProvider, - verbosity: Verbosity.Detailed); - - return result; - } + WriteLine($"Done fixing '{project.Name}' in {elapsed - lastElapsed:mm\\:ss\\.ff}", Verbosity.Normal); - private async Task FixProjectAsync( - Project project, - ImmutableArray analyzers, - ImmutableArray fixers, - CancellationToken cancellationToken) - { - if (!fixers.Any()) - { - WriteLine( - (analyzers.Any()) ? " No fixers found" : " No analyzers and fixers found", - ConsoleColors.DarkGray, - Verbosity.Normal); + lastElapsed = elapsed; + } - return new FixResult(ProjectFixKind.NoFixers); - } + stopwatch.Stop(); - Dictionary> fixersById = fixers - .SelectMany(f => f.FixableDiagnosticIds.Select(id => (id, fixer: f))) - .GroupBy(f => f.id) - .ToDictionary(f => f.Key, g => g.Select(f => f.fixer).Distinct().ToImmutableArray()); + WriteLine($"Done fixing solution '{CurrentSolution.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal); - analyzers = analyzers - .Where(analyzer => analyzer.SupportedDiagnostics.Any(descriptor => fixersById.ContainsKey(descriptor.Id))) - .ToImmutableArray(); + return results.ToImmutableArray(); + } - Dictionary> analyzersById = analyzers - .SelectMany(f => f.SupportedDiagnostics.Select(d => (id: d.Id, analyzer: f))) - .GroupBy(f => f.id, f => f.analyzer) - .ToDictionary(g => g.Key, g => g.Select(analyzer => analyzer).Distinct().ToImmutableArray()); + public async Task FixProjectAsync(Project project, CancellationToken cancellationToken = default) + { + (ImmutableArray analyzers, ImmutableArray fixers) = _analyzerLoader.GetAnalyzersAndFixers(project: project); - LogHelpers.WriteUsedAnalyzers(analyzers, f => fixersById.ContainsKey(f.Id), Options, ConsoleColors.DarkGray, Verbosity.Diagnostic); - LogHelpers.WriteUsedFixers(fixers, Options, ConsoleColors.DarkGray, Verbosity.Diagnostic); + FixResult fixResult = await FixProjectAsync(project, analyzers, fixers, cancellationToken).ConfigureAwait(false); - ImmutableArray.Builder fixedDiagnostics = ImmutableArray.CreateBuilder(); + project = CurrentSolution.GetProject(project.Id); - ImmutableArray previousDiagnostics = ImmutableArray.Empty; - ImmutableArray previousPreviousDiagnostics = ImmutableArray.Empty; + Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - var fixKind = ProjectFixKind.Success; + Dictionary> fixersById = fixers + .SelectMany(f => f.FixableDiagnosticIds.Select(id => (id, fixer: f))) + .GroupBy(f => f.id) + .ToDictionary(f => f.Key, g => g.Select(f => f.fixer).Distinct().ToImmutableArray()); + + ImmutableArray unfixableDiagnostics = await GetDiagnosticsAsync( + analyzers, + fixResult.FixedDiagnostics, + compilation, + project.AnalyzerOptions, + f => !fixersById.ContainsKey(f.id), + cancellationToken) + .ConfigureAwait(false); + + ImmutableArray unfixedDiagnostics = await GetDiagnosticsAsync( + analyzers, + fixResult.FixedDiagnostics.Concat(unfixableDiagnostics), + compilation, + project.AnalyzerOptions, + f => fixersById.ContainsKey(f.id), + cancellationToken) + .ConfigureAwait(false); + + int numberOfAddedFileBanners = 0; + + if (Options.FileBannerLines.Any()) + numberOfAddedFileBanners = await AddFileBannerAsync(CurrentSolution.GetProject(project.Id), Options.FileBannerLines, cancellationToken).ConfigureAwait(false); + + ImmutableArray formattedDocuments = ImmutableArray.Empty; + + if (Options.Format) + formattedDocuments = await FormatProjectAsync(CurrentSolution.GetProject(project.Id), cancellationToken).ConfigureAwait(false); + + var result = new ProjectFixResult( + kind: fixResult.Kind, + fixedDiagnostics: fixResult.FixedDiagnostics.Select(f => DiagnosticInfo.Create(f)), + unfixedDiagnostics: unfixedDiagnostics.Select(f => DiagnosticInfo.Create(f)), + unfixableDiagnostics: unfixableDiagnostics.Select(f => DiagnosticInfo.Create(f)), + numberOfFormattedDocuments: (Options.FileBannerLines.Any()) ? formattedDocuments.Length : -1, + numberOfAddedFileBanners: (Options.Format) ? numberOfAddedFileBanners : -1); + + LogHelpers.WriteFixSummary( + fixResult.FixedDiagnostics, + unfixedDiagnostics, + unfixableDiagnostics, + baseDirectoryPath: Path.GetDirectoryName(project.FilePath), + indentation: " ", + formatProvider: FormatProvider, + verbosity: Verbosity.Detailed); + + return result; + } - for (int iterationCount = 1; ; iterationCount++) + private async Task FixProjectAsync( + Project project, + ImmutableArray analyzers, + ImmutableArray fixers, + CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); + if (!fixers.Any()) + { + WriteLine( + (analyzers.Any()) ? " No fixers found" : " No analyzers and fixers found", + ConsoleColors.DarkGray, + Verbosity.Normal); - project = CurrentSolution.GetProject(project.Id); + return new FixResult(ProjectFixKind.NoFixers); + } - WriteLine($" Compile '{project.Name}'{((iterationCount > 1) ? $" iteration {iterationCount}" : "")}", Verbosity.Normal); + Dictionary> fixersById = fixers + .SelectMany(f => f.FixableDiagnosticIds.Select(id => (id, fixer: f))) + .GroupBy(f => f.id) + .ToDictionary(f => f.Key, g => g.Select(f => f.fixer).Distinct().ToImmutableArray()); - Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + analyzers = analyzers + .Where(analyzer => analyzer.SupportedDiagnostics.Any(descriptor => fixersById.ContainsKey(descriptor.Id))) + .ToImmutableArray(); - ImmutableArray compilerDiagnostics = compilation.GetDiagnostics(cancellationToken); + Dictionary> analyzersById = analyzers + .SelectMany(f => f.SupportedDiagnostics.Select(d => (id: d.Id, analyzer: f))) + .GroupBy(f => f.id, f => f.analyzer) + .ToDictionary(g => g.Key, g => g.Select(analyzer => analyzer).Distinct().ToImmutableArray()); - if (!VerifyCompilerDiagnostics(compilerDiagnostics, project)) - return new FixResult(ProjectFixKind.CompilerError, fixedDiagnostics); + LogHelpers.WriteUsedAnalyzers(analyzers, f => fixersById.ContainsKey(f.Id), Options, ConsoleColors.DarkGray, Verbosity.Diagnostic); + LogHelpers.WriteUsedFixers(fixers, Options, ConsoleColors.DarkGray, Verbosity.Diagnostic); - WriteLine($" Analyze '{project.Name}'", Verbosity.Normal); + ImmutableArray.Builder fixedDiagnostics = ImmutableArray.CreateBuilder(); - ImmutableArray diagnostics = ImmutableArray.Empty; + ImmutableArray previousDiagnostics = ImmutableArray.Empty; + ImmutableArray previousPreviousDiagnostics = ImmutableArray.Empty; - if (analyzers.Any()) + var fixKind = ProjectFixKind.Success; + + for (int iterationCount = 1; ; iterationCount++) { - diagnostics = await GetAnalyzerDiagnosticsAsync(compilation, analyzers, project.AnalyzerOptions, cancellationToken).ConfigureAwait(false); - LogHelpers.WriteAnalyzerExceptionDiagnostics(diagnostics); - } + cancellationToken.ThrowIfCancellationRequested(); - diagnostics = GetFixableDiagnostics(diagnostics, compilerDiagnostics); + project = CurrentSolution.GetProject(project.Id); - int length = diagnostics.Length; + WriteLine($" Compile '{project.Name}'{((iterationCount > 1) ? $" iteration {iterationCount}" : "")}", Verbosity.Normal); - if (length == 0) - break; + Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - if (length == previousDiagnostics.Length - && !diagnostics.Except(previousDiagnostics, DiagnosticDeepEqualityComparer.Instance).Any()) - { - break; - } + ImmutableArray compilerDiagnostics = compilation.GetDiagnostics(cancellationToken); - if (length == previousPreviousDiagnostics.Length - && !diagnostics.Except(previousPreviousDiagnostics, DiagnosticDeepEqualityComparer.Instance).Any()) - { - LogHelpers.WriteInfiniteLoopSummary(diagnostics, previousDiagnostics, project, FormatProvider); + if (!VerifyCompilerDiagnostics(compilerDiagnostics, project)) + return new FixResult(ProjectFixKind.CompilerError, fixedDiagnostics); - fixKind = ProjectFixKind.InfiniteLoop; - break; - } + WriteLine($" Analyze '{project.Name}'", Verbosity.Normal); - WriteLine($" Found {length} {((length == 1) ? "diagnostic" : "diagnostics")} in '{project.Name}'", Verbosity.Normal); + ImmutableArray diagnostics = ImmutableArray.Empty; - foreach (DiagnosticDescriptor descriptor in GetSortedDescriptors(diagnostics)) - { - cancellationToken.ThrowIfCancellationRequested(); + if (analyzers.Any()) + { + diagnostics = await GetAnalyzerDiagnosticsAsync(compilation, analyzers, project.AnalyzerOptions, cancellationToken).ConfigureAwait(false); + LogHelpers.WriteAnalyzerExceptionDiagnostics(diagnostics); + } - string diagnosticId = descriptor.Id; + diagnostics = GetFixableDiagnostics(diagnostics, compilerDiagnostics); - DiagnosticFixResult result = await FixDiagnosticsAsync( - descriptor, - (descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Compiler)) - ? default - : analyzersById[diagnosticId], - fixersById[diagnosticId], - CurrentSolution.GetProject(project.Id), - cancellationToken) - .ConfigureAwait(false); + int length = diagnostics.Length; - if (result.Kind == DiagnosticFixKind.Success) + if (length == 0) + break; + + if (length == previousDiagnostics.Length + && !diagnostics.Except(previousDiagnostics, DiagnosticDeepEqualityComparer.Instance).Any()) { - fixedDiagnostics.AddRange(result.FixedDiagnostics); + break; } - else if (result.Kind == DiagnosticFixKind.CompilerError) + + if (length == previousPreviousDiagnostics.Length + && !diagnostics.Except(previousPreviousDiagnostics, DiagnosticDeepEqualityComparer.Instance).Any()) { - return new FixResult(ProjectFixKind.CompilerError, fixedDiagnostics); + LogHelpers.WriteInfiniteLoopSummary(diagnostics, previousDiagnostics, project, FormatProvider); + + fixKind = ProjectFixKind.InfiniteLoop; + break; } - } - if (iterationCount == Options.MaxIterations) - break; + WriteLine($" Found {length} {((length == 1) ? "diagnostic" : "diagnostics")} in '{project.Name}'", Verbosity.Normal); - previousPreviousDiagnostics = previousDiagnostics; - previousDiagnostics = diagnostics; - } + foreach (DiagnosticDescriptor descriptor in GetSortedDescriptors(diagnostics)) + { + cancellationToken.ThrowIfCancellationRequested(); - return new FixResult(fixKind, fixedDiagnostics); + string diagnosticId = descriptor.Id; - ImmutableArray GetFixableDiagnostics( - ImmutableArray diagnostics, - ImmutableArray compilerDiagnostics) - { - IEnumerable fixableCompilerDiagnostics = compilerDiagnostics - .Where(f => f.Severity != DiagnosticSeverity.Error - && !Options.IgnoredCompilerDiagnosticIds.Contains(f.Id) - && fixersById.ContainsKey(f.Id)); + DiagnosticFixResult result = await FixDiagnosticsAsync( + descriptor, + (descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Compiler)) + ? default + : analyzersById[diagnosticId], + fixersById[diagnosticId], + CurrentSolution.GetProject(project.Id), + cancellationToken) + .ConfigureAwait(false); - return diagnostics - .Where(f => f.IsEffective(Options, project.CompilationOptions) - && analyzersById.ContainsKey(f.Id) - && fixersById.ContainsKey(f.Id)) - .Concat(fixableCompilerDiagnostics) - .ToImmutableArray(); - } + if (result.Kind == DiagnosticFixKind.Success) + { + fixedDiagnostics.AddRange(result.FixedDiagnostics); + } + else if (result.Kind == DiagnosticFixKind.CompilerError) + { + return new FixResult(ProjectFixKind.CompilerError, fixedDiagnostics); + } + } - IEnumerable GetSortedDescriptors( - ImmutableArray diagnostics) - { - Dictionary countByDescriptor = diagnostics - .GroupBy(f => f.Descriptor, DiagnosticDescriptorComparer.Id) - .ToDictionary(f => f.Key, f => f.Count()); + if (iterationCount == Options.MaxIterations) + break; - return countByDescriptor - .Select(f => f.Key) - .OrderBy(f => f, new DiagnosticDescriptorFixComparer(countByDescriptor, fixersById)); - } - } + previousPreviousDiagnostics = previousDiagnostics; + previousDiagnostics = diagnostics; + } - private async Task FixDiagnosticsAsync( - DiagnosticDescriptor descriptor, - ImmutableArray analyzers, - ImmutableArray fixers, - Project project, - CancellationToken cancellationToken) - { - ImmutableArray.Builder fixedDiagnostics = ImmutableArray.CreateBuilder(); + return new FixResult(fixKind, fixedDiagnostics); + + ImmutableArray GetFixableDiagnostics( + ImmutableArray diagnostics, + ImmutableArray compilerDiagnostics) + { + IEnumerable fixableCompilerDiagnostics = compilerDiagnostics + .Where(f => f.Severity != DiagnosticSeverity.Error + && !Options.IgnoredCompilerDiagnosticIds.Contains(f.Id) + && fixersById.ContainsKey(f.Id)); + + return diagnostics + .Where(f => f.IsEffective(Options, project.CompilationOptions) + && analyzersById.ContainsKey(f.Id) + && fixersById.ContainsKey(f.Id)) + .Concat(fixableCompilerDiagnostics) + .ToImmutableArray(); + } - ImmutableArray diagnostics = ImmutableArray.Empty; - ImmutableArray previousDiagnostics = ImmutableArray.Empty; - ImmutableArray previousDiagnosticsToFix = ImmutableArray.Empty; + IEnumerable GetSortedDescriptors( + ImmutableArray diagnostics) + { + Dictionary countByDescriptor = diagnostics + .GroupBy(f => f.Descriptor, DiagnosticDescriptorComparer.Id) + .ToDictionary(f => f.Key, f => f.Count()); - int length = 0; - var fixKind = DiagnosticFixKind.NotFixed; + return countByDescriptor + .Select(f => f.Key) + .OrderBy(f => f, new DiagnosticDescriptorFixComparer(countByDescriptor, fixersById)); + } + } - while (true) + private async Task FixDiagnosticsAsync( + DiagnosticDescriptor descriptor, + ImmutableArray analyzers, + ImmutableArray fixers, + Project project, + CancellationToken cancellationToken) { - Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + ImmutableArray.Builder fixedDiagnostics = ImmutableArray.CreateBuilder(); + + ImmutableArray diagnostics = ImmutableArray.Empty; + ImmutableArray previousDiagnostics = ImmutableArray.Empty; + ImmutableArray previousDiagnosticsToFix = ImmutableArray.Empty; - ImmutableArray compilerDiagnostics = compilation.GetDiagnostics(cancellationToken); + int length = 0; + var fixKind = DiagnosticFixKind.NotFixed; - if (!VerifyCompilerDiagnostics(compilerDiagnostics, project)) + while (true) { - fixKind = DiagnosticFixKind.CompilerError; + Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - if (!previousDiagnostics.Any()) - break; - } + ImmutableArray compilerDiagnostics = compilation.GetDiagnostics(cancellationToken); - if (analyzers.IsDefault) - { - diagnostics = compilerDiagnostics; - } - else - { - diagnostics = await GetAnalyzerDiagnosticsAsync(compilation, analyzers, project.AnalyzerOptions, cancellationToken).ConfigureAwait(false); - } + if (!VerifyCompilerDiagnostics(compilerDiagnostics, project)) + { + fixKind = DiagnosticFixKind.CompilerError; - diagnostics = diagnostics - .Where(f => f.Id == descriptor.Id && f.Severity >= Options.SeverityLevel) - .ToImmutableArray(); + if (!previousDiagnostics.Any()) + break; + } - if (fixKind == DiagnosticFixKind.CompilerError) - { - break; - } - else if (fixKind == DiagnosticFixKind.Success) - { - if (Options.BatchSize <= 0 - || length <= Options.BatchSize) + if (analyzers.IsDefault) + { + diagnostics = compilerDiagnostics; + } + else + { + diagnostics = await GetAnalyzerDiagnosticsAsync(compilation, analyzers, project.AnalyzerOptions, cancellationToken).ConfigureAwait(false); + } + + diagnostics = diagnostics + .Where(f => f.Id == descriptor.Id && f.Severity >= Options.SeverityLevel) + .ToImmutableArray(); + + if (fixKind == DiagnosticFixKind.CompilerError) + { + break; + } + else if (fixKind == DiagnosticFixKind.Success) + { + if (Options.BatchSize <= 0 + || length <= Options.BatchSize) + { + break; + } + } + else if (previousDiagnostics.Any() + && fixKind != DiagnosticFixKind.PartiallyFixed) { break; } - } - else if (previousDiagnostics.Any() - && fixKind != DiagnosticFixKind.PartiallyFixed) - { - break; - } - length = diagnostics.Length; + length = diagnostics.Length; - if (length == 0) - break; + if (length == 0) + break; - if (length == previousDiagnostics.Length - && !diagnostics.Except(previousDiagnostics, DiagnosticDeepEqualityComparer.Instance).Any()) - { - break; - } + if (length == previousDiagnostics.Length + && !diagnostics.Except(previousDiagnostics, DiagnosticDeepEqualityComparer.Instance).Any()) + { + break; + } - fixedDiagnostics.AddRange(previousDiagnosticsToFix.Except(diagnostics, DiagnosticDeepEqualityComparer.Instance)); + fixedDiagnostics.AddRange(previousDiagnosticsToFix.Except(diagnostics, DiagnosticDeepEqualityComparer.Instance)); - previousDiagnostics = diagnostics; + previousDiagnostics = diagnostics; - if (Options.FixAllScope == FixAllScope.Document) - { - foreach (IGrouping grouping in diagnostics - .GroupBy(f => f.Location.SourceTree) - .OrderByDescending(f => f.Count())) + if (Options.FixAllScope == FixAllScope.Document) { - IEnumerable syntaxTreeDiagnostics = grouping.AsEnumerable(); + foreach (IGrouping grouping in diagnostics + .GroupBy(f => f.Location.SourceTree) + .OrderByDescending(f => f.Count())) + { + IEnumerable syntaxTreeDiagnostics = grouping.AsEnumerable(); - if (Options.BatchSize > 0) - syntaxTreeDiagnostics = syntaxTreeDiagnostics.Take(Options.BatchSize); + if (Options.BatchSize > 0) + syntaxTreeDiagnostics = syntaxTreeDiagnostics.Take(Options.BatchSize); - ImmutableArray diagnosticsCandidate = syntaxTreeDiagnostics.ToImmutableArray(); + ImmutableArray diagnosticsCandidate = syntaxTreeDiagnostics.ToImmutableArray(); - DiagnosticFixKind fixKindCandidate = await FixDiagnosticsAsync(diagnosticsCandidate, descriptor, fixers, project, cancellationToken).ConfigureAwait(false); + DiagnosticFixKind fixKindCandidate = await FixDiagnosticsAsync(diagnosticsCandidate, descriptor, fixers, project, cancellationToken).ConfigureAwait(false); - if (fixKindCandidate == DiagnosticFixKind.Success - || fixKindCandidate == DiagnosticFixKind.PartiallyFixed) - { - diagnostics = diagnosticsCandidate; - fixKind = fixKindCandidate; - break; + if (fixKindCandidate == DiagnosticFixKind.Success + || fixKindCandidate == DiagnosticFixKind.PartiallyFixed) + { + diagnostics = diagnosticsCandidate; + fixKind = fixKindCandidate; + break; + } } } - } - else - { - if (Options.BatchSize > 0 - && length > Options.BatchSize) + else { - diagnostics = ImmutableArray.CreateRange(diagnostics, 0, Options.BatchSize, f => f); + if (Options.BatchSize > 0 + && length > Options.BatchSize) + { + diagnostics = ImmutableArray.CreateRange(diagnostics, 0, Options.BatchSize, f => f); + } + + fixKind = await FixDiagnosticsAsync(diagnostics, descriptor, fixers, project, cancellationToken).ConfigureAwait(false); } - fixKind = await FixDiagnosticsAsync(diagnostics, descriptor, fixers, project, cancellationToken).ConfigureAwait(false); + previousDiagnosticsToFix = diagnostics; + + project = CurrentSolution.GetProject(project.Id); } - previousDiagnosticsToFix = diagnostics; + fixedDiagnostics.AddRange(previousDiagnosticsToFix.Except(diagnostics, DiagnosticDeepEqualityComparer.Instance)); - project = CurrentSolution.GetProject(project.Id); + return new DiagnosticFixResult(fixKind, fixedDiagnostics.ToImmutableArray()); } - fixedDiagnostics.AddRange(previousDiagnosticsToFix.Except(diagnostics, DiagnosticDeepEqualityComparer.Instance)); - - return new DiagnosticFixResult(fixKind, fixedDiagnostics.ToImmutableArray()); - } - - private async Task FixDiagnosticsAsync( - ImmutableArray diagnostics, - DiagnosticDescriptor descriptor, - ImmutableArray fixers, - Project project, - CancellationToken cancellationToken) - { - WriteLine($" Fix {diagnostics.Length} {descriptor.Id} '{descriptor.Title}'", diagnostics[0].Severity.GetColors(), Verbosity.Normal); - - LogHelpers.WriteDiagnostics(diagnostics, baseDirectoryPath: Path.GetDirectoryName(project.FilePath), formatProvider: FormatProvider, indentation: " ", verbosity: Verbosity.Detailed); + private async Task FixDiagnosticsAsync( + ImmutableArray diagnostics, + DiagnosticDescriptor descriptor, + ImmutableArray fixers, + Project project, + CancellationToken cancellationToken) + { + WriteLine($" Fix {diagnostics.Length} {descriptor.Id} '{descriptor.Title}'", diagnostics[0].Severity.GetColors(), Verbosity.Normal); - DiagnosticFix diagnosticFix = await DiagnosticFixProvider.GetFixAsync( - diagnostics, - descriptor, - fixers, - project, - Options, - FormatProvider, - cancellationToken) - .ConfigureAwait(false); + LogHelpers.WriteDiagnostics(diagnostics, baseDirectoryPath: Path.GetDirectoryName(project.FilePath), formatProvider: FormatProvider, indentation: " ", verbosity: Verbosity.Detailed); - if (diagnosticFix.FixProvider2 != null) - return DiagnosticFixKind.MultipleFixers; + DiagnosticFix diagnosticFix = await DiagnosticFixProvider.GetFixAsync( + diagnostics, + descriptor, + fixers, + project, + Options, + FormatProvider, + cancellationToken) + .ConfigureAwait(false); - CodeAction fix = diagnosticFix.CodeAction; + if (diagnosticFix.FixProvider2 is not null) + return DiagnosticFixKind.MultipleFixers; - if (fix != null) - { - ImmutableArray operations = await fix.GetOperationsAsync(cancellationToken).ConfigureAwait(false); + CodeAction fix = diagnosticFix.CodeAction; - if (operations.Length == 1) + if (fix is not null) { - operations[0].Apply(Workspace, cancellationToken); + ImmutableArray operations = await fix.GetOperationsAsync(cancellationToken).ConfigureAwait(false); - return (diagnostics.Length != 1 && diagnosticFix.FixProvider.GetFixAllProvider() == null) - ? DiagnosticFixKind.PartiallyFixed - : DiagnosticFixKind.Success; - } - else if (operations.Length > 1) - { - LogHelpers.WriteMultipleOperationsSummary(fix); + if (operations.Length == 1) + { + operations[0].Apply(Workspace, cancellationToken); + + return (diagnostics.Length != 1 && diagnosticFix.FixProvider.GetFixAllProvider() is null) + ? DiagnosticFixKind.PartiallyFixed + : DiagnosticFixKind.Success; + } + else if (operations.Length > 1) + { + LogHelpers.WriteMultipleOperationsSummary(fix); + } } - } - return DiagnosticFixKind.NotFixed; - } + return DiagnosticFixKind.NotFixed; + } - private bool VerifyCompilerDiagnostics(ImmutableArray diagnostics, Project project) - { - int errorCount = LogHelpers.WriteCompilerErrors( - diagnostics, - baseDirectoryPath: Path.GetDirectoryName(project.FilePath), - ignoredCompilerDiagnosticIds: Options.IgnoredCompilerDiagnosticIds, - formatProvider: FormatProvider, - indentation: " "); - - if (errorCount > 0) + private bool VerifyCompilerDiagnostics(ImmutableArray diagnostics, Project project) { - if (!Options.IgnoreCompilerErrors) + int errorCount = LogHelpers.WriteCompilerErrors( + diagnostics, + baseDirectoryPath: Path.GetDirectoryName(project.FilePath), + ignoredCompilerDiagnosticIds: Options.IgnoredCompilerDiagnosticIds, + formatProvider: FormatProvider, + indentation: " "); + + if (errorCount > 0) { + if (!Options.IgnoreCompilerErrors) + { #if DEBUG - Console.Write("Stop (Y/N)? "); + Console.Write("Stop (Y/N)? "); - return char.ToUpperInvariant((char)Console.Read()) != 'Y'; + return char.ToUpperInvariant((char)Console.Read()) != 'Y'; #else - return false; + return false; #endif + } } + + return true; } - return true; - } + private async Task> GetDiagnosticsAsync( + ImmutableArray analyzers, + IEnumerable except, + Compilation compilation, + AnalyzerOptions analyzerOptions, + Func<(string id, DiagnosticAnalyzer analyzer), bool> predicate, + CancellationToken cancellationToken) + { + Dictionary> analyzersById = analyzers + .SelectMany(f => f.SupportedDiagnostics.Select(d => (id: d.Id, analyzer: f))) + .Where(predicate) + .GroupBy(f => f.id, f => f.analyzer) + .ToDictionary(g => g.Key, g => g.Select(analyzer => analyzer).Distinct().ToImmutableArray()); + + analyzers = analyzersById + .SelectMany(f => f.Value) + .Distinct() + .ToImmutableArray(); - private async Task> GetDiagnosticsAsync( - ImmutableArray analyzers, - IEnumerable except, - Compilation compilation, - AnalyzerOptions analyzerOptions, - Func<(string id, DiagnosticAnalyzer analyzer), bool> predicate, - CancellationToken cancellationToken) - { - Dictionary> analyzersById = analyzers - .SelectMany(f => f.SupportedDiagnostics.Select(d => (id: d.Id, analyzer: f))) - .Where(predicate) - .GroupBy(f => f.id, f => f.analyzer) - .ToDictionary(g => g.Key, g => g.Select(analyzer => analyzer).Distinct().ToImmutableArray()); - - analyzers = analyzersById - .SelectMany(f => f.Value) - .Distinct() - .ToImmutableArray(); - - if (!analyzers.Any()) - return ImmutableArray.Empty; - - ImmutableArray diagnostics = await GetAnalyzerDiagnosticsAsync(compilation, analyzers, analyzerOptions, cancellationToken).ConfigureAwait(false); - - return diagnostics - .Where(f => f.IsEffective(Options, compilation.Options) - && analyzersById.ContainsKey(f.Id)) - .Except(except, DiagnosticDeepEqualityComparer.Instance) - .ToImmutableArray(); - } + if (!analyzers.Any()) + return ImmutableArray.Empty; - private async Task AddFileBannerAsync( - Project project, - ImmutableArray banner, - CancellationToken cancellationToken) - { - int count = 0; + ImmutableArray diagnostics = await GetAnalyzerDiagnosticsAsync(compilation, analyzers, analyzerOptions, cancellationToken).ConfigureAwait(false); - string solutionDirectory = Path.GetDirectoryName(project.Solution.FilePath); + return diagnostics + .Where(f => f.IsEffective(Options, compilation.Options) + && analyzersById.ContainsKey(f.Id)) + .Except(except, DiagnosticDeepEqualityComparer.Instance) + .ToImmutableArray(); + } - foreach (DocumentId documentId in project.DocumentIds) + private async Task AddFileBannerAsync( + Project project, + ImmutableArray banner, + CancellationToken cancellationToken) { - Document document = project.GetDocument(documentId); + int count = 0; - if (GeneratedCodeUtility.IsGeneratedCodeFile(document.FilePath)) - continue; + string solutionDirectory = Path.GetDirectoryName(project.Solution.FilePath); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + foreach (DocumentId documentId in project.DocumentIds) + { + Document document = project.GetDocument(documentId); - ISyntaxFactsService syntaxFacts = MefWorkspaceServices.Default.GetService(project.Language); + if (GeneratedCodeUtility.IsGeneratedCodeFile(document.FilePath)) + continue; - if (syntaxFacts.BeginsWithAutoGeneratedComment(root)) - continue; + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - if (syntaxFacts.BeginsWithBanner(root, banner)) - continue; + ISyntaxFactsService syntaxFacts = MefWorkspaceServices.Default.GetService(project.Language); - SyntaxTriviaList leading = root.GetLeadingTrivia(); + if (syntaxFacts.BeginsWithAutoGeneratedComment(root)) + continue; - SyntaxTriviaList newLeading = leading.InsertRange(0, banner.SelectMany(f => syntaxFacts.ParseLeadingTrivia(syntaxFacts.SingleLineCommentStart + f + Environment.NewLine))); + if (syntaxFacts.BeginsWithBanner(root, banner)) + continue; - if (!syntaxFacts.IsEndOfLineTrivia(leading.LastOrDefault())) - newLeading = newLeading.AddRange(syntaxFacts.ParseLeadingTrivia(Environment.NewLine)); + SyntaxTriviaList leading = root.GetLeadingTrivia(); - SyntaxNode newRoot = root.WithLeadingTrivia(newLeading); + SyntaxTriviaList newLeading = leading.InsertRange(0, banner.SelectMany(f => syntaxFacts.ParseLeadingTrivia(syntaxFacts.SingleLineCommentStart + f + Environment.NewLine))); - Document newDocument = document.WithSyntaxRoot(newRoot); + if (!syntaxFacts.IsEndOfLineTrivia(leading.LastOrDefault())) + newLeading = newLeading.AddRange(syntaxFacts.ParseLeadingTrivia(Environment.NewLine)); - WriteLine($" Add banner to '{PathUtilities.TrimStart(document.FilePath, solutionDirectory)}'", ConsoleColors.DarkGray, Verbosity.Detailed); + SyntaxNode newRoot = root.WithLeadingTrivia(newLeading); - project = newDocument.Project; + Document newDocument = document.WithSyntaxRoot(newRoot); - count++; - } + WriteLine($" Add banner to '{PathUtilities.TrimStart(document.FilePath, solutionDirectory)}'", ConsoleColors.DarkGray, Verbosity.Detailed); - if (count > 0 - && !Workspace.TryApplyChanges(project.Solution)) - { - Debug.Fail($"Cannot apply changes to solution '{project.Solution.FilePath}'"); - WriteLine($"Cannot apply changes to solution '{project.Solution.FilePath}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + project = newDocument.Project; + + count++; + } + + if (count > 0 + && !Workspace.TryApplyChanges(project.Solution)) + { + Debug.Fail($"Cannot apply changes to solution '{project.Solution.FilePath}'"); + WriteLine($"Cannot apply changes to solution '{project.Solution.FilePath}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + } + + return count; } - return count; - } + private async Task> FormatProjectAsync(Project project, CancellationToken cancellationToken) + { + WriteLine($" Format '{project.Name}'", Verbosity.Normal); - private async Task> FormatProjectAsync(Project project, CancellationToken cancellationToken) - { - WriteLine($" Format '{project.Name}'", Verbosity.Normal); + ISyntaxFactsService syntaxFacts = MefWorkspaceServices.Default.GetService(project.Language); - ISyntaxFactsService syntaxFacts = MefWorkspaceServices.Default.GetService(project.Language); + Project newProject = await CodeFormatter.FormatProjectAsync(project, syntaxFacts, cancellationToken).ConfigureAwait(false); - Project newProject = await CodeFormatter.FormatProjectAsync(project, syntaxFacts, cancellationToken).ConfigureAwait(false); + string solutionDirectory = Path.GetDirectoryName(project.Solution.FilePath); - string solutionDirectory = Path.GetDirectoryName(project.Solution.FilePath); + ImmutableArray formattedDocuments = await CodeFormatter.GetFormattedDocumentsAsync(project, newProject, syntaxFacts).ConfigureAwait(false); - ImmutableArray formattedDocuments = await CodeFormatter.GetFormattedDocumentsAsync(project, newProject, syntaxFacts).ConfigureAwait(false); + LogHelpers.WriteFormattedDocuments(formattedDocuments, project, solutionDirectory); - LogHelpers.WriteFormattedDocuments(formattedDocuments, project, solutionDirectory); + if (formattedDocuments.Length > 0 + && !Workspace.TryApplyChanges(newProject.Solution)) + { + Debug.Fail($"Cannot apply changes to solution '{newProject.Solution.FilePath}'"); + WriteLine($"Cannot apply changes to solution '{newProject.Solution.FilePath}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + } - if (formattedDocuments.Length > 0 - && !Workspace.TryApplyChanges(newProject.Solution)) - { - Debug.Fail($"Cannot apply changes to solution '{newProject.Solution.FilePath}'"); - WriteLine($"Cannot apply changes to solution '{newProject.Solution.FilePath}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + return formattedDocuments; } - return formattedDocuments; - } - - private Task> GetAnalyzerDiagnosticsAsync( - Compilation compilation, - ImmutableArray analyzers, - AnalyzerOptions analyzerOptions, - CancellationToken cancellationToken = default) - { - var compilationWithAnalyzersOptions = new CompilationWithAnalyzersOptions( - analyzerOptions, - onAnalyzerException: default(Action), - concurrentAnalysis: Options.ConcurrentAnalysis, - logAnalyzerExecutionTime: false, - reportSuppressedDiagnostics: false); + private Task> GetAnalyzerDiagnosticsAsync( + Compilation compilation, + ImmutableArray analyzers, + AnalyzerOptions analyzerOptions, + CancellationToken cancellationToken = default) + { + var compilationWithAnalyzersOptions = new CompilationWithAnalyzersOptions( + analyzerOptions, + onAnalyzerException: default(Action), + concurrentAnalysis: Options.ConcurrentAnalysis, + logAnalyzerExecutionTime: false, + reportSuppressedDiagnostics: false); - var compilationWithAnalyzers = new CompilationWithAnalyzers(compilation, analyzers, compilationWithAnalyzersOptions); + var compilationWithAnalyzers = new CompilationWithAnalyzers(compilation, analyzers, compilationWithAnalyzersOptions); - return compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(cancellationToken); - } + return compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(cancellationToken); + } - private class FixResult - { - internal static FixResult Skipped { get; } = new(ProjectFixKind.Skipped); - - internal FixResult( - ProjectFixKind kind, - IEnumerable fixedDiagnostics = default, - IEnumerable unfixedDiagnostics = default, - IEnumerable unfixableDiagnostics = default, - int numberOfFormattedDocuments = -1, - int numberOfAddedFileBanners = -1) + private class FixResult { - Kind = kind; - FixedDiagnostics = fixedDiagnostics?.ToImmutableArray() ?? ImmutableArray.Empty; - UnfixedDiagnostics = unfixedDiagnostics?.ToImmutableArray() ?? ImmutableArray.Empty; - UnfixableDiagnostics = unfixableDiagnostics?.ToImmutableArray() ?? ImmutableArray.Empty; - NumberOfFormattedDocuments = numberOfFormattedDocuments; - NumberOfAddedFileBanners = numberOfAddedFileBanners; - } + internal static FixResult Skipped { get; } = new(ProjectFixKind.Skipped); + + internal FixResult( + ProjectFixKind kind, + IEnumerable fixedDiagnostics = default, + IEnumerable unfixedDiagnostics = default, + IEnumerable unfixableDiagnostics = default, + int numberOfFormattedDocuments = -1, + int numberOfAddedFileBanners = -1) + { + Kind = kind; + FixedDiagnostics = fixedDiagnostics?.ToImmutableArray() ?? ImmutableArray.Empty; + UnfixedDiagnostics = unfixedDiagnostics?.ToImmutableArray() ?? ImmutableArray.Empty; + UnfixableDiagnostics = unfixableDiagnostics?.ToImmutableArray() ?? ImmutableArray.Empty; + NumberOfFormattedDocuments = numberOfFormattedDocuments; + NumberOfAddedFileBanners = numberOfAddedFileBanners; + } - public ProjectFixKind Kind { get; } + public ProjectFixKind Kind { get; } - public ImmutableArray FixedDiagnostics { get; } + public ImmutableArray FixedDiagnostics { get; } - public ImmutableArray UnfixedDiagnostics { get; } + public ImmutableArray UnfixedDiagnostics { get; } - public ImmutableArray UnfixableDiagnostics { get; } + public ImmutableArray UnfixableDiagnostics { get; } - public int NumberOfFormattedDocuments { get; } + public int NumberOfFormattedDocuments { get; } - public int NumberOfAddedFileBanners { get; } + public int NumberOfAddedFileBanners { get; } + } } } diff --git a/src/Workspaces.Core/CodeFixes/CodeFixerOptions.cs b/src/Workspaces.Core/CodeFixes/CodeFixerOptions.cs index 2db8caee27..400c2badea 100644 --- a/src/Workspaces.Core/CodeFixes/CodeFixerOptions.cs +++ b/src/Workspaces.Core/CodeFixes/CodeFixerOptions.cs @@ -8,114 +8,115 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; -namespace Roslynator.CodeFixes; - -internal class CodeFixerOptions : CodeAnalysisOptions +namespace Roslynator.CodeFixes { - private ImmutableArray _fileBannerLines; - - public static CodeFixerOptions Default { get; } = new(); - - public CodeFixerOptions( - DiagnosticSeverity severityLevel = DiagnosticSeverity.Info, - bool ignoreCompilerErrors = false, - bool ignoreAnalyzerReferences = false, - bool concurrentAnalysis = true, - IEnumerable supportedDiagnosticIds = null, - IEnumerable ignoredDiagnosticIds = null, - IEnumerable ignoredCompilerDiagnosticIds = null, - IEnumerable diagnosticIdsFixableOneByOne = null, - IEnumerable> diagnosticFixMap = null, - IEnumerable> diagnosticFixerMap = null, - FixAllScope fixAllScope = FixAllScope.Project, - string fileBanner = null, - int maxIterations = -1, - int batchSize = -1, - bool format = false) : base( - severityLevel: severityLevel, - ignoreAnalyzerReferences: ignoreAnalyzerReferences, - concurrentAnalysis: concurrentAnalysis, - supportedDiagnosticIds: supportedDiagnosticIds, - ignoredDiagnosticIds: ignoredDiagnosticIds) + internal class CodeFixerOptions : CodeAnalysisOptions { - IgnoreCompilerErrors = ignoreCompilerErrors; - IgnoredCompilerDiagnosticIds = ignoredCompilerDiagnosticIds?.ToImmutableHashSet() ?? ImmutableHashSet.Empty; - DiagnosticIdsFixableOneByOne = diagnosticIdsFixableOneByOne?.ToImmutableHashSet() ?? ImmutableHashSet.Empty; - - if (diagnosticFixMap != null) - { - DiagnosticFixMap = diagnosticFixMap - .GroupBy(kvp => kvp.Key) - .ToImmutableDictionary(g => g.Key, g => g.Select(kvp => kvp.Value).ToImmutableArray()); - } - else + private ImmutableArray _fileBannerLines; + + public static CodeFixerOptions Default { get; } = new(); + + public CodeFixerOptions( + DiagnosticSeverity severityLevel = DiagnosticSeverity.Info, + bool ignoreCompilerErrors = false, + bool ignoreAnalyzerReferences = false, + bool concurrentAnalysis = true, + IEnumerable supportedDiagnosticIds = null, + IEnumerable ignoredDiagnosticIds = null, + IEnumerable ignoredCompilerDiagnosticIds = null, + IEnumerable diagnosticIdsFixableOneByOne = null, + IEnumerable> diagnosticFixMap = null, + IEnumerable> diagnosticFixerMap = null, + FixAllScope fixAllScope = FixAllScope.Project, + string fileBanner = null, + int maxIterations = -1, + int batchSize = -1, + bool format = false) : base( + severityLevel: severityLevel, + ignoreAnalyzerReferences: ignoreAnalyzerReferences, + concurrentAnalysis: concurrentAnalysis, + supportedDiagnosticIds: supportedDiagnosticIds, + ignoredDiagnosticIds: ignoredDiagnosticIds) { - DiagnosticFixMap = ImmutableDictionary>.Empty; - } + IgnoreCompilerErrors = ignoreCompilerErrors; + IgnoredCompilerDiagnosticIds = ignoredCompilerDiagnosticIds?.ToImmutableHashSet() ?? ImmutableHashSet.Empty; + DiagnosticIdsFixableOneByOne = diagnosticIdsFixableOneByOne?.ToImmutableHashSet() ?? ImmutableHashSet.Empty; - DiagnosticFixerMap = diagnosticFixerMap?.ToImmutableDictionary() ?? ImmutableDictionary.Empty; + if (diagnosticFixMap is not null) + { + DiagnosticFixMap = diagnosticFixMap + .GroupBy(kvp => kvp.Key) + .ToImmutableDictionary(g => g.Key, g => g.Select(kvp => kvp.Value).ToImmutableArray()); + } + else + { + DiagnosticFixMap = ImmutableDictionary>.Empty; + } - if (FixAllScope != FixAllScope.Document - && FixAllScope != FixAllScope.Project) - { - throw new ArgumentException("", nameof(fixAllScope)); - } + DiagnosticFixerMap = diagnosticFixerMap?.ToImmutableDictionary() ?? ImmutableDictionary.Empty; - FixAllScope = fixAllScope; - FileBanner = fileBanner; - MaxIterations = maxIterations; - BatchSize = batchSize; - Format = format; - } + if (FixAllScope != FixAllScope.Document + && FixAllScope != FixAllScope.Project) + { + throw new ArgumentException("", nameof(fixAllScope)); + } - public bool IgnoreCompilerErrors { get; } + FixAllScope = fixAllScope; + FileBanner = fileBanner; + MaxIterations = maxIterations; + BatchSize = batchSize; + Format = format; + } - public ImmutableHashSet IgnoredCompilerDiagnosticIds { get; } + public bool IgnoreCompilerErrors { get; } - public string FileBanner { get; } + public ImmutableHashSet IgnoredCompilerDiagnosticIds { get; } - public ImmutableArray FileBannerLines - { - get + public string FileBanner { get; } + + public ImmutableArray FileBannerLines { - if (_fileBannerLines.IsDefault) + get { - if (!string.IsNullOrEmpty(FileBanner)) + if (_fileBannerLines.IsDefault) { - ImmutableArray.Builder lines = ImmutableArray.CreateBuilder(); - - using (var sr = new StringReader(FileBanner)) + if (!string.IsNullOrEmpty(FileBanner)) { - string line = null; - while ((line = sr.ReadLine()) != null) + ImmutableArray.Builder lines = ImmutableArray.CreateBuilder(); + + using (var sr = new StringReader(FileBanner)) { - lines.Add(line); + string line = null; + while ((line = sr.ReadLine()) is not null) + { + lines.Add(line); + } } - } - _fileBannerLines = lines.ToImmutableArray(); - } - else - { - _fileBannerLines = ImmutableArray.Empty; + _fileBannerLines = lines.ToImmutableArray(); + } + else + { + _fileBannerLines = ImmutableArray.Empty; + } } - } - return _fileBannerLines; + return _fileBannerLines; + } } - } - public int MaxIterations { get; } + public int MaxIterations { get; } - public int BatchSize { get; } + public int BatchSize { get; } - public bool Format { get; } + public bool Format { get; } - public ImmutableHashSet DiagnosticIdsFixableOneByOne { get; } + public ImmutableHashSet DiagnosticIdsFixableOneByOne { get; } - public ImmutableDictionary> DiagnosticFixMap { get; } + public ImmutableDictionary> DiagnosticFixMap { get; } - public ImmutableDictionary DiagnosticFixerMap { get; } + public ImmutableDictionary DiagnosticFixerMap { get; } - public FixAllScope FixAllScope { get; } + public FixAllScope FixAllScope { get; } + } } diff --git a/src/Workspaces.Core/CodeFixes/DiagnosticDescriptorFixComparer.cs b/src/Workspaces.Core/CodeFixes/DiagnosticDescriptorFixComparer.cs index f1eeee20bd..dd3a984320 100644 --- a/src/Workspaces.Core/CodeFixes/DiagnosticDescriptorFixComparer.cs +++ b/src/Workspaces.Core/CodeFixes/DiagnosticDescriptorFixComparer.cs @@ -6,48 +6,49 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; -namespace Roslynator.CodeFixes; - -internal class DiagnosticDescriptorFixComparer : IComparer +namespace Roslynator.CodeFixes { - public DiagnosticDescriptorFixComparer( - Dictionary diagnosticCountByDescriptor, - Dictionary> fixersById) + internal class DiagnosticDescriptorFixComparer : IComparer { - DiagnosticCountByDescriptor = diagnosticCountByDescriptor; - FixersById = fixersById; - } + public DiagnosticDescriptorFixComparer( + Dictionary diagnosticCountByDescriptor, + Dictionary> fixersById) + { + DiagnosticCountByDescriptor = diagnosticCountByDescriptor; + FixersById = fixersById; + } - private Dictionary DiagnosticCountByDescriptor { get; } + private Dictionary DiagnosticCountByDescriptor { get; } - private Dictionary> FixersById { get; } + private Dictionary> FixersById { get; } - public int Compare(DiagnosticDescriptor x, DiagnosticDescriptor y) - { - if (object.ReferenceEquals(x, y)) - return 0; + public int Compare(DiagnosticDescriptor x, DiagnosticDescriptor y) + { + if (object.ReferenceEquals(x, y)) + return 0; - if (x == null) - return -1; + if (x is null) + return -1; - if (y == null) - return 1; + if (y is null) + return 1; - if (HasFixAll(x)) - { - if (!HasFixAll(y)) - return -1; + if (HasFixAll(x)) + { + if (!HasFixAll(y)) + return -1; + } + else if (HasFixAll(y)) + { + return 1; + } + + return DiagnosticCountByDescriptor[y].CompareTo(DiagnosticCountByDescriptor[x]); } - else if (HasFixAll(y)) + + private bool HasFixAll(DiagnosticDescriptor descriptor) { - return 1; + return FixersById[descriptor.Id].Any(f => f.HasFixAllProvider(FixAllScope.Project)); } - - return DiagnosticCountByDescriptor[y].CompareTo(DiagnosticCountByDescriptor[x]); - } - - private bool HasFixAll(DiagnosticDescriptor descriptor) - { - return FixersById[descriptor.Id].Any(f => f.HasFixAllProvider(FixAllScope.Project)); } } diff --git a/src/Workspaces.Core/CodeFixes/DiagnosticFixProvider.cs b/src/Workspaces.Core/CodeFixes/DiagnosticFixProvider.cs index 03ac3ca938..6188bd4a6d 100644 --- a/src/Workspaces.Core/CodeFixes/DiagnosticFixProvider.cs +++ b/src/Workspaces.Core/CodeFixes/DiagnosticFixProvider.cs @@ -13,281 +13,282 @@ using Microsoft.CodeAnalysis.CodeFixes; using static Roslynator.Logger; -namespace Roslynator.CodeFixes; - -internal static class DiagnosticFixProvider +namespace Roslynator.CodeFixes { - public static async Task GetFixAsync( - ImmutableArray diagnostics, - DiagnosticDescriptor descriptor, - ImmutableArray fixers, - Project project, - CodeFixerOptions options, - IFormatProvider formatProvider = null, - CancellationToken cancellationToken = default) + internal static class DiagnosticFixProvider { - CodeFixProvider fixer = null; - CodeAction fix = null; - Document document = null; - - for (int i = 0; i < fixers.Length; i++) + public static async Task GetFixAsync( + ImmutableArray diagnostics, + DiagnosticDescriptor descriptor, + ImmutableArray fixers, + Project project, + CodeFixerOptions options, + IFormatProvider formatProvider = null, + CancellationToken cancellationToken = default) { - cancellationToken.ThrowIfCancellationRequested(); - - (CodeAction fixCandidate, Document documentCandidate) = await GetFixAsync( - diagnostics, - descriptor, - fixers[i], - project, - options, - formatProvider, - cancellationToken) - .ConfigureAwait(false); - - if (fixCandidate != null) + CodeFixProvider fixer = null; + CodeAction fix = null; + Document document = null; + + for (int i = 0; i < fixers.Length; i++) { - if (fix == null) + cancellationToken.ThrowIfCancellationRequested(); + + (CodeAction fixCandidate, Document documentCandidate) = await GetFixAsync( + diagnostics, + descriptor, + fixers[i], + project, + options, + formatProvider, + cancellationToken) + .ConfigureAwait(false); + + if (fixCandidate is not null) { - if (options.DiagnosticFixerMap.IsEmpty - || !options.DiagnosticFixerMap.TryGetValue(descriptor.Id, out string fullTypeName) - || string.Equals(fixers[i].GetType().FullName, fullTypeName, StringComparison.Ordinal)) + if (fix is null) { - fix = fixCandidate; - fixer = fixers[i]; - document = documentCandidate; + if (options.DiagnosticFixerMap.IsEmpty + || !options.DiagnosticFixerMap.TryGetValue(descriptor.Id, out string fullTypeName) + || string.Equals(fixers[i].GetType().FullName, fullTypeName, StringComparison.Ordinal)) + { + fix = fixCandidate; + fixer = fixers[i]; + document = documentCandidate; + } + } + else if (options.DiagnosticFixerMap.IsEmpty + || !options.DiagnosticFixerMap.ContainsKey(descriptor.Id)) + { + LogHelpers.WriteMultipleFixersSummary(descriptor.Id, fixer, fixers[i]); + return new DiagnosticFix(null, null, fixer, fixers[i]); } - } - else if (options.DiagnosticFixerMap.IsEmpty - || !options.DiagnosticFixerMap.ContainsKey(descriptor.Id)) - { - LogHelpers.WriteMultipleFixersSummary(descriptor.Id, fixer, fixers[i]); - return new DiagnosticFix(null, null, fixer, fixers[i]); } } + + return new DiagnosticFix(fix, document, fixer, null); } - return new DiagnosticFix(fix, document, fixer, null); - } + private static async Task<(CodeAction, Document)> GetFixAsync( + ImmutableArray diagnostics, + DiagnosticDescriptor descriptor, + CodeFixProvider fixer, + Project project, + CodeFixerOptions options, + IFormatProvider formatProvider = null, + CancellationToken cancellationToken = default) + { + if (diagnostics.Length == 1) + return await GetFixAsync(diagnostics[0], fixer, project, options, formatProvider, cancellationToken).ConfigureAwait(false); - private static async Task<(CodeAction, Document)> GetFixAsync( - ImmutableArray diagnostics, - DiagnosticDescriptor descriptor, - CodeFixProvider fixer, - Project project, - CodeFixerOptions options, - IFormatProvider formatProvider = null, - CancellationToken cancellationToken = default) - { - if (diagnostics.Length == 1) - return await GetFixAsync(diagnostics[0], fixer, project, options, formatProvider, cancellationToken).ConfigureAwait(false); + FixAllProvider fixAllProvider = fixer.GetFixAllProvider(); - FixAllProvider fixAllProvider = fixer.GetFixAllProvider(); + if (fixAllProvider is null) + { + if (options.DiagnosticIdsFixableOneByOne.Contains(descriptor.Id)) + return await GetFixAsync(diagnostics[0], fixer, project, options, formatProvider, cancellationToken).ConfigureAwait(false); - if (fixAllProvider == null) - { - if (options.DiagnosticIdsFixableOneByOne.Contains(descriptor.Id)) - return await GetFixAsync(diagnostics[0], fixer, project, options, formatProvider, cancellationToken).ConfigureAwait(false); + WriteLine($" Diagnostic '{descriptor.Id}' cannot be fixed with '{fixer.GetType().FullName}' because it does not have FixAllProvider and '{descriptor.Id}' is not allowed to be fixed one by one.", ConsoleColors.Yellow, Verbosity.Diagnostic); + return default; + } - WriteLine($" Diagnostic '{descriptor.Id}' cannot be fixed with '{fixer.GetType().FullName}' because it does not have FixAllProvider and '{descriptor.Id}' is not allowed to be fixed one by one.", ConsoleColors.Yellow, Verbosity.Diagnostic); - return default; - } + if (!fixAllProvider.GetSupportedFixAllDiagnosticIds(fixer).Any(f => f == descriptor.Id)) + { + WriteLine($" '{fixAllProvider.GetType().FullName}' does not support diagnostic '{descriptor.Id}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + return default; + } - if (!fixAllProvider.GetSupportedFixAllDiagnosticIds(fixer).Any(f => f == descriptor.Id)) - { - WriteLine($" '{fixAllProvider.GetType().FullName}' does not support diagnostic '{descriptor.Id}'", ConsoleColors.Yellow, Verbosity.Diagnostic); - return default; - } + if (!fixAllProvider.GetSupportedFixAllScopes().Any(f => f == options.FixAllScope)) + { + WriteLine($" '{fixAllProvider.GetType().FullName}' does not support scope '{options.FixAllScope}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + return default; + } - if (!fixAllProvider.GetSupportedFixAllScopes().Any(f => f == options.FixAllScope)) - { - WriteLine($" '{fixAllProvider.GetType().FullName}' does not support scope '{options.FixAllScope}'", ConsoleColors.Yellow, Verbosity.Diagnostic); - return default; - } + var multipleFixesInfos = new HashSet(); - var multipleFixesInfos = new HashSet(); + options.DiagnosticFixMap.TryGetValue(descriptor.Id, out ImmutableArray equivalenceKeys); - options.DiagnosticFixMap.TryGetValue(descriptor.Id, out ImmutableArray equivalenceKeys); + foreach (Diagnostic diagnostic in diagnostics) + { + cancellationToken.ThrowIfCancellationRequested(); - foreach (Diagnostic diagnostic in diagnostics) - { - cancellationToken.ThrowIfCancellationRequested(); + if (!diagnostic.Location.IsInSource) + continue; - if (!diagnostic.Location.IsInSource) - continue; + Document document = project.GetDocument(diagnostic.Location.SourceTree); - Document document = project.GetDocument(diagnostic.Location.SourceTree); + if (document is null) + continue; - if (document == null) - continue; + CodeAction fix = await GetFixAsync(diagnostic, fixer, document, multipleFixesInfos, equivalenceKeys, cancellationToken).ConfigureAwait(false); - CodeAction fix = await GetFixAsync(diagnostic, fixer, document, multipleFixesInfos, equivalenceKeys, cancellationToken).ConfigureAwait(false); + if (fix is null) + continue; - if (fix == null) - continue; + var fixAllContext = new FixAllContext( + document, + fixer, + options.FixAllScope, + fix.EquivalenceKey, + new string[] { descriptor.Id }, + new FixAllDiagnosticProvider(diagnostics), + cancellationToken); - var fixAllContext = new FixAllContext( - document, - fixer, - options.FixAllScope, - fix.EquivalenceKey, - new string[] { descriptor.Id }, - new FixAllDiagnosticProvider(diagnostics), - cancellationToken); + CodeAction fixAll = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(false); - CodeAction fixAll = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(false); + if (fixAll is not null) + { + WriteLine($" CodeFixProvider: '{fixer.GetType().FullName}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); - if (fixAll != null) - { - WriteLine($" CodeFixProvider: '{fixer.GetType().FullName}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); + if (!string.IsNullOrEmpty(fix.EquivalenceKey)) + WriteLine($" EquivalenceKey: '{fix.EquivalenceKey}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); - if (!string.IsNullOrEmpty(fix.EquivalenceKey)) - WriteLine($" EquivalenceKey: '{fix.EquivalenceKey}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); + WriteLine($" FixAllProvider: '{fixAllProvider.GetType().FullName}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); - WriteLine($" FixAllProvider: '{fixAllProvider.GetType().FullName}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); + return (fixAll, document); + } - return (fixAll, document); + WriteLine($" Fixer '{fixer.GetType().FullName}' registered no action for diagnostic '{descriptor.Id}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); + LogHelpers.WriteDiagnostic(diagnostic, baseDirectoryPath: Path.GetDirectoryName(project.FilePath), formatProvider: formatProvider, indentation: " ", verbosity: Verbosity.Diagnostic); } - WriteLine($" Fixer '{fixer.GetType().FullName}' registered no action for diagnostic '{descriptor.Id}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); - LogHelpers.WriteDiagnostic(diagnostic, baseDirectoryPath: Path.GetDirectoryName(project.FilePath), formatProvider: formatProvider, indentation: " ", verbosity: Verbosity.Diagnostic); + return default; } - return default; - } + private static async Task<(CodeAction, Document)> GetFixAsync( + Diagnostic diagnostic, + CodeFixProvider fixer, + Project project, + CodeFixerOptions options, + IFormatProvider formatProvider, + CancellationToken cancellationToken) + { + if (!diagnostic.Location.IsInSource) + return default; - private static async Task<(CodeAction, Document)> GetFixAsync( - Diagnostic diagnostic, - CodeFixProvider fixer, - Project project, - CodeFixerOptions options, - IFormatProvider formatProvider, - CancellationToken cancellationToken) - { - if (!diagnostic.Location.IsInSource) - return default; + Document document = project.GetDocument(diagnostic.Location.SourceTree); - Document document = project.GetDocument(diagnostic.Location.SourceTree); + Debug.Assert(document is not null, ""); - Debug.Assert(document != null, ""); + if (document is null) + return default; - if (document == null) - return default; + options.DiagnosticFixMap.TryGetValue(diagnostic.Id, out ImmutableArray equivalenceKeys); - options.DiagnosticFixMap.TryGetValue(diagnostic.Id, out ImmutableArray equivalenceKeys); + CodeAction action = await GetFixAsync(diagnostic, fixer, document, multipleFixesInfos: default, equivalenceKeys, cancellationToken).ConfigureAwait(false); - CodeAction action = await GetFixAsync(diagnostic, fixer, document, multipleFixesInfos: default, equivalenceKeys, cancellationToken).ConfigureAwait(false); + if (action is null) + { + WriteLine($" Fixer '{fixer.GetType().FullName}' registered no action for diagnostic '{diagnostic.Id}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); + LogHelpers.WriteDiagnostic(diagnostic, baseDirectoryPath: Path.GetDirectoryName(project.FilePath), formatProvider: formatProvider, indentation: " ", verbosity: Verbosity.Diagnostic); + } - if (action == null) - { - WriteLine($" Fixer '{fixer.GetType().FullName}' registered no action for diagnostic '{diagnostic.Id}'", ConsoleColors.DarkGray, Verbosity.Diagnostic); - LogHelpers.WriteDiagnostic(diagnostic, baseDirectoryPath: Path.GetDirectoryName(project.FilePath), formatProvider: formatProvider, indentation: " ", verbosity: Verbosity.Diagnostic); + return (action, document); } - return (action, document); - } - - private static async Task GetFixAsync( - Diagnostic diagnostic, - CodeFixProvider fixer, - Document document, - HashSet multipleFixesInfos, - ImmutableArray equivalenceKeys, - CancellationToken cancellationToken) - { - CodeAction action = null; - - var context = new CodeFixContext( - document, - diagnostic, - (a, _) => - { - if (!equivalenceKeys.IsDefaultOrEmpty - && !equivalenceKeys.Contains(a.EquivalenceKey, StringComparer.Ordinal)) - { - return; - } + private static async Task GetFixAsync( + Diagnostic diagnostic, + CodeFixProvider fixer, + Document document, + HashSet multipleFixesInfos, + ImmutableArray equivalenceKeys, + CancellationToken cancellationToken) + { + CodeAction action = null; - if (action == null) - { - action = a; - } - else + var context = new CodeFixContext( + document, + diagnostic, + (a, _) => { - var multipleFixesInfo = new MultipleFixesInfo(diagnostic.Id, fixer, action.EquivalenceKey, a.EquivalenceKey); + if (!equivalenceKeys.IsDefaultOrEmpty + && !equivalenceKeys.Contains(a.EquivalenceKey, StringComparer.Ordinal)) + { + return; + } - if (multipleFixesInfos == null) - multipleFixesInfos = new HashSet(); + if (action is null) + { + action = a; + } + else + { + var multipleFixesInfo = new MultipleFixesInfo(diagnostic.Id, fixer, action.EquivalenceKey, a.EquivalenceKey); - if (multipleFixesInfos.Add(multipleFixesInfo)) - WriteMultipleActionsSummary(multipleFixesInfo); + if (multipleFixesInfos is null) + multipleFixesInfos = new HashSet(); - action = null; - } - }, - cancellationToken); + if (multipleFixesInfos.Add(multipleFixesInfo)) + WriteMultipleActionsSummary(multipleFixesInfo); - await fixer.RegisterCodeFixesAsync(context).ConfigureAwait(false); + action = null; + } + }, + cancellationToken); - return action; - } + await fixer.RegisterCodeFixesAsync(context).ConfigureAwait(false); - private static void WriteMultipleActionsSummary(in MultipleFixesInfo info) - { - WriteLine($" '{info.Fixer.GetType().FullName}' registered multiple actions to fix diagnostic '{info.DiagnosticId}'", ConsoleColors.Yellow, Verbosity.Diagnostic); - WriteLine($" EquivalenceKey 1: '{info.EquivalenceKey1}'", ConsoleColors.Yellow, Verbosity.Diagnostic); - WriteLine($" EquivalenceKey 2: '{info.EquivalenceKey2}'", ConsoleColors.Yellow, Verbosity.Diagnostic); - } + return action; + } - private readonly struct MultipleFixesInfo : IEquatable - { - public MultipleFixesInfo(string diagnosticId, CodeFixProvider fixer, string equivalenceKey1, string equivalenceKey2) + private static void WriteMultipleActionsSummary(in MultipleFixesInfo info) { - DiagnosticId = diagnosticId; - Fixer = fixer; - EquivalenceKey1 = equivalenceKey1; - EquivalenceKey2 = equivalenceKey2; + WriteLine($" '{info.Fixer.GetType().FullName}' registered multiple actions to fix diagnostic '{info.DiagnosticId}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + WriteLine($" EquivalenceKey 1: '{info.EquivalenceKey1}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + WriteLine($" EquivalenceKey 2: '{info.EquivalenceKey2}'", ConsoleColors.Yellow, Verbosity.Diagnostic); } - public string DiagnosticId { get; } + private readonly struct MultipleFixesInfo : IEquatable + { + public MultipleFixesInfo(string diagnosticId, CodeFixProvider fixer, string equivalenceKey1, string equivalenceKey2) + { + DiagnosticId = diagnosticId; + Fixer = fixer; + EquivalenceKey1 = equivalenceKey1; + EquivalenceKey2 = equivalenceKey2; + } - public CodeFixProvider Fixer { get; } + public string DiagnosticId { get; } - public string EquivalenceKey1 { get; } + public CodeFixProvider Fixer { get; } - public string EquivalenceKey2 { get; } + public string EquivalenceKey1 { get; } - public override bool Equals(object obj) - { - return obj is MultipleFixesInfo other && Equals(other); - } + public string EquivalenceKey2 { get; } - public bool Equals(MultipleFixesInfo other) - { - return DiagnosticId == other.DiagnosticId - && Fixer == other.Fixer - && EquivalenceKey1 == other.EquivalenceKey1 - && EquivalenceKey2 == other.EquivalenceKey2; - } + public override bool Equals(object obj) + { + return obj is MultipleFixesInfo other && Equals(other); + } - public override int GetHashCode() - { - return Hash.Combine( - DiagnosticId, - Hash.Combine( - Fixer, + public bool Equals(MultipleFixesInfo other) + { + return DiagnosticId == other.DiagnosticId + && Fixer == other.Fixer + && EquivalenceKey1 == other.EquivalenceKey1 + && EquivalenceKey2 == other.EquivalenceKey2; + } + + public override int GetHashCode() + { + return Hash.Combine( + DiagnosticId, Hash.Combine( - EquivalenceKey1, - Hash.Create(EquivalenceKey2)))); - } + Fixer, + Hash.Combine( + EquivalenceKey1, + Hash.Create(EquivalenceKey2)))); + } - public static bool operator ==(in MultipleFixesInfo info1, in MultipleFixesInfo info2) - { - return info1.Equals(info2); - } + public static bool operator ==(in MultipleFixesInfo info1, in MultipleFixesInfo info2) + { + return info1.Equals(info2); + } - public static bool operator !=(in MultipleFixesInfo info1, in MultipleFixesInfo info2) - { - return !(info1 == info2); + public static bool operator !=(in MultipleFixesInfo info1, in MultipleFixesInfo info2) + { + return !(info1 == info2); + } } } } diff --git a/src/Workspaces.Core/Comparers/MemberSymbolDefinitionComparer.cs b/src/Workspaces.Core/Comparers/MemberSymbolDefinitionComparer.cs index 23e63301fd..dc93278587 100644 --- a/src/Workspaces.Core/Comparers/MemberSymbolDefinitionComparer.cs +++ b/src/Workspaces.Core/Comparers/MemberSymbolDefinitionComparer.cs @@ -5,196 +5,197 @@ using System.Diagnostics; using Microsoft.CodeAnalysis; -namespace Roslynator; - -internal sealed class MemberSymbolDefinitionComparer : IComparer +namespace Roslynator { - internal MemberSymbolDefinitionComparer(SymbolDefinitionComparer symbolComparer) - { - SymbolComparer = symbolComparer; - } - - public SymbolDefinitionComparer SymbolComparer { get; } - - public int Compare(ISymbol x, ISymbol y) + internal sealed class MemberSymbolDefinitionComparer : IComparer { - Debug.Assert(x.IsKind(SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property), x.Kind.ToString()); - Debug.Assert(y.IsKind(SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property), y.Kind.ToString()); - - if (object.ReferenceEquals(x, y)) - return 0; - - if (x == null) - return -1; - - if (y == null) - return 1; + internal MemberSymbolDefinitionComparer(SymbolDefinitionComparer symbolComparer) + { + SymbolComparer = symbolComparer; + } - int diff; + public SymbolDefinitionComparer SymbolComparer { get; } - if ((SymbolComparer.Options & SymbolDefinitionSortOptions.OmitContainingNamespace) == 0) + public int Compare(ISymbol x, ISymbol y) { - diff = CompareContainingNamespace(x, y); + Debug.Assert(x.IsKind(SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property), x.Kind.ToString()); + Debug.Assert(y.IsKind(SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property), y.Kind.ToString()); - if (diff != 0) - return diff; - } + if (object.ReferenceEquals(x, y)) + return 0; - if ((SymbolComparer.Options & SymbolDefinitionSortOptions.OmitContainingType) == 0) - { - diff = SymbolComparer.TypeComparer.Compare(x.ContainingType, y.ContainingType); + if (x is null) + return -1; - if (diff != 0) - return diff; - } + if (y is null) + return 1; - MemberDeclarationKind kind1 = x.GetMemberDeclarationKind(); - MemberDeclarationKind kind2 = y.GetMemberDeclarationKind(); + int diff; - diff = ((int)kind1).CompareTo((int)kind2); + if ((SymbolComparer.Options & SymbolDefinitionSortOptions.OmitContainingNamespace) == 0) + { + diff = CompareContainingNamespace(x, y); - if (diff != 0) - return diff; + if (diff != 0) + return diff; + } - switch (kind1) - { - case MemberDeclarationKind.Constructor: - case MemberDeclarationKind.Method: - { - return CompareMethods((IMethodSymbol)x, (IMethodSymbol)y); - } - case MemberDeclarationKind.Indexer: - case MemberDeclarationKind.Property: - { - return CompareProperties((IPropertySymbol)x, (IPropertySymbol)y); - } - case MemberDeclarationKind.ExplicitlyImplementedEvent: - { - var e1 = (IEventSymbol)x; - var e2 = (IEventSymbol)y; - - diff = CompareExplicitImplementations(e1.ExplicitInterfaceImplementations, e2.ExplicitInterfaceImplementations); - - if (diff != 0) - return diff; - - break; - } - case MemberDeclarationKind.ExplicitlyImplementedMethod: - { - var m1 = (IMethodSymbol)x; - var m2 = (IMethodSymbol)y; - - diff = CompareExplicitImplementations(m1.ExplicitInterfaceImplementations, m2.ExplicitInterfaceImplementations); - - if (diff != 0) - return diff; - - return CompareMethods(m1, m2); - } - case MemberDeclarationKind.ExplicitlyImplementedProperty: - { - var p1 = (IPropertySymbol)x; - var p2 = (IPropertySymbol)y; - - diff = CompareExplicitImplementations(p1.ExplicitInterfaceImplementations, p2.ExplicitInterfaceImplementations); - - if (diff != 0) - return diff; - - return CompareProperties(p1, p2); - } - } + if ((SymbolComparer.Options & SymbolDefinitionSortOptions.OmitContainingType) == 0) + { + diff = SymbolComparer.TypeComparer.Compare(x.ContainingType, y.ContainingType); - diff = SymbolDefinitionComparer.CompareName(x, y); + if (diff != 0) + return diff; + } - if (diff != 0) - return diff; + MemberDeclarationKind kind1 = x.GetMemberDeclarationKind(); + MemberDeclarationKind kind2 = y.GetMemberDeclarationKind(); - return CompareContainingNamespace(x, y); - } + diff = ((int)kind1).CompareTo((int)kind2); - private int CompareMethods(IMethodSymbol methodSymbol1, IMethodSymbol methodSymbol2) - { - int diff = SymbolDefinitionComparer.CompareName(methodSymbol1, methodSymbol2); + if (diff != 0) + return diff; - if (diff != 0) - return diff; + switch (kind1) + { + case MemberDeclarationKind.Constructor: + case MemberDeclarationKind.Method: + { + return CompareMethods((IMethodSymbol)x, (IMethodSymbol)y); + } + case MemberDeclarationKind.Indexer: + case MemberDeclarationKind.Property: + { + return CompareProperties((IPropertySymbol)x, (IPropertySymbol)y); + } + case MemberDeclarationKind.ExplicitlyImplementedEvent: + { + var e1 = (IEventSymbol)x; + var e2 = (IEventSymbol)y; + + diff = CompareExplicitImplementations(e1.ExplicitInterfaceImplementations, e2.ExplicitInterfaceImplementations); + + if (diff != 0) + return diff; + + break; + } + case MemberDeclarationKind.ExplicitlyImplementedMethod: + { + var m1 = (IMethodSymbol)x; + var m2 = (IMethodSymbol)y; + + diff = CompareExplicitImplementations(m1.ExplicitInterfaceImplementations, m2.ExplicitInterfaceImplementations); + + if (diff != 0) + return diff; + + return CompareMethods(m1, m2); + } + case MemberDeclarationKind.ExplicitlyImplementedProperty: + { + var p1 = (IPropertySymbol)x; + var p2 = (IPropertySymbol)y; + + diff = CompareExplicitImplementations(p1.ExplicitInterfaceImplementations, p2.ExplicitInterfaceImplementations); + + if (diff != 0) + return diff; + + return CompareProperties(p1, p2); + } + } + + diff = SymbolDefinitionComparer.CompareName(x, y); - diff = methodSymbol1.TypeParameters.Length.CompareTo(methodSymbol2.TypeParameters.Length); + if (diff != 0) + return diff; - if (diff != 0) - return diff; + return CompareContainingNamespace(x, y); + } - diff = CompareParameters(methodSymbol1.Parameters, methodSymbol2.Parameters); + private int CompareMethods(IMethodSymbol methodSymbol1, IMethodSymbol methodSymbol2) + { + int diff = SymbolDefinitionComparer.CompareName(methodSymbol1, methodSymbol2); - if (diff != 0) - return diff; + if (diff != 0) + return diff; - return CompareContainingNamespace(methodSymbol1, methodSymbol2); - } + diff = methodSymbol1.TypeParameters.Length.CompareTo(methodSymbol2.TypeParameters.Length); - private int CompareProperties(IPropertySymbol propertySymbol1, IPropertySymbol propertySymbol2) - { - int diff = SymbolDefinitionComparer.CompareName(propertySymbol1, propertySymbol2); + if (diff != 0) + return diff; - if (diff != 0) - return diff; + diff = CompareParameters(methodSymbol1.Parameters, methodSymbol2.Parameters); - diff = CompareParameters(propertySymbol1.Parameters, propertySymbol2.Parameters); + if (diff != 0) + return diff; - if (diff != 0) - return diff; + return CompareContainingNamespace(methodSymbol1, methodSymbol2); + } - return CompareContainingNamespace(propertySymbol1, propertySymbol2); - } + private int CompareProperties(IPropertySymbol propertySymbol1, IPropertySymbol propertySymbol2) + { + int diff = SymbolDefinitionComparer.CompareName(propertySymbol1, propertySymbol2); - private int CompareExplicitImplementations(ImmutableArray x, ImmutableArray y) where TSymbol : ISymbol - { - return SymbolComparer.TypeComparer.Compare(x[0].ContainingType, y[0].ContainingType); - } + if (diff != 0) + return diff; - private static int CompareParameters(ImmutableArray parameters1, ImmutableArray parameters2) - { - int length = parameters1.Length; + diff = CompareParameters(propertySymbol1.Parameters, propertySymbol2.Parameters); + + if (diff != 0) + return diff; - int diff = length.CompareTo(parameters2.Length); + return CompareContainingNamespace(propertySymbol1, propertySymbol2); + } - if (diff != 0) - return diff; + private int CompareExplicitImplementations(ImmutableArray x, ImmutableArray y) where TSymbol : ISymbol + { + return SymbolComparer.TypeComparer.Compare(x[0].ContainingType, y[0].ContainingType); + } - for (int i = 0; i < length; i++) + private static int CompareParameters(ImmutableArray parameters1, ImmutableArray parameters2) { - diff = CompareParameter(parameters1[i], parameters2[i]); + int length = parameters1.Length; + + int diff = length.CompareTo(parameters2.Length); if (diff != 0) return diff; - } - return 0; - } + for (int i = 0; i < length; i++) + { + diff = CompareParameter(parameters1[i], parameters2[i]); + + if (diff != 0) + return diff; + } - private static int CompareParameter(IParameterSymbol x, IParameterSymbol y) - { - if (object.ReferenceEquals(x, y)) return 0; + } + + private static int CompareParameter(IParameterSymbol x, IParameterSymbol y) + { + if (object.ReferenceEquals(x, y)) + return 0; - if (x == null) - return -1; + if (x is null) + return -1; - if (y == null) - return 1; + if (y is null) + return 1; - int diff = ((int)x.RefKind).CompareTo((int)y.RefKind); + int diff = ((int)x.RefKind).CompareTo((int)y.RefKind); - if (diff != 0) - return diff; + if (diff != 0) + return diff; - return SymbolDefinitionComparer.CompareName(x, y); - } + return SymbolDefinitionComparer.CompareName(x, y); + } - private int CompareContainingNamespace(ISymbol x, ISymbol y) - { - return SymbolComparer.CompareContainingNamespace(x, y); + private int CompareContainingNamespace(ISymbol x, ISymbol y) + { + return SymbolComparer.CompareContainingNamespace(x, y); + } } } diff --git a/src/Workspaces.Core/Comparers/NamedTypeSymbolDefinitionComparer.cs b/src/Workspaces.Core/Comparers/NamedTypeSymbolDefinitionComparer.cs index 735098d576..c888077184 100644 --- a/src/Workspaces.Core/Comparers/NamedTypeSymbolDefinitionComparer.cs +++ b/src/Workspaces.Core/Comparers/NamedTypeSymbolDefinitionComparer.cs @@ -4,129 +4,130 @@ using System.Diagnostics; using Microsoft.CodeAnalysis; -namespace Roslynator; - -internal sealed class NamedTypeSymbolDefinitionComparer : IComparer +namespace Roslynator { - internal NamedTypeSymbolDefinitionComparer(SymbolDefinitionComparer symbolComparer) + internal sealed class NamedTypeSymbolDefinitionComparer : IComparer { - SymbolComparer = symbolComparer; - } + internal NamedTypeSymbolDefinitionComparer(SymbolDefinitionComparer symbolComparer) + { + SymbolComparer = symbolComparer; + } - public SymbolDefinitionComparer SymbolComparer { get; } + public SymbolDefinitionComparer SymbolComparer { get; } - public int Compare(INamedTypeSymbol x, INamedTypeSymbol y) - { - if (object.ReferenceEquals(x, y)) - return 0; + public int Compare(INamedTypeSymbol x, INamedTypeSymbol y) + { + if (object.ReferenceEquals(x, y)) + return 0; - if (x == null) - return -1; + if (x is null) + return -1; - if (y == null) - return 1; + if (y is null) + return 1; - int diff; + int diff; - if ((SymbolComparer.Options & SymbolDefinitionSortOptions.OmitContainingNamespace) == 0) - { - diff = SymbolComparer.CompareContainingNamespace(x, y); + if ((SymbolComparer.Options & SymbolDefinitionSortOptions.OmitContainingNamespace) == 0) + { + diff = SymbolComparer.CompareContainingNamespace(x, y); - if (diff != 0) - return diff; - } + if (diff != 0) + return diff; + } - diff = GetRank(x).CompareTo(GetRank(y)); + diff = GetRank(x).CompareTo(GetRank(y)); - if (diff != 0) - return diff; + if (diff != 0) + return diff; - int count1 = CountContainingTypes(x); - int count2 = CountContainingTypes(y); + int count1 = CountContainingTypes(x); + int count2 = CountContainingTypes(y); - while (true) - { - INamedTypeSymbol containingType1 = GetContainingType(x, count1); - INamedTypeSymbol containingType2 = GetContainingType(y, count2); + while (true) + { + INamedTypeSymbol containingType1 = GetContainingType(x, count1); + INamedTypeSymbol containingType2 = GetContainingType(y, count2); - diff = SymbolDefinitionComparer.CompareName(containingType1, containingType2); + diff = SymbolDefinitionComparer.CompareName(containingType1, containingType2); - if (diff != 0) - return diff; + if (diff != 0) + return diff; - diff = containingType1.TypeParameters.Length.CompareTo(containingType2.TypeParameters.Length); + diff = containingType1.TypeParameters.Length.CompareTo(containingType2.TypeParameters.Length); - if (diff != 0) - return diff; + if (diff != 0) + return diff; - if (count1 == 0) - { - if (count2 == 0) + if (count1 == 0) { - return SymbolComparer.CompareContainingNamespace(x, y); + if (count2 == 0) + { + return SymbolComparer.CompareContainingNamespace(x, y); + } + else + { + return -1; + } } - else - { - return -1; - } - } - if (count2 == 0) - return 1; - - count1--; - count2--; - } + if (count2 == 0) + return 1; - static int CountContainingTypes(INamedTypeSymbol namedType) - { - int count = 0; + count1--; + count2--; + } - while (true) + static int CountContainingTypes(INamedTypeSymbol namedType) { - namedType = namedType.ContainingType; + int count = 0; - if (namedType == null) - break; + while (true) + { + namedType = namedType.ContainingType; - count++; - } + if (namedType is null) + break; - return count; - } + count++; + } - static INamedTypeSymbol GetContainingType(INamedTypeSymbol namedType, int count) - { - while (count > 0) - { - namedType = namedType.ContainingType; - count--; + return count; } - return namedType; - } - - static int GetRank(INamedTypeSymbol symbol) - { - switch (symbol.TypeKind) + static INamedTypeSymbol GetContainingType(INamedTypeSymbol namedType, int count) { - case TypeKind.Module: - return 1; - case TypeKind.Class: - return 2; - case TypeKind.Struct: - return 3; - case TypeKind.Interface: - return 4; - case TypeKind.Enum: - return 5; - case TypeKind.Delegate: - return 6; + while (count > 0) + { + namedType = namedType.ContainingType; + count--; + } + + return namedType; } - Debug.Fail(symbol.ToDisplayString(SymbolDisplayFormats.Test)); + static int GetRank(INamedTypeSymbol symbol) + { + switch (symbol.TypeKind) + { + case TypeKind.Module: + return 1; + case TypeKind.Class: + return 2; + case TypeKind.Struct: + return 3; + case TypeKind.Interface: + return 4; + case TypeKind.Enum: + return 5; + case TypeKind.Delegate: + return 6; + } + + Debug.Fail(symbol.ToDisplayString(SymbolDisplayFormats.Test)); - return 0; + return 0; + } } } } diff --git a/src/Workspaces.Core/Comparers/NamespaceSymbolDefinitionComparer.cs b/src/Workspaces.Core/Comparers/NamespaceSymbolDefinitionComparer.cs index 7b3168de8f..93b8174925 100644 --- a/src/Workspaces.Core/Comparers/NamespaceSymbolDefinitionComparer.cs +++ b/src/Workspaces.Core/Comparers/NamespaceSymbolDefinitionComparer.cs @@ -3,102 +3,103 @@ using System.Collections.Generic; using Microsoft.CodeAnalysis; -namespace Roslynator; - -internal sealed class NamespaceSymbolDefinitionComparer : IComparer +namespace Roslynator { - internal NamespaceSymbolDefinitionComparer(SymbolDefinitionComparer symbolComparer) - { - SymbolComparer = symbolComparer; - } - - public SymbolDefinitionComparer SymbolComparer { get; } - - public int Compare(INamespaceSymbol x, INamespaceSymbol y) + internal sealed class NamespaceSymbolDefinitionComparer : IComparer { - if (object.ReferenceEquals(x, y)) - return 0; - - if (x == null) - return -1; - - if (y == null) - return 1; - - if (x.IsGlobalNamespace) + internal NamespaceSymbolDefinitionComparer(SymbolDefinitionComparer symbolComparer) { - return (y.IsGlobalNamespace) ? 0 : -1; - } - else if (y.IsGlobalNamespace) - { - return 1; + SymbolComparer = symbolComparer; } - int count1 = CountContainingNamespaces(x); - int count2 = CountContainingNamespaces(y); + public SymbolDefinitionComparer SymbolComparer { get; } - if ((SymbolComparer.Options & SymbolDefinitionSortOptions.SystemFirst) != 0) + public int Compare(INamespaceSymbol x, INamespaceSymbol y) { - INamespaceSymbol namespaceSymbol1 = GetNamespaceSymbol(x, count1); - INamespaceSymbol namespaceSymbol2 = GetNamespaceSymbol(y, count2); + if (object.ReferenceEquals(x, y)) + return 0; + + if (x is null) + return -1; + + if (y is null) + return 1; - if (namespaceSymbol1.Name == "System") + if (x.IsGlobalNamespace) { - if (namespaceSymbol2.Name != "System") - return -1; + return (y.IsGlobalNamespace) ? 0 : -1; } - else if (namespaceSymbol2.Name == "System") + else if (y.IsGlobalNamespace) { return 1; } - } - while (true) - { - INamespaceSymbol namespaceSymbol1 = GetNamespaceSymbol(x, count1); - INamespaceSymbol namespaceSymbol2 = GetNamespaceSymbol(y, count2); + int count1 = CountContainingNamespaces(x); + int count2 = CountContainingNamespaces(y); + + if ((SymbolComparer.Options & SymbolDefinitionSortOptions.SystemFirst) != 0) + { + INamespaceSymbol namespaceSymbol1 = GetNamespaceSymbol(x, count1); + INamespaceSymbol namespaceSymbol2 = GetNamespaceSymbol(y, count2); + + if (namespaceSymbol1.Name == "System") + { + if (namespaceSymbol2.Name != "System") + return -1; + } + else if (namespaceSymbol2.Name == "System") + { + return 1; + } + } - int diff = SymbolDefinitionComparer.CompareName(namespaceSymbol1, namespaceSymbol2); + while (true) + { + INamespaceSymbol namespaceSymbol1 = GetNamespaceSymbol(x, count1); + INamespaceSymbol namespaceSymbol2 = GetNamespaceSymbol(y, count2); - if (diff != 0) - return diff; + int diff = SymbolDefinitionComparer.CompareName(namespaceSymbol1, namespaceSymbol2); - if (count1 == 0) - return (count2 == 0) ? 0 : -1; + if (diff != 0) + return diff; - if (count2 == 0) - return 1; + if (count1 == 0) + return (count2 == 0) ? 0 : -1; - count1--; - count2--; - } + if (count2 == 0) + return 1; - static int CountContainingNamespaces(INamespaceSymbol namespaceSymbol) - { - int count = 0; + count1--; + count2--; + } - while (true) + static int CountContainingNamespaces(INamespaceSymbol namespaceSymbol) { - namespaceSymbol = namespaceSymbol.ContainingNamespace; + int count = 0; - if (namespaceSymbol.IsGlobalNamespace) - break; + while (true) + { + namespaceSymbol = namespaceSymbol.ContainingNamespace; - count++; - } + if (namespaceSymbol.IsGlobalNamespace) + break; - return count; - } + count++; + } - static INamespaceSymbol GetNamespaceSymbol(INamespaceSymbol namespaceSymbol, int count) - { - while (count > 0) - { - namespaceSymbol = namespaceSymbol.ContainingNamespace; - count--; + return count; } - return namespaceSymbol; + static INamespaceSymbol GetNamespaceSymbol(INamespaceSymbol namespaceSymbol, int count) + { + while (count > 0) + { + namespaceSymbol = namespaceSymbol.ContainingNamespace; + count--; + } + + return namespaceSymbol; + } } } } diff --git a/src/Workspaces.Core/Comparers/SymbolDefinitionComparer.cs b/src/Workspaces.Core/Comparers/SymbolDefinitionComparer.cs index fb27dd7b0b..b2ae03be34 100644 --- a/src/Workspaces.Core/Comparers/SymbolDefinitionComparer.cs +++ b/src/Workspaces.Core/Comparers/SymbolDefinitionComparer.cs @@ -6,214 +6,215 @@ using System.Threading; using Microsoft.CodeAnalysis; -namespace Roslynator; - -internal abstract class SymbolDefinitionComparer : IComparer +namespace Roslynator { - internal SymbolDefinitionComparer(SymbolDefinitionSortOptions options = SymbolDefinitionSortOptions.None) + internal abstract class SymbolDefinitionComparer : IComparer { - Options = options; - } + internal SymbolDefinitionComparer(SymbolDefinitionSortOptions options = SymbolDefinitionSortOptions.None) + { + Options = options; + } - public static SymbolDefinitionComparer Default { get; } = new DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions.None); + public static SymbolDefinitionComparer Default { get; } = new DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions.None); - public static SymbolDefinitionComparer SystemFirst { get; } = new DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions.SystemFirst); + public static SymbolDefinitionComparer SystemFirst { get; } = new DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions.SystemFirst); - public static SymbolDefinitionComparer OmitContainingNamespace { get; } = new DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions.OmitContainingNamespace); + public static SymbolDefinitionComparer OmitContainingNamespace { get; } = new DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions.OmitContainingNamespace); - public static SymbolDefinitionComparer SystemFirstOmitContainingNamespace { get; } = new DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions.SystemFirst | SymbolDefinitionSortOptions.OmitContainingNamespace); + public static SymbolDefinitionComparer SystemFirstOmitContainingNamespace { get; } = new DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions.SystemFirst | SymbolDefinitionSortOptions.OmitContainingNamespace); - public SymbolDefinitionSortOptions Options { get; } + public SymbolDefinitionSortOptions Options { get; } - public abstract IComparer NamespaceComparer { get; } + public abstract IComparer NamespaceComparer { get; } - public abstract IComparer TypeComparer { get; } + public abstract IComparer TypeComparer { get; } - public abstract IComparer MemberComparer { get; } + public abstract IComparer MemberComparer { get; } - public int Compare(ISymbol x, ISymbol y) - { - if (object.ReferenceEquals(x, y)) - return 0; - - if (x == null) - return -1; + public int Compare(ISymbol x, ISymbol y) + { + if (object.ReferenceEquals(x, y)) + return 0; - if (y == null) - return 1; + if (x is null) + return -1; - switch (x.Kind) - { - case SymbolKind.Namespace: - { - var namespaceSymbol = (INamespaceSymbol)x; + if (y is null) + return 1; - switch (y.Kind) + switch (x.Kind) + { + case SymbolKind.Namespace: { - 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); + 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; } - - break; - } - case SymbolKind.NamedType: - { - var typeSymbol = (INamedTypeSymbol)x; - - switch (y.Kind) + case SymbolKind.NamedType: { - 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); + 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; } - - break; - } - case SymbolKind.Event: - case SymbolKind.Field: - case SymbolKind.Method: - case SymbolKind.Property: - { - switch (y.Kind) + case SymbolKind.Event: + case SymbolKind.Field: + case SymbolKind.Method: + case SymbolKind.Property: { - 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); + 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; } + } - break; - } + throw new InvalidOperationException(); } - throw new InvalidOperationException(); - } - - private int CompareNamedTypeSymbol(INamedTypeSymbol typeSymbol1, INamedTypeSymbol typeSymbol2) - { - int diff = CompareContainingNamespace(typeSymbol1, typeSymbol2); - - if (diff != 0) - return diff; + private int CompareNamedTypeSymbol(INamedTypeSymbol typeSymbol1, INamedTypeSymbol typeSymbol2) + { + int diff = CompareContainingNamespace(typeSymbol1, typeSymbol2); - return TypeComparer.Compare(typeSymbol1, typeSymbol2); - } + if (diff != 0) + return diff; - private int CompareMemberSymbol(ISymbol symbol1, ISymbol symbol2) - { - int diff = CompareNamedTypeSymbol(symbol1.ContainingType, symbol2.ContainingType); + return TypeComparer.Compare(typeSymbol1, typeSymbol2); + } - if (diff != 0) - return diff; + private int CompareMemberSymbol(ISymbol symbol1, ISymbol symbol2) + { + int diff = CompareNamedTypeSymbol(symbol1.ContainingType, symbol2.ContainingType); - return MemberComparer.Compare(symbol1, symbol2); - } + if (diff != 0) + return diff; - private int CompareSymbolAndNamespaceSymbol(ISymbol symbol, INamespaceSymbol namespaceSymbol) - { - int diff = NamespaceComparer.Compare(symbol.ContainingNamespace, namespaceSymbol); + return MemberComparer.Compare(symbol1, symbol2); + } - if (diff != 0) - return diff; + private int CompareSymbolAndNamespaceSymbol(ISymbol symbol, INamespaceSymbol namespaceSymbol) + { + int diff = NamespaceComparer.Compare(symbol.ContainingNamespace, namespaceSymbol); - return 1; - } + if (diff != 0) + return diff; - private int CompareSymbolAndNamedTypeSymbol(ISymbol symbol, INamedTypeSymbol typeSymbol) - { - int diff = TypeComparer.Compare(symbol.ContainingType, typeSymbol); + return 1; + } - if (diff != 0) - return diff; + private int CompareSymbolAndNamedTypeSymbol(ISymbol symbol, INamedTypeSymbol typeSymbol) + { + int diff = TypeComparer.Compare(symbol.ContainingType, typeSymbol); - return 1; - } + if (diff != 0) + return diff; - internal int CompareContainingNamespace(ISymbol x, ISymbol y) - { - Debug.Assert(x.Kind != SymbolKind.Namespace, x.Kind.ToString()); - Debug.Assert(y.Kind != SymbolKind.Namespace, y.Kind.ToString()); - - return NamespaceComparer.Compare(x.ContainingNamespace, y.ContainingNamespace); - } + return 1; + } - public static int CompareName(ISymbol symbol1, ISymbol symbol2) - { - return string.CompareOrdinal(symbol1.Name, symbol2.Name); - } + internal int CompareContainingNamespace(ISymbol x, ISymbol y) + { + Debug.Assert(x.Kind != SymbolKind.Namespace, x.Kind.ToString()); + Debug.Assert(y.Kind != SymbolKind.Namespace, y.Kind.ToString()); - private class DefaultSymbolDefinitionComparer : SymbolDefinitionComparer - { - private IComparer _namespaceComparer; - private IComparer _typeComparer; - private IComparer _memberComparer; + return NamespaceComparer.Compare(x.ContainingNamespace, y.ContainingNamespace); + } - internal DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions options = SymbolDefinitionSortOptions.None) - : base(options) + public static int CompareName(ISymbol symbol1, ISymbol symbol2) { + return string.CompareOrdinal(symbol1.Name, symbol2.Name); } - public override IComparer NamespaceComparer + private class DefaultSymbolDefinitionComparer : SymbolDefinitionComparer { - get - { - if (_namespaceComparer == null) - Interlocked.CompareExchange(ref _namespaceComparer, CreateNamespaceComparer(), null); + private IComparer _namespaceComparer; + private IComparer _typeComparer; + private IComparer _memberComparer; - return _namespaceComparer; + internal DefaultSymbolDefinitionComparer(SymbolDefinitionSortOptions options = SymbolDefinitionSortOptions.None) + : base(options) + { + } - IComparer CreateNamespaceComparer() + public override IComparer NamespaceComparer + { + get { - return new NamespaceSymbolDefinitionComparer(this); + if (_namespaceComparer is null) + Interlocked.CompareExchange(ref _namespaceComparer, CreateNamespaceComparer(), null); + + return _namespaceComparer; + + IComparer CreateNamespaceComparer() + { + return new NamespaceSymbolDefinitionComparer(this); + } } } - } - public override IComparer TypeComparer - { - get + public override IComparer TypeComparer { - if (_typeComparer == null) - Interlocked.CompareExchange(ref _typeComparer, CreateTypeComparer(), null); + get + { + if (_typeComparer is null) + Interlocked.CompareExchange(ref _typeComparer, CreateTypeComparer(), null); - return _typeComparer; + return _typeComparer; - IComparer CreateTypeComparer() - { - return new NamedTypeSymbolDefinitionComparer(this); + IComparer CreateTypeComparer() + { + return new NamedTypeSymbolDefinitionComparer(this); + } } } - } - public override IComparer MemberComparer - { - get + public override IComparer MemberComparer { - if (_memberComparer == null) - Interlocked.CompareExchange(ref _memberComparer, CreateMemberComparer(), null); + get + { + if (_memberComparer is null) + Interlocked.CompareExchange(ref _memberComparer, CreateMemberComparer(), null); - return _memberComparer; + return _memberComparer; - IComparer CreateMemberComparer() - { - return new MemberSymbolDefinitionComparer(this); + IComparer CreateMemberComparer() + { + return new MemberSymbolDefinitionComparer(this); + } } } } diff --git a/src/Workspaces.Core/Diagnostics/CodeAnalyzer.cs b/src/Workspaces.Core/Diagnostics/CodeAnalyzer.cs index c4b4af1d8c..67dfe195f0 100644 --- a/src/Workspaces.Core/Diagnostics/CodeAnalyzer.cs +++ b/src/Workspaces.Core/Diagnostics/CodeAnalyzer.cs @@ -14,267 +14,268 @@ using Roslynator.Host.Mef; using static Roslynator.Logger; -namespace Roslynator.Diagnostics; - -internal class CodeAnalyzer +namespace Roslynator.Diagnostics { - private readonly AnalyzerLoader _analyzerLoader; - - internal static readonly TimeSpan MinimalExecutionTime = TimeSpan.FromMilliseconds(1); - - public CodeAnalyzer( - AnalyzerLoader analyzerLoader, - IFormatProvider formatProvider = null, - CodeAnalyzerOptions options = null) + internal class CodeAnalyzer { - _analyzerLoader = analyzerLoader; + private readonly AnalyzerLoader _analyzerLoader; - FormatProvider = formatProvider; - Options = options ?? CodeAnalyzerOptions.Default; - } + internal static readonly TimeSpan MinimalExecutionTime = TimeSpan.FromMilliseconds(1); - public IFormatProvider FormatProvider { get; } + public CodeAnalyzer( + AnalyzerLoader analyzerLoader, + IFormatProvider formatProvider = null, + CodeAnalyzerOptions options = null) + { + _analyzerLoader = analyzerLoader; - public CodeAnalyzerOptions Options { get; } + FormatProvider = formatProvider; + Options = options ?? CodeAnalyzerOptions.Default; + } - public async Task> AnalyzeSolutionAsync( - Solution solution, - Func predicate, - CancellationToken cancellationToken = default) - { - foreach (string id in Options.IgnoredDiagnosticIds.OrderBy(f => f)) - WriteLine($"Ignore diagnostic '{id}'", Verbosity.Diagnostic); + public IFormatProvider FormatProvider { get; } - ImmutableArray projectIds = solution - .GetProjectDependencyGraph() - .GetTopologicallySortedProjects(cancellationToken) - .ToImmutableArray(); + public CodeAnalyzerOptions Options { get; } - WriteLine($"Analyze solution '{solution.FilePath}'", ConsoleColors.Cyan, Verbosity.Minimal); + public async Task> AnalyzeSolutionAsync( + Solution solution, + Func predicate, + CancellationToken cancellationToken = default) + { + foreach (string id in Options.IgnoredDiagnosticIds.OrderBy(f => f)) + WriteLine($"Ignore diagnostic '{id}'", Verbosity.Diagnostic); - var results = new List(); + ImmutableArray projectIds = solution + .GetProjectDependencyGraph() + .GetTopologicallySortedProjects(cancellationToken) + .ToImmutableArray(); - Stopwatch stopwatch = Stopwatch.StartNew(); + WriteLine($"Analyze solution '{solution.FilePath}'", ConsoleColors.Cyan, Verbosity.Minimal); - TimeSpan lastElapsed = TimeSpan.Zero; + var results = new List(); - for (int i = 0; i < projectIds.Length; i++) - { - cancellationToken.ThrowIfCancellationRequested(); + Stopwatch stopwatch = Stopwatch.StartNew(); - Project project = solution.GetProject(projectIds[i]); + TimeSpan lastElapsed = TimeSpan.Zero; - if (predicate == null || predicate(project)) + for (int i = 0; i < projectIds.Length; i++) { - WriteLine($"Analyze '{project.Name}' {$"{i + 1}/{projectIds.Length}"}", Verbosity.Minimal); + cancellationToken.ThrowIfCancellationRequested(); - ProjectAnalysisResult result = await AnalyzeProjectCoreAsync(project, cancellationToken).ConfigureAwait(false); + Project project = solution.GetProject(projectIds[i]); - results.Add(result); - } - else - { - WriteLine($"Skip '{project.Name}' {$"{i + 1}/{projectIds.Length}"}", ConsoleColors.DarkGray, Verbosity.Minimal); - } + if (predicate is null || predicate(project)) + { + WriteLine($"Analyze '{project.Name}' {$"{i + 1}/{projectIds.Length}"}", Verbosity.Minimal); - lastElapsed = stopwatch.Elapsed; - } + ProjectAnalysisResult result = await AnalyzeProjectCoreAsync(project, cancellationToken).ConfigureAwait(false); - stopwatch.Stop(); + results.Add(result); + } + else + { + WriteLine($"Skip '{project.Name}' {$"{i + 1}/{projectIds.Length}"}", ConsoleColors.DarkGray, Verbosity.Minimal); + } - WriteLine($"Done analyzing solution '{solution.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal); + lastElapsed = stopwatch.Elapsed; + } - if (results.Count > 0) - WriteProjectAnalysisResults(results); + stopwatch.Stop(); - return results.ToImmutableArray(); - } + WriteLine($"Done analyzing solution '{solution.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal); - public async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken = default) - { - WriteLine($"Analyze '{project.Name}'", ConsoleColors.Cyan, Verbosity.Minimal); + if (results.Count > 0) + WriteProjectAnalysisResults(results); - Stopwatch stopwatch = Stopwatch.StartNew(); + return results.ToImmutableArray(); + } - ProjectAnalysisResult result = await AnalyzeProjectCoreAsync(project, cancellationToken).ConfigureAwait(false); + public async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken = default) + { + WriteLine($"Analyze '{project.Name}'", ConsoleColors.Cyan, Verbosity.Minimal); - stopwatch.Stop(); + Stopwatch stopwatch = Stopwatch.StartNew(); - WriteLine($"Done analyzing project '{project.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal); + ProjectAnalysisResult result = await AnalyzeProjectCoreAsync(project, cancellationToken).ConfigureAwait(false); - WriteProjectAnalysisResults(new ProjectAnalysisResult[] { result }); + stopwatch.Stop(); - return result; - } + WriteLine($"Done analyzing project '{project.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal); - private async Task AnalyzeProjectCoreAsync(Project project, CancellationToken cancellationToken = default) - { - ImmutableArray analyzers = _analyzerLoader.GetAnalyzers(project: project); + WriteProjectAnalysisResults(new ProjectAnalysisResult[] { result }); - if (!analyzers.Any()) - WriteLine($" No analyzers found to analyze '{project.Name}'", ConsoleColors.DarkGray, Verbosity.Normal); + return result; + } - if (analyzers.Any() - || !Options.IgnoreCompilerDiagnostics) + private async Task AnalyzeProjectCoreAsync(Project project, CancellationToken cancellationToken = default) { - return await AnalyzeProjectCoreAsync(project, analyzers, cancellationToken).ConfigureAwait(false); - } + ImmutableArray analyzers = _analyzerLoader.GetAnalyzers(project: project); - return ProjectAnalysisResult.Create(project); - } + if (!analyzers.Any()) + WriteLine($" No analyzers found to analyze '{project.Name}'", ConsoleColors.DarkGray, Verbosity.Normal); - private async Task AnalyzeProjectCoreAsync(Project project, ImmutableArray analyzers, CancellationToken cancellationToken = default) - { - LogHelpers.WriteUsedAnalyzers(analyzers, null, Options, ConsoleColors.DarkGray, Verbosity.Diagnostic); + if (analyzers.Any() + || !Options.IgnoreCompilerDiagnostics) + { + return await AnalyzeProjectCoreAsync(project, analyzers, cancellationToken).ConfigureAwait(false); + } - cancellationToken.ThrowIfCancellationRequested(); + return ProjectAnalysisResult.Create(project); + } - Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + private async Task AnalyzeProjectCoreAsync(Project project, ImmutableArray analyzers, CancellationToken cancellationToken = default) + { + LogHelpers.WriteUsedAnalyzers(analyzers, null, Options, ConsoleColors.DarkGray, Verbosity.Diagnostic); - ImmutableArray compilerDiagnostics = (Options.IgnoreCompilerDiagnostics) - ? ImmutableArray.Empty - : compilation.GetDiagnostics(cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); - compilerDiagnostics = FilterDiagnostics(compilerDiagnostics, project, cancellationToken).ToImmutableArray(); + Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - ImmutableArray diagnostics = ImmutableArray.Empty; + ImmutableArray compilerDiagnostics = (Options.IgnoreCompilerDiagnostics) + ? ImmutableArray.Empty + : compilation.GetDiagnostics(cancellationToken); - ImmutableDictionary telemetry = ImmutableDictionary.Empty; + compilerDiagnostics = FilterDiagnostics(compilerDiagnostics, project, cancellationToken).ToImmutableArray(); - if (analyzers.Any()) - { - var compilationWithAnalyzersOptions = new CompilationWithAnalyzersOptions( - options: project.AnalyzerOptions, - onAnalyzerException: default(Action), - concurrentAnalysis: Options.ConcurrentAnalysis, - logAnalyzerExecutionTime: Options.LogAnalyzerExecutionTime, - reportSuppressedDiagnostics: Options.ReportSuppressedDiagnostics); + ImmutableArray diagnostics = ImmutableArray.Empty; - var compilationWithAnalyzers = new CompilationWithAnalyzers(compilation, analyzers, compilationWithAnalyzersOptions); + ImmutableDictionary telemetry = ImmutableDictionary.Empty; - if (Options.LogAnalyzerExecutionTime) + if (analyzers.Any()) { - AnalysisResult analysisResult = await compilationWithAnalyzers.GetAnalysisResultAsync(cancellationToken).ConfigureAwait(false); + var compilationWithAnalyzersOptions = new CompilationWithAnalyzersOptions( + options: project.AnalyzerOptions, + onAnalyzerException: default(Action), + concurrentAnalysis: Options.ConcurrentAnalysis, + logAnalyzerExecutionTime: Options.LogAnalyzerExecutionTime, + reportSuppressedDiagnostics: Options.ReportSuppressedDiagnostics); - diagnostics = analysisResult.GetAllDiagnostics(); - telemetry = analysisResult.AnalyzerTelemetryInfo; - } - else - { - diagnostics = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(cancellationToken).ConfigureAwait(false); + var compilationWithAnalyzers = new CompilationWithAnalyzers(compilation, analyzers, compilationWithAnalyzersOptions); + + if (Options.LogAnalyzerExecutionTime) + { + AnalysisResult analysisResult = await compilationWithAnalyzers.GetAnalysisResultAsync(cancellationToken).ConfigureAwait(false); + + diagnostics = analysisResult.GetAllDiagnostics(); + telemetry = analysisResult.AnalyzerTelemetryInfo; + } + else + { + diagnostics = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(cancellationToken).ConfigureAwait(false); + } } - } - string projectDirectoryPath = Path.GetDirectoryName(project.FilePath); + string projectDirectoryPath = Path.GetDirectoryName(project.FilePath); - LogHelpers.WriteDiagnostics(FilterDiagnostics(diagnostics.Where(f => f.IsAnalyzerExceptionDiagnostic()), project, cancellationToken).ToImmutableArray(), baseDirectoryPath: projectDirectoryPath, formatProvider: FormatProvider, indentation: " ", verbosity: Verbosity.Detailed); + LogHelpers.WriteDiagnostics(FilterDiagnostics(diagnostics.Where(f => f.IsAnalyzerExceptionDiagnostic()), project, cancellationToken).ToImmutableArray(), baseDirectoryPath: projectDirectoryPath, formatProvider: FormatProvider, indentation: " ", verbosity: Verbosity.Detailed); #if DEBUG - if (ConsoleOut.Verbosity >= Verbosity.Detailed - && diagnostics.Any(f => f.IsAnalyzerExceptionDiagnostic())) - { - Console.Write("Stop (Y/N)? "); + if (ConsoleOut.Verbosity >= Verbosity.Detailed + && diagnostics.Any(f => f.IsAnalyzerExceptionDiagnostic())) + { + Console.Write("Stop (Y/N)? "); - if (char.ToUpperInvariant((char)Console.Read()) == 'Y') - throw new OperationCanceledException(); - } + if (char.ToUpperInvariant((char)Console.Read()) == 'Y') + throw new OperationCanceledException(); + } #endif - diagnostics = FilterDiagnostics(diagnostics.Where(f => !f.IsAnalyzerExceptionDiagnostic()), project, cancellationToken).ToImmutableArray(); + diagnostics = FilterDiagnostics(diagnostics.Where(f => !f.IsAnalyzerExceptionDiagnostic()), project, cancellationToken).ToImmutableArray(); - LogHelpers.WriteDiagnostics(compilerDiagnostics, baseDirectoryPath: projectDirectoryPath, formatProvider: FormatProvider, indentation: " ", verbosity: Verbosity.Normal); + LogHelpers.WriteDiagnostics(compilerDiagnostics, baseDirectoryPath: projectDirectoryPath, formatProvider: FormatProvider, indentation: " ", verbosity: Verbosity.Normal); - LogHelpers.WriteDiagnostics(diagnostics, baseDirectoryPath: projectDirectoryPath, formatProvider: FormatProvider, indentation: " ", verbosity: Verbosity.Normal); + LogHelpers.WriteDiagnostics(diagnostics, baseDirectoryPath: projectDirectoryPath, formatProvider: FormatProvider, indentation: " ", verbosity: Verbosity.Normal); - return ProjectAnalysisResult.Create(project, compilerDiagnostics, diagnostics, telemetry); - } + return ProjectAnalysisResult.Create(project, compilerDiagnostics, diagnostics, telemetry); + } - private IEnumerable FilterDiagnostics(IEnumerable diagnostics, Project project, CancellationToken cancellationToken = default) - { - foreach (Diagnostic diagnostic in diagnostics) + private IEnumerable FilterDiagnostics(IEnumerable diagnostics, Project project, CancellationToken cancellationToken = default) { - if (diagnostic.IsEffective(Options, project.CompilationOptions) - && (Options.ReportNotConfigurable || !diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable))) + foreach (Diagnostic diagnostic in diagnostics) { - if (diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Compiler)) + if (diagnostic.IsEffective(Options, project.CompilationOptions) + && (Options.ReportNotConfigurable || !diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable))) { - Debug.Assert(diagnostic.Id.StartsWith("CS", "VB", StringComparison.Ordinal), diagnostic.Id); + if (diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Compiler)) + { + Debug.Assert(diagnostic.Id.StartsWith("CS", "VB", StringComparison.Ordinal), diagnostic.Id); - SyntaxTree tree = diagnostic.Location.SourceTree; + SyntaxTree tree = diagnostic.Location.SourceTree; - if (tree == null - || !GeneratedCodeUtility.IsGeneratedCode(tree, f => MefWorkspaceServices.Default.GetService(tree.Options.Language).IsComment(f), cancellationToken)) + if (tree is null + || !GeneratedCodeUtility.IsGeneratedCode(tree, f => MefWorkspaceServices.Default.GetService(tree.Options.Language).IsComment(f), cancellationToken)) + { + yield return diagnostic; + } + } + else { yield return diagnostic; } } - else - { - yield return diagnostic; - } } } - } - private void WriteProjectAnalysisResults(IList results) - { - if (Options.LogAnalyzerExecutionTime) - WriteExecutionTime(); + private void WriteProjectAnalysisResults(IList results) + { + if (Options.LogAnalyzerExecutionTime) + WriteExecutionTime(); - int totalCount = results.Sum(f => f.Diagnostics.Length + f.CompilerDiagnostics.Length); + int totalCount = results.Sum(f => f.Diagnostics.Length + f.CompilerDiagnostics.Length); - if (totalCount > 0) - { - WriteLine(Verbosity.Normal); + if (totalCount > 0) + { + WriteLine(Verbosity.Normal); - Dictionary diagnosticsByDescriptor = results - .SelectMany(f => f.Diagnostics.Concat(f.CompilerDiagnostics)) - .GroupBy(f => f.Descriptor, DiagnosticDescriptorComparer.Id) - .ToDictionary(f => f.Key, f => f.Count()); + Dictionary diagnosticsByDescriptor = results + .SelectMany(f => f.Diagnostics.Concat(f.CompilerDiagnostics)) + .GroupBy(f => f.Descriptor, DiagnosticDescriptorComparer.Id) + .ToDictionary(f => f.Key, f => f.Count()); - int maxCountLength = Math.Max(totalCount.ToString().Length, diagnosticsByDescriptor.Max(f => f.Value.ToString().Length)); - int maxIdLength = diagnosticsByDescriptor.Max(f => f.Key.Id.Length); + int maxCountLength = Math.Max(totalCount.ToString().Length, diagnosticsByDescriptor.Max(f => f.Value.ToString().Length)); + int maxIdLength = diagnosticsByDescriptor.Max(f => f.Key.Id.Length); - foreach (KeyValuePair kvp in diagnosticsByDescriptor.OrderBy(f => f.Key.Id)) - { - WriteLine($"{kvp.Value.ToString().PadLeft(maxCountLength)} {kvp.Key.Id.PadRight(maxIdLength)} {kvp.Key.Title}", Verbosity.Normal); + foreach (KeyValuePair kvp in diagnosticsByDescriptor.OrderBy(f => f.Key.Id)) + { + WriteLine($"{kvp.Value.ToString().PadLeft(maxCountLength)} {kvp.Key.Id.PadRight(maxIdLength)} {kvp.Key.Title}", Verbosity.Normal); + } } - } - WriteLine(Verbosity.Minimal); - WriteLine($"{totalCount} {((totalCount == 1) ? "diagnostic" : "diagnostics")} found", ConsoleColors.Green, Verbosity.Minimal); + WriteLine(Verbosity.Minimal); + WriteLine($"{totalCount} {((totalCount == 1) ? "diagnostic" : "diagnostics")} found", ConsoleColors.Green, Verbosity.Minimal); - void WriteExecutionTime() - { - var telemetryInfos = new Dictionary(); - - foreach (ProjectAnalysisResult result in results) + void WriteExecutionTime() { - foreach (KeyValuePair kvp in result.Telemetry) + var telemetryInfos = new Dictionary(); + + foreach (ProjectAnalysisResult result in results) { - DiagnosticAnalyzer analyzer = kvp.Key; + foreach (KeyValuePair kvp in result.Telemetry) + { + DiagnosticAnalyzer analyzer = kvp.Key; - if (!telemetryInfos.TryGetValue(analyzer, out AnalyzerTelemetryInfo telemetryInfo)) - telemetryInfo = new AnalyzerTelemetryInfo(); + if (!telemetryInfos.TryGetValue(analyzer, out AnalyzerTelemetryInfo telemetryInfo)) + telemetryInfo = new AnalyzerTelemetryInfo(); - telemetryInfo.Add(kvp.Value); + telemetryInfo.Add(kvp.Value); - telemetryInfos[analyzer] = telemetryInfo; + telemetryInfos[analyzer] = telemetryInfo; + } } - } - using (IEnumerator> en = telemetryInfos - .Where(f => f.Value.ExecutionTime >= MinimalExecutionTime) - .OrderByDescending(f => f.Value.ExecutionTime) - .GetEnumerator()) - { - if (en.MoveNext()) + using (IEnumerator> en = telemetryInfos + .Where(f => f.Value.ExecutionTime >= MinimalExecutionTime) + .OrderByDescending(f => f.Value.ExecutionTime) + .GetEnumerator()) { - WriteLine(Verbosity.Minimal); - - do + if (en.MoveNext()) { - WriteLine($"{en.Current.Value.ExecutionTime:mm\\:ss\\.fff} '{en.Current.Key.GetType().FullName}'", Verbosity.Minimal); + WriteLine(Verbosity.Minimal); + + do + { + WriteLine($"{en.Current.Value.ExecutionTime:mm\\:ss\\.fff} '{en.Current.Key.GetType().FullName}'", Verbosity.Minimal); + } + while (en.MoveNext()); } - while (en.MoveNext()); } } } diff --git a/src/Workspaces.Core/Extensions/CollectionExtensions.cs b/src/Workspaces.Core/Extensions/CollectionExtensions.cs index 441ab4e9cb..db1f24f074 100644 --- a/src/Workspaces.Core/Extensions/CollectionExtensions.cs +++ b/src/Workspaces.Core/Extensions/CollectionExtensions.cs @@ -4,55 +4,56 @@ using System.Collections.Generic; using System.Linq; -namespace Roslynator; - -internal static class CollectionExtensions +namespace Roslynator { - public static T SingleOrDefault(this IReadOnlyCollection values, bool shouldThrow) + internal static class CollectionExtensions { - if (values == null) - throw new ArgumentNullException(nameof(values)); - - if (shouldThrow) + public static T SingleOrDefault(this IReadOnlyCollection values, bool shouldThrow) { - return values.SingleOrDefault(); - } - else - { - return (values.Count == 1) ? values.First() : default; + if (values is null) + throw new ArgumentNullException(nameof(values)); + + if (shouldThrow) + { + return values.SingleOrDefault(); + } + else + { + return (values.Count == 1) ? values.First() : default; + } } - } - public static T SingleOrDefault( - this IReadOnlyCollection list, - Func predicate, - bool shouldThrow) - { - if (list == null) - throw new ArgumentNullException(nameof(list)); + public static T SingleOrDefault( + this IReadOnlyCollection list, + Func predicate, + bool shouldThrow) + { + if (list is null) + throw new ArgumentNullException(nameof(list)); - if (shouldThrow) - return list.SingleOrDefault(predicate); + if (shouldThrow) + return list.SingleOrDefault(predicate); - using (IEnumerator en = list.GetEnumerator()) - { - while (en.MoveNext()) + using (IEnumerator en = list.GetEnumerator()) { - T item = en.Current; - - if (predicate(item)) + while (en.MoveNext()) { - while (en.MoveNext()) + T item = en.Current; + + if (predicate(item)) { - if (predicate(en.Current)) - return default; - } + while (en.MoveNext()) + { + if (predicate(en.Current)) + return default; + } - return item; + return item; + } } } - } - return default; + return default; + } } } diff --git a/src/Workspaces.Core/Extensions/WorkspaceExtensions.cs b/src/Workspaces.Core/Extensions/WorkspaceExtensions.cs index 72ca33fc0c..78cdf4bb68 100644 --- a/src/Workspaces.Core/Extensions/WorkspaceExtensions.cs +++ b/src/Workspaces.Core/Extensions/WorkspaceExtensions.cs @@ -8,495 +8,496 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; -namespace Roslynator; - -/// -/// A set of extension methods for the workspace layer. -/// -public static class WorkspaceExtensions +namespace Roslynator { - #region Document - internal static Task WithTextChangeAsync( - this Document document, - TextSpan span, - string newText, - CancellationToken cancellationToken = default) - { - return WithTextChangeAsync(document, new TextChange(span, newText), cancellationToken); - } - /// - /// Creates a new document updated with the specified text change. + /// A set of extension methods for the workspace layer. /// - /// - /// - /// - public static Task WithTextChangeAsync( - this Document document, - TextChange textChange, - CancellationToken cancellationToken = default) + public static class WorkspaceExtensions { - return WithTextChangesAsync(document, new TextChange[] { textChange }, cancellationToken); - } + #region Document + internal static Task WithTextChangeAsync( + this Document document, + TextSpan span, + string newText, + CancellationToken cancellationToken = default) + { + return WithTextChangeAsync(document, new TextChange(span, newText), cancellationToken); + } - /// - /// Creates a new document updated with the specified text changes. - /// - /// - /// - /// - public static async Task WithTextChangesAsync( - this Document document, - TextChange[] textChanges, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + /// + /// Creates a new document updated with the specified text change. + /// + /// + /// + /// + public static Task WithTextChangeAsync( + this Document document, + TextChange textChange, + CancellationToken cancellationToken = default) + { + return WithTextChangesAsync(document, new TextChange[] { textChange }, cancellationToken); + } - if (textChanges == null) - throw new ArgumentNullException(nameof(textChanges)); + /// + /// Creates a new document updated with the specified text changes. + /// + /// + /// + /// + public static async Task WithTextChangesAsync( + this Document document, + TextChange[] textChanges, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + if (textChanges is null) + throw new ArgumentNullException(nameof(textChanges)); - SourceText newSourceText = sourceText.WithChanges(textChanges); + SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); - return document.WithText(newSourceText); - } + SourceText newSourceText = sourceText.WithChanges(textChanges); - /// - /// Creates a new document updated with the specified text changes. - /// - /// - /// - /// - public static async Task WithTextChangesAsync( - this Document document, - IEnumerable textChanges, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithText(newSourceText); + } - if (textChanges == null) - throw new ArgumentNullException(nameof(textChanges)); + /// + /// Creates a new document updated with the specified text changes. + /// + /// + /// + /// + public static async Task WithTextChangesAsync( + this Document document, + IEnumerable textChanges, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + if (textChanges is null) + throw new ArgumentNullException(nameof(textChanges)); - SourceText newSourceText = sourceText.WithChanges(textChanges); + SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); - return document.WithText(newSourceText); - } + SourceText newSourceText = sourceText.WithChanges(textChanges); - /// - /// Creates a new document with the specified old node replaced with a new node. - /// - /// - /// - /// - /// - public static async Task ReplaceNodeAsync( - this Document document, - SyntaxNode oldNode, - SyntaxNode newNode, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithText(newSourceText); + } - if (oldNode == null) - throw new ArgumentNullException(nameof(oldNode)); + /// + /// Creates a new document with the specified old node replaced with a new node. + /// + /// + /// + /// + /// + public static async Task ReplaceNodeAsync( + this Document document, + SyntaxNode oldNode, + SyntaxNode newNode, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - if (newNode == null) - throw new ArgumentNullException(nameof(newNode)); + if (oldNode is null) + throw new ArgumentNullException(nameof(oldNode)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (newNode is null) + throw new ArgumentNullException(nameof(newNode)); - SyntaxNode newRoot = root.ReplaceNode(oldNode, newNode); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.ReplaceNode(oldNode, newNode); - /// - /// Creates a new document with the specified old node replaced with new nodes. - /// - /// - /// - /// - /// - public static async Task ReplaceNodeAsync( - this Document document, - SyntaxNode oldNode, - IEnumerable newNodes, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - if (oldNode == null) - throw new ArgumentNullException(nameof(oldNode)); + /// + /// Creates a new document with the specified old node replaced with new nodes. + /// + /// + /// + /// + /// + public static async Task ReplaceNodeAsync( + this Document document, + SyntaxNode oldNode, + IEnumerable newNodes, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - if (newNodes == null) - throw new ArgumentNullException(nameof(newNodes)); + if (oldNode is null) + throw new ArgumentNullException(nameof(oldNode)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (newNodes is null) + throw new ArgumentNullException(nameof(newNodes)); - SyntaxNode newRoot = root.ReplaceNode(oldNode, newNodes); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.ReplaceNode(oldNode, newNodes); - /// - /// Creates a new document with the specified old nodes replaced with new nodes. - /// - /// - /// - /// - /// - /// - public static async Task ReplaceNodesAsync( - this Document document, - IEnumerable nodes, - Func computeReplacementNode, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - if (nodes == null) - throw new ArgumentNullException(nameof(nodes)); + /// + /// Creates a new document with the specified old nodes replaced with new nodes. + /// + /// + /// + /// + /// + /// + public static async Task ReplaceNodesAsync( + this Document document, + IEnumerable nodes, + Func computeReplacementNode, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - if (computeReplacementNode == null) - throw new ArgumentNullException(nameof(computeReplacementNode)); + if (nodes is null) + throw new ArgumentNullException(nameof(nodes)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (computeReplacementNode is null) + throw new ArgumentNullException(nameof(computeReplacementNode)); - SyntaxNode newRoot = root.ReplaceNodes(nodes, computeReplacementNode); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.ReplaceNodes(nodes, computeReplacementNode); - /// - /// Creates a new document with the specified old token replaced with a new token. - /// - /// - /// - /// - /// - public static async Task ReplaceTokenAsync( - this Document document, - SyntaxToken oldToken, - SyntaxToken newToken, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + /// + /// Creates a new document with the specified old token replaced with a new token. + /// + /// + /// + /// + /// + public static async Task ReplaceTokenAsync( + this Document document, + SyntaxToken oldToken, + SyntaxToken newToken, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode newRoot = root.ReplaceToken(oldToken, newToken); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.ReplaceToken(oldToken, newToken); - /// - /// Creates a new document with the specified old token replaced with new tokens. - /// - /// - /// - /// - /// - public static async Task ReplaceTokenAsync( - this Document document, - SyntaxToken oldToken, - IEnumerable newTokens, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - if (newTokens == null) - throw new ArgumentNullException(nameof(newTokens)); + /// + /// Creates a new document with the specified old token replaced with new tokens. + /// + /// + /// + /// + /// + public static async Task ReplaceTokenAsync( + this Document document, + SyntaxToken oldToken, + IEnumerable newTokens, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (newTokens is null) + throw new ArgumentNullException(nameof(newTokens)); - SyntaxNode newRoot = root.ReplaceToken(oldToken, newTokens); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.ReplaceToken(oldToken, newTokens); - /// - /// Creates a new document with the specified old trivia replaced with a new trivia. - /// - /// - /// - /// - /// - public static async Task ReplaceTriviaAsync( - this Document document, - SyntaxTrivia oldTrivia, - SyntaxTrivia newTrivia, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + /// + /// Creates a new document with the specified old trivia replaced with a new trivia. + /// + /// + /// + /// + /// + public static async Task ReplaceTriviaAsync( + this Document document, + SyntaxTrivia oldTrivia, + SyntaxTrivia newTrivia, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode newRoot = root.ReplaceTrivia(oldTrivia, newTrivia); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.ReplaceTrivia(oldTrivia, newTrivia); - /// - /// Creates a new document with the specified old trivia replaced with a new trivia. - /// - /// - /// - /// - /// - public static async Task ReplaceTriviaAsync( - this Document document, - SyntaxTrivia oldTrivia, - IEnumerable newTrivia, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - if (newTrivia == null) - throw new ArgumentNullException(nameof(newTrivia)); + /// + /// Creates a new document with the specified old trivia replaced with a new trivia. + /// + /// + /// + /// + /// + public static async Task ReplaceTriviaAsync( + this Document document, + SyntaxTrivia oldTrivia, + IEnumerable newTrivia, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (newTrivia is null) + throw new ArgumentNullException(nameof(newTrivia)); - SyntaxNode newRoot = root.ReplaceTrivia(oldTrivia, newTrivia); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.ReplaceTrivia(oldTrivia, newTrivia); - /// - /// Creates a new document with a new node inserted before the specified node. - /// - /// - /// - /// - /// - public static Task InsertNodeBeforeAsync( - this Document document, - SyntaxNode nodeInList, - SyntaxNode newNode, - CancellationToken cancellationToken = default) - { - if (newNode == null) - throw new ArgumentNullException(nameof(newNode)); + return document.WithSyntaxRoot(newRoot); + } - return InsertNodesBeforeAsync(document, nodeInList, new SyntaxNode[] { newNode }, cancellationToken); - } + /// + /// Creates a new document with a new node inserted before the specified node. + /// + /// + /// + /// + /// + public static Task InsertNodeBeforeAsync( + this Document document, + SyntaxNode nodeInList, + SyntaxNode newNode, + CancellationToken cancellationToken = default) + { + if (newNode is null) + throw new ArgumentNullException(nameof(newNode)); - /// - /// Creates a new document with new nodes inserted before the specified node. - /// - /// - /// - /// - /// - public static async Task InsertNodesBeforeAsync( - this Document document, - SyntaxNode nodeInList, - IEnumerable newNodes, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return InsertNodesBeforeAsync(document, nodeInList, new SyntaxNode[] { newNode }, cancellationToken); + } - if (nodeInList == null) - throw new ArgumentNullException(nameof(nodeInList)); + /// + /// Creates a new document with new nodes inserted before the specified node. + /// + /// + /// + /// + /// + public static async Task InsertNodesBeforeAsync( + this Document document, + SyntaxNode nodeInList, + IEnumerable newNodes, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - if (newNodes == null) - throw new ArgumentNullException(nameof(newNodes)); + if (nodeInList is null) + throw new ArgumentNullException(nameof(nodeInList)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (newNodes is null) + throw new ArgumentNullException(nameof(newNodes)); - SyntaxNode newRoot = root.InsertNodesBefore(nodeInList, newNodes); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.InsertNodesBefore(nodeInList, newNodes); - /// - /// Creates a new document with a new node inserted after the specified node. - /// - /// - /// - /// - /// - public static Task InsertNodeAfterAsync( - this Document document, - SyntaxNode nodeInList, - SyntaxNode newNode, - CancellationToken cancellationToken = default) - { - if (newNode == null) - throw new ArgumentNullException(nameof(newNode)); + return document.WithSyntaxRoot(newRoot); + } - return InsertNodesAfterAsync(document, nodeInList, new SyntaxNode[] { newNode }, cancellationToken); - } + /// + /// Creates a new document with a new node inserted after the specified node. + /// + /// + /// + /// + /// + public static Task InsertNodeAfterAsync( + this Document document, + SyntaxNode nodeInList, + SyntaxNode newNode, + CancellationToken cancellationToken = default) + { + if (newNode is null) + throw new ArgumentNullException(nameof(newNode)); - /// - /// Creates a new document with new nodes inserted after the specified node. - /// - /// - /// - /// - /// - public static async Task InsertNodesAfterAsync( - this Document document, - SyntaxNode nodeInList, - IEnumerable newNodes, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return InsertNodesAfterAsync(document, nodeInList, new SyntaxNode[] { newNode }, cancellationToken); + } - if (nodeInList == null) - throw new ArgumentNullException(nameof(nodeInList)); + /// + /// Creates a new document with new nodes inserted after the specified node. + /// + /// + /// + /// + /// + public static async Task InsertNodesAfterAsync( + this Document document, + SyntaxNode nodeInList, + IEnumerable newNodes, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - if (newNodes == null) - throw new ArgumentNullException(nameof(newNodes)); + if (nodeInList is null) + throw new ArgumentNullException(nameof(nodeInList)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (newNodes is null) + throw new ArgumentNullException(nameof(newNodes)); - SyntaxNode newRoot = root.InsertNodesAfter(nodeInList, newNodes); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.InsertNodesAfter(nodeInList, newNodes); - /// - /// Creates a new document with the specified node removed. - /// - /// - /// - /// - /// - public static async Task RemoveNodeAsync( - this Document document, - SyntaxNode node, - SyntaxRemoveOptions options, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - if (node == null) - throw new ArgumentNullException(nameof(node)); + /// + /// Creates a new document with the specified node removed. + /// + /// + /// + /// + /// + public static async Task RemoveNodeAsync( + this Document document, + SyntaxNode node, + SyntaxRemoveOptions options, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (node is null) + throw new ArgumentNullException(nameof(node)); - SyntaxNode newRoot = root.RemoveNode(node, options); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.RemoveNode(node, options); - /// - /// Creates a new document with the specified nodes removed. - /// - /// - /// - /// - /// - public static async Task RemoveNodesAsync( - this Document document, - IEnumerable nodes, - SyntaxRemoveOptions options, - CancellationToken cancellationToken = default) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); + return document.WithSyntaxRoot(newRoot); + } - if (nodes == null) - throw new ArgumentNullException(nameof(nodes)); + /// + /// Creates a new document with the specified nodes removed. + /// + /// + /// + /// + /// + public static async Task RemoveNodesAsync( + this Document document, + IEnumerable nodes, + SyntaxRemoveOptions options, + CancellationToken cancellationToken = default) + { + if (document is null) + throw new ArgumentNullException(nameof(document)); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (nodes is null) + throw new ArgumentNullException(nameof(nodes)); - SyntaxNode newRoot = root.RemoveNodes(nodes, options); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(newRoot); - } + SyntaxNode newRoot = root.RemoveNodes(nodes, options); - internal static Solution Solution(this Document document) - { - return document.Project.Solution; - } - #endregion Document + return document.WithSyntaxRoot(newRoot); + } - #region Solution - /// - /// Creates a new solution with the specified old node replaced with a new node. - /// - /// - /// - /// - /// - /// - public static async Task ReplaceNodeAsync( - this Solution solution, - TNode oldNode, - TNode newNode, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - if (solution == null) - throw new ArgumentNullException(nameof(solution)); + internal static Solution Solution(this Document document) + { + return document.Project.Solution; + } + #endregion Document + + #region Solution + /// + /// Creates a new solution with the specified old node replaced with a new node. + /// + /// + /// + /// + /// + /// + public static async Task ReplaceNodeAsync( + this Solution solution, + TNode oldNode, + TNode newNode, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + if (solution is null) + throw new ArgumentNullException(nameof(solution)); - if (oldNode == null) - throw new ArgumentNullException(nameof(oldNode)); + if (oldNode is null) + throw new ArgumentNullException(nameof(oldNode)); - if (newNode == null) - throw new ArgumentNullException(nameof(newNode)); + if (newNode is null) + throw new ArgumentNullException(nameof(newNode)); - Document document = solution.GetDocument(oldNode.SyntaxTree); + Document document = solution.GetDocument(oldNode.SyntaxTree); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - SyntaxNode newRoot = root.ReplaceNode(oldNode, newNode); + SyntaxNode newRoot = root.ReplaceNode(oldNode, newNode); - return solution.WithDocumentSyntaxRoot(document.Id, newRoot); - } + return solution.WithDocumentSyntaxRoot(document.Id, newRoot); + } - /// - /// Creates a new solution with the specified old nodes replaced with new nodes. - /// - /// - /// - /// - /// - /// - public static async Task ReplaceNodesAsync( - this Solution solution, - IEnumerable nodes, - Func computeReplacementNodes, - CancellationToken cancellationToken = default) where TNode : SyntaxNode - { - if (solution == null) - throw new ArgumentNullException(nameof(solution)); + /// + /// Creates a new solution with the specified old nodes replaced with new nodes. + /// + /// + /// + /// + /// + /// + public static async Task ReplaceNodesAsync( + this Solution solution, + IEnumerable nodes, + Func computeReplacementNodes, + CancellationToken cancellationToken = default) where TNode : SyntaxNode + { + if (solution is null) + throw new ArgumentNullException(nameof(solution)); - if (nodes == null) - throw new ArgumentNullException(nameof(nodes)); + if (nodes is null) + throw new ArgumentNullException(nameof(nodes)); - if (computeReplacementNodes == null) - throw new ArgumentNullException(nameof(computeReplacementNodes)); + if (computeReplacementNodes is null) + throw new ArgumentNullException(nameof(computeReplacementNodes)); - Solution newSolution = solution; + Solution newSolution = solution; - foreach (IGrouping grouping in nodes.GroupBy(f => f.SyntaxTree)) - { - Document document = solution.GetDocument(grouping.Key); + foreach (IGrouping grouping in nodes.GroupBy(f => f.SyntaxTree)) + { + Document document = solution.GetDocument(grouping.Key); - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - SyntaxNode newRoot = root.ReplaceNodes(grouping, computeReplacementNodes); + SyntaxNode newRoot = root.ReplaceNodes(grouping, computeReplacementNodes); - newSolution = newSolution.WithDocumentSyntaxRoot(document.Id, newRoot); - } + newSolution = newSolution.WithDocumentSyntaxRoot(document.Id, newRoot); + } - return newSolution; + return newSolution; + } + #endregion Solution } - #endregion Solution } diff --git a/src/Workspaces.Core/Formatting/CodeFormatter.cs b/src/Workspaces.Core/Formatting/CodeFormatter.cs index c05f655058..3aef6191ec 100644 --- a/src/Workspaces.Core/Formatting/CodeFormatter.cs +++ b/src/Workspaces.Core/Formatting/CodeFormatter.cs @@ -10,103 +10,104 @@ using Microsoft.CodeAnalysis.Options; using static Roslynator.Logger; -namespace Roslynator.Formatting; - -internal static class CodeFormatter +namespace Roslynator.Formatting { - public static Task FormatProjectAsync( - Project project, - ISyntaxFactsService syntaxFacts, - CancellationToken cancellationToken = default) - { - return FormatProjectAsync(project, syntaxFacts, default(CodeFormatterOptions), cancellationToken); - } - - public static async Task FormatProjectAsync( - Project project, - ISyntaxFactsService syntaxFacts, - CodeFormatterOptions options, - CancellationToken cancellationToken = default) + internal static class CodeFormatter { - if (options == null) - options = CodeFormatterOptions.Default; + public static Task FormatProjectAsync( + Project project, + ISyntaxFactsService syntaxFacts, + CancellationToken cancellationToken = default) + { + return FormatProjectAsync(project, syntaxFacts, default(CodeFormatterOptions), cancellationToken); + } - foreach (DocumentId documentId in project.DocumentIds) + public static async Task FormatProjectAsync( + Project project, + ISyntaxFactsService syntaxFacts, + CodeFormatterOptions options, + CancellationToken cancellationToken = default) { - Document document = project.GetDocument(documentId); + if (options is null) + options = CodeFormatterOptions.Default; - if (options.IncludeGeneratedCode - || !GeneratedCodeUtility.IsGeneratedCodeFile(document.FilePath)) + foreach (DocumentId documentId in project.DocumentIds) { - SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + Document document = project.GetDocument(documentId); if (options.IncludeGeneratedCode - || !syntaxFacts.BeginsWithAutoGeneratedComment(root)) + || !GeneratedCodeUtility.IsGeneratedCodeFile(document.FilePath)) { - DocumentOptionSet optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - Document newDocument = await Formatter.FormatAsync(document, optionSet, cancellationToken).ConfigureAwait(false); + if (options.IncludeGeneratedCode + || !syntaxFacts.BeginsWithAutoGeneratedComment(root)) + { + DocumentOptionSet optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); - project = newDocument.Project; + Document newDocument = await Formatter.FormatAsync(document, optionSet, cancellationToken).ConfigureAwait(false); + + project = newDocument.Project; + } } } - } - return project; - } - - internal static async Task> GetFormattedDocumentsAsync( - Project project, - Project newProject, - ISyntaxFactsService syntaxFacts) - { - ImmutableArray.Builder builder = null; + return project; + } - //TODO: GetChangedDocuments(onlyGetDocumentsWithTextChanges: true) - foreach (DocumentId documentId in newProject - .GetChanges(project) - .GetChangedDocuments()) + internal static async Task> GetFormattedDocumentsAsync( + Project project, + Project newProject, + ISyntaxFactsService syntaxFacts) { - Document document = newProject.GetDocument(documentId); + ImmutableArray.Builder builder = null; - // https://github.com/dotnet/roslyn/issues/30674 - if ((await document.GetTextChangesAsync(project.GetDocument(documentId)).ConfigureAwait(false)).Any()) + //TODO: GetChangedDocuments(onlyGetDocumentsWithTextChanges: true) + foreach (DocumentId documentId in newProject + .GetChanges(project) + .GetChangedDocuments()) { + Document document = newProject.GetDocument(documentId); + + // https://github.com/dotnet/roslyn/issues/30674 + if ((await document.GetTextChangesAsync(project.GetDocument(documentId)).ConfigureAwait(false)).Any()) + { #if DEBUG - bool success = await VerifySyntaxEquivalenceAsync(project.GetDocument(document.Id), document, syntaxFacts).ConfigureAwait(false); + bool success = await VerifySyntaxEquivalenceAsync(project.GetDocument(document.Id), document, syntaxFacts).ConfigureAwait(false); #endif - (builder ??= ImmutableArray.CreateBuilder()).Add(document.Id); + (builder ??= ImmutableArray.CreateBuilder()).Add(document.Id); + } } - } - return builder?.ToImmutableArray() ?? ImmutableArray.Empty; - } + return builder?.ToImmutableArray() ?? ImmutableArray.Empty; + } #if DEBUG - private static async Task VerifySyntaxEquivalenceAsync( - Document oldDocument, - Document newDocument, - ISyntaxFactsService syntaxFacts, - CancellationToken cancellationToken = default) - { - if (!string.Equals( - (await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).NormalizeWhitespace("", false).ToFullString(), - (await oldDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).NormalizeWhitespace("", false).ToFullString(), - StringComparison.Ordinal)) + private static async Task VerifySyntaxEquivalenceAsync( + Document oldDocument, + Document newDocument, + ISyntaxFactsService syntaxFacts, + CancellationToken cancellationToken = default) { - WriteLine($"Syntax roots with normalized white-space are not equivalent '{oldDocument.FilePath}'", ConsoleColors.Magenta); - return false; - } + if (!string.Equals( + (await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).NormalizeWhitespace("", false).ToFullString(), + (await oldDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).NormalizeWhitespace("", false).ToFullString(), + StringComparison.Ordinal)) + { + WriteLine($"Syntax roots with normalized white-space are not equivalent '{oldDocument.FilePath}'", ConsoleColors.Magenta); + return false; + } - if (!syntaxFacts.AreEquivalent( - await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), - await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))) - { - WriteLine($"Syntax trees are not equivalent '{oldDocument.FilePath}'", ConsoleColors.Magenta); - return false; - } + if (!syntaxFacts.AreEquivalent( + await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), + await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))) + { + WriteLine($"Syntax trees are not equivalent '{oldDocument.FilePath}'", ConsoleColors.Magenta); + return false; + } - return true; - } + return true; + } #endif + } } diff --git a/src/Workspaces.Core/Host/Mef/MefHostServices.cs b/src/Workspaces.Core/Host/Mef/MefHostServices.cs index 3c18e85171..05c8638868 100644 --- a/src/Workspaces.Core/Host/Mef/MefHostServices.cs +++ b/src/Workspaces.Core/Host/Mef/MefHostServices.cs @@ -11,112 +11,113 @@ using System.Threading; using Microsoft.CodeAnalysis; -namespace Roslynator.Host.Mef; - -internal class MefHostServices +namespace Roslynator.Host.Mef { - private static MefHostServices _default; - private static ImmutableArray _defaultAssemblies; + internal class MefHostServices + { + private static MefHostServices _default; + private static ImmutableArray _defaultAssemblies; - private readonly CompositionContext _compositionContext; + private readonly CompositionContext _compositionContext; - public MefHostServices(CompositionContext compositionContext) - { - _compositionContext = compositionContext; - } + public MefHostServices(CompositionContext compositionContext) + { + _compositionContext = compositionContext; + } - public static MefHostServices Default - { - get + public static MefHostServices Default { - if (_default == null) + get { - MefHostServices services = Create(DefaultAssemblies); - Interlocked.CompareExchange(ref _default, services, null); - } + if (_default is null) + { + MefHostServices services = Create(DefaultAssemblies); + Interlocked.CompareExchange(ref _default, services, null); + } - return _default; + return _default; + } } - } - public static ImmutableArray DefaultAssemblies - { - get + public static ImmutableArray DefaultAssemblies { - if (_defaultAssemblies.IsDefault) - ImmutableInterlocked.InterlockedInitialize(ref _defaultAssemblies, LoadDefaultAssemblies()); + get + { + if (_defaultAssemblies.IsDefault) + ImmutableInterlocked.InterlockedInitialize(ref _defaultAssemblies, LoadDefaultAssemblies()); - return _defaultAssemblies; + return _defaultAssemblies; + } } - } - - public static MefHostServices Create(CompositionContext compositionContext) - { - if (compositionContext == null) - throw new ArgumentNullException(nameof(compositionContext)); - return new MefHostServices(compositionContext); - } + public static MefHostServices Create(CompositionContext compositionContext) + { + if (compositionContext is null) + throw new ArgumentNullException(nameof(compositionContext)); - public static MefHostServices Create(IEnumerable assemblies) - { - if (assemblies == null) - throw new ArgumentNullException(nameof(assemblies)); + return new MefHostServices(compositionContext); + } - ContainerConfiguration compositionConfiguration = new ContainerConfiguration().WithAssemblies(assemblies); + public static MefHostServices Create(IEnumerable assemblies) + { + if (assemblies is null) + throw new ArgumentNullException(nameof(assemblies)); - CompositionHost container = compositionConfiguration.CreateContainer(); + ContainerConfiguration compositionConfiguration = new ContainerConfiguration().WithAssemblies(assemblies); - return new MefHostServices(container); - } + CompositionHost container = compositionConfiguration.CreateContainer(); - private static ImmutableArray LoadDefaultAssemblies() - { - return GetAssemblyNames() - .Select(f => TryLoadAssembly(f)) - .Where(f => f != null) - .ToImmutableArray(); + return new MefHostServices(container); + } - static IEnumerable GetAssemblyNames() + private static ImmutableArray LoadDefaultAssemblies() { - AssemblyName assemblyName = typeof(MefHostServices).GetTypeInfo().Assembly.GetName(); - Version assemblyVersion = assemblyName.Version; - string publicKeyToken = assemblyName.GetPublicKeyToken().Aggregate("", (s, b) => s + b.ToString("x2")); + return GetAssemblyNames() + .Select(f => TryLoadAssembly(f)) + .Where(f => f is not null) + .ToImmutableArray(); + + static IEnumerable GetAssemblyNames() + { + AssemblyName assemblyName = typeof(MefHostServices).GetTypeInfo().Assembly.GetName(); + Version assemblyVersion = assemblyName.Version; + string publicKeyToken = assemblyName.GetPublicKeyToken().Aggregate("", (s, b) => s + b.ToString("x2")); - string prefix = Regex.Match(assemblyName.Name, @"\A.*Roslynator(?=\..*\z)", RegexOptions.RightToLeft).Value; + string prefix = Regex.Match(assemblyName.Name, @"\A.*Roslynator(?=\..*\z)", RegexOptions.RightToLeft).Value; - yield return $"{prefix}.CSharp.Workspaces, Version={assemblyVersion}, Culture=neutral, PublicKeyToken={publicKeyToken}"; - yield return $"{prefix}.VisualBasic.Workspaces, Version={assemblyVersion}, Culture=neutral, PublicKeyToken={publicKeyToken}"; + yield return $"{prefix}.CSharp.Workspaces, Version={assemblyVersion}, Culture=neutral, PublicKeyToken={publicKeyToken}"; + yield return $"{prefix}.VisualBasic.Workspaces, Version={assemblyVersion}, Culture=neutral, PublicKeyToken={publicKeyToken}"; + } } - } - private static Assembly TryLoadAssembly(string assemblyName) - { - try + private static Assembly TryLoadAssembly(string assemblyName) { - return Assembly.Load(new AssemblyName(assemblyName)); + try + { + return Assembly.Load(new AssemblyName(assemblyName)); + } + catch (Exception) + { + return null; + } } - catch (Exception) + + public IEnumerable> GetExports() { - return null; + return _compositionContext.GetExports().Select(e => new Lazy(() => e)); } - } - - public IEnumerable> GetExports() - { - return _compositionContext.GetExports().Select(e => new Lazy(() => e)); - } - public IEnumerable> GetExports() - { - var importer = new WithMetadataImporter(); - _compositionContext.SatisfyImports(importer); - return importer.Exports; - } + public IEnumerable> GetExports() + { + var importer = new WithMetadataImporter(); + _compositionContext.SatisfyImports(importer); + return importer.Exports; + } - private class WithMetadataImporter - { - [ImportMany] - public IEnumerable> Exports { get; set; } + private class WithMetadataImporter + { + [ImportMany] + public IEnumerable> Exports { get; set; } + } } } diff --git a/src/Workspaces.Core/Host/Mef/MefWorkspaceServices.cs b/src/Workspaces.Core/Host/Mef/MefWorkspaceServices.cs index 808fdec587..020788f7e3 100644 --- a/src/Workspaces.Core/Host/Mef/MefWorkspaceServices.cs +++ b/src/Workspaces.Core/Host/Mef/MefWorkspaceServices.cs @@ -7,90 +7,91 @@ using System.Threading; using Microsoft.CodeAnalysis.Host; -namespace Roslynator.Host.Mef; - -internal class MefWorkspaceServices +namespace Roslynator.Host.Mef { - private static MefWorkspaceServices _default; - private readonly MefHostServices _mefServices; - private IEnumerable _languages; + internal class MefWorkspaceServices + { + private static MefWorkspaceServices _default; + private readonly MefHostServices _mefServices; + private IEnumerable _languages; - private ImmutableDictionary _languageServicesMap - = ImmutableDictionary.Empty; + private ImmutableDictionary _languageServicesMap + = ImmutableDictionary.Empty; - public MefWorkspaceServices(MefHostServices mefServices) - { - _mefServices = mefServices; - } + public MefWorkspaceServices(MefHostServices mefServices) + { + _mefServices = mefServices; + } - public static MefWorkspaceServices Default - { - get + public static MefWorkspaceServices Default { - if (_default == null) + get { - var services = new MefWorkspaceServices(MefHostServices.Default); - Interlocked.CompareExchange(ref _default, services, null); - } + if (_default is null) + { + var services = new MefWorkspaceServices(MefHostServices.Default); + Interlocked.CompareExchange(ref _default, services, null); + } - return _default; + return _default; + } } - } - public IEnumerable SupportedLanguages => GetSupportedLanguages(); + public IEnumerable SupportedLanguages => GetSupportedLanguages(); - private IEnumerable GetSupportedLanguages() - { - if (_languages == null) + private IEnumerable GetSupportedLanguages() { - ImmutableArray languages = _mefServices.GetExports() - .Select(lazy => lazy.Metadata.Language) - .Distinct() - .ToImmutableArray(); - - Interlocked.CompareExchange(ref _languages, languages, null); - } + if (_languages is null) + { + ImmutableArray languages = _mefServices.GetExports() + .Select(lazy => lazy.Metadata.Language) + .Distinct() + .ToImmutableArray(); - return _languages; - } + Interlocked.CompareExchange(ref _languages, languages, null); + } - public bool IsSupported(string languageName) => GetSupportedLanguages().Contains(languageName); + return _languages; + } - public MefLanguageServices GetLanguageServices(string languageName) - { - ImmutableDictionary languageServicesMap = _languageServicesMap; + public bool IsSupported(string languageName) => GetSupportedLanguages().Contains(languageName); - if (!languageServicesMap.TryGetValue(languageName, out MefLanguageServices languageServices)) + public MefLanguageServices GetLanguageServices(string languageName) { - languageServices = ImmutableInterlocked.GetOrAdd( - ref _languageServicesMap, - languageName, - _ => new MefLanguageServices(this, languageName)); - } + ImmutableDictionary languageServicesMap = _languageServicesMap; - if (!languageServices.HasServices) - throw new NotSupportedException($"The language '{languageName}' is not supported."); + if (!languageServicesMap.TryGetValue(languageName, out MefLanguageServices languageServices)) + { + languageServices = ImmutableInterlocked.GetOrAdd( + ref _languageServicesMap, + languageName, + _ => new MefLanguageServices(this, languageName)); + } - return languageServices; - } + if (!languageServices.HasServices) + throw new NotSupportedException($"The language '{languageName}' is not supported."); - internal bool TryGetLanguageServices(string languageName, out MefLanguageServices languageServices) - { - return _languageServicesMap.TryGetValue(languageName, out languageServices); - } + return languageServices; + } - internal TLanguageService GetService(string languageName) - { - return GetLanguageServices(languageName).GetService(); - } + internal bool TryGetLanguageServices(string languageName, out MefLanguageServices languageServices) + { + return _languageServicesMap.TryGetValue(languageName, out languageServices); + } - internal IEnumerable> GetExports() - { - return _mefServices.GetExports(); - } + internal TLanguageService GetService(string languageName) + { + return GetLanguageServices(languageName).GetService(); + } - internal IEnumerable> GetExports() - { - return _mefServices.GetExports(); + internal IEnumerable> GetExports() + { + return _mefServices.GetExports(); + } + + internal IEnumerable> GetExports() + { + return _mefServices.GetExports(); + } } } diff --git a/src/Workspaces.Core/Logging/ConsoleColors.cs b/src/Workspaces.Core/Logging/ConsoleColors.cs index 1583a1619b..2ed44b876a 100644 --- a/src/Workspaces.Core/Logging/ConsoleColors.cs +++ b/src/Workspaces.Core/Logging/ConsoleColors.cs @@ -3,74 +3,75 @@ using System; using System.Diagnostics; -namespace Roslynator; - -[DebuggerDisplay("{DebuggerDisplay,nq}")] -internal readonly struct ConsoleColors : IEquatable +namespace Roslynator { - public static ConsoleColors Cyan { get; } = new(ConsoleColor.Cyan); + [DebuggerDisplay("{DebuggerDisplay,nq}")] + internal readonly struct ConsoleColors : IEquatable + { + public static ConsoleColors Cyan { get; } = new(ConsoleColor.Cyan); - public static ConsoleColors DarkGray { get; } = new(ConsoleColor.DarkGray); + public static ConsoleColors DarkGray { get; } = new(ConsoleColor.DarkGray); - public static ConsoleColors Gray { get; } = new(ConsoleColor.Gray); + public static ConsoleColors Gray { get; } = new(ConsoleColor.Gray); - public static ConsoleColors Green { get; } = new(ConsoleColor.Green); + public static ConsoleColors Green { get; } = new(ConsoleColor.Green); - public static ConsoleColors Magenta { get; } = new(ConsoleColor.Magenta); + public static ConsoleColors Magenta { get; } = new(ConsoleColor.Magenta); - public static ConsoleColors Yellow { get; } = new(ConsoleColor.Yellow); + public static ConsoleColors Yellow { get; } = new(ConsoleColor.Yellow); - public ConsoleColors(ConsoleColor? foreground) - : this(foreground, null) - { - } + public ConsoleColors(ConsoleColor? foreground) + : this(foreground, null) + { + } - public ConsoleColors(ConsoleColor? foreground, ConsoleColor? background) - { - Foreground = foreground; - Background = background; - } + public ConsoleColors(ConsoleColor? foreground, ConsoleColor? background) + { + Foreground = foreground; + Background = background; + } - public ConsoleColor? Foreground { get; } + public ConsoleColor? Foreground { get; } - public ConsoleColor? Background { get; } + public ConsoleColor? Background { get; } - public bool IsDefault => Foreground == null && Background == null; + public bool IsDefault => Foreground is null && Background is null; - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay - { - get + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private string DebuggerDisplay { - return $"{((Foreground != null) ? Foreground.ToString() : "None")} " - + $"{((Background != null) ? Background.ToString() : "None")}"; + get + { + return $"{((Foreground is not null) ? Foreground.ToString() : "None")} " + + $"{((Background is not null) ? Background.ToString() : "None")}"; + } } - } - public override bool Equals(object obj) - { - return obj is ConsoleColors colors - && Equals(colors); - } + public override bool Equals(object obj) + { + return obj is ConsoleColors colors + && Equals(colors); + } - public bool Equals(ConsoleColors other) - { - return Foreground == other.Foreground - && Background == other.Background; - } + public bool Equals(ConsoleColors other) + { + return Foreground == other.Foreground + && Background == other.Background; + } - public override int GetHashCode() - { - return Hash.Combine(Foreground?.GetHashCode() ?? -1, Background?.GetHashCode() ?? -1); - } + public override int GetHashCode() + { + return Hash.Combine(Foreground?.GetHashCode() ?? -1, Background?.GetHashCode() ?? -1); + } - public static bool operator ==(ConsoleColors left, ConsoleColors right) - { - return left.Equals(right); - } + public static bool operator ==(ConsoleColors left, ConsoleColors right) + { + return left.Equals(right); + } - public static bool operator !=(ConsoleColors left, ConsoleColors right) - { - return !(left == right); + public static bool operator !=(ConsoleColors left, ConsoleColors right) + { + return !(left == right); + } } } diff --git a/src/Workspaces.Core/Logging/ConsoleWriter.cs b/src/Workspaces.Core/Logging/ConsoleWriter.cs index 68b5c5f3d6..63e2f88ff4 100644 --- a/src/Workspaces.Core/Logging/ConsoleWriter.cs +++ b/src/Workspaces.Core/Logging/ConsoleWriter.cs @@ -2,95 +2,96 @@ using System; -namespace Roslynator; - -internal sealed class ConsoleWriter : TextWriterWithVerbosity +namespace Roslynator { - public static ConsoleWriter Instance { get; } = new(); - - private ConsoleWriter() : base(Console.Out, Console.Out.FormatProvider) + internal sealed class ConsoleWriter : TextWriterWithVerbosity { - } + public static ConsoleWriter Instance { get; } = new(); - public ConsoleColors Colors - { - get { return new ConsoleColors(Console.ForegroundColor, Console.BackgroundColor); } - set + private ConsoleWriter() : base(Console.Out, Console.Out.FormatProvider) { - if (value.Foreground != null) - Console.ForegroundColor = value.Foreground.Value; - - if (value.Background != null) - Console.BackgroundColor = value.Background.Value; } - } - public void Write(string value, ConsoleColors colors) - { - if (!colors.IsDefault) + public ConsoleColors Colors { - ConsoleColors tmp = Colors; - Colors = colors; - Write(value); - Colors = tmp; + get { return new ConsoleColors(Console.ForegroundColor, Console.BackgroundColor); } + set + { + if (value.Foreground is not null) + Console.ForegroundColor = value.Foreground.Value; + + if (value.Background is not null) + Console.BackgroundColor = value.Background.Value; + } } - else + + public void Write(string value, ConsoleColors colors) { - Write(value); + if (!colors.IsDefault) + { + ConsoleColors tmp = Colors; + Colors = colors; + Write(value); + Colors = tmp; + } + else + { + Write(value); + } } - } - - public void Write(string value, ConsoleColors colors, Verbosity verbosity) - { - WriteIf(ShouldWrite(verbosity), value, colors); - } - public void WriteIf(bool condition, string value, ConsoleColors colors) - { - if (condition) - Write(value, colors); - } - - public void WriteLine(string value, ConsoleColors colors) - { - if (!colors.IsDefault) + public void Write(string value, ConsoleColors colors, Verbosity verbosity) { - ConsoleColors tmp = Colors; - Colors = colors; - Write(value); - Colors = tmp; - WriteLine(); + WriteIf(ShouldWrite(verbosity), value, colors); } - else + + public void WriteIf(bool condition, string value, ConsoleColors colors) { - WriteLine(value); + if (condition) + Write(value, colors); } - } - public void WriteLine(string value, ConsoleColors colors, Verbosity verbosity) - { - WriteLineIf(ShouldWrite(verbosity), value, colors); - } + public void WriteLine(string value, ConsoleColors colors) + { + if (!colors.IsDefault) + { + ConsoleColors tmp = Colors; + Colors = colors; + Write(value); + Colors = tmp; + WriteLine(); + } + else + { + WriteLine(value); + } + } - public override void WriteLine(LogMessage message) - { - if (message.Colors != null) + public void WriteLine(string value, ConsoleColors colors, Verbosity verbosity) { - WriteLineIf(ShouldWrite(message.Verbosity), message.Text, message.Colors.Value); + WriteLineIf(ShouldWrite(verbosity), value, colors); } - else + + public override void WriteLine(LogMessage message) { - base.WriteLine(message); + if (message.Colors is not null) + { + WriteLineIf(ShouldWrite(message.Verbosity), message.Text, message.Colors.Value); + } + else + { + base.WriteLine(message); + } } - } - public void WriteLineIf(bool condition, string value, ConsoleColors colors) - { - if (condition) - WriteLine(value, colors); - } + public void WriteLineIf(bool condition, string value, ConsoleColors colors) + { + if (condition) + WriteLine(value, colors); + } - protected override void Dispose(bool disposing) - { + protected override void Dispose(bool disposing) + { + } } } diff --git a/src/Workspaces.Core/Logging/LogHelpers.cs b/src/Workspaces.Core/Logging/LogHelpers.cs index 0698ed250f..0701b458c4 100644 --- a/src/Workspaces.Core/Logging/LogHelpers.cs +++ b/src/Workspaces.Core/Logging/LogHelpers.cs @@ -16,530 +16,531 @@ using Roslynator.Text; using static Roslynator.Logger; -namespace Roslynator; - -internal static class LogHelpers +namespace Roslynator { - private static readonly SymbolDisplayFormat _symbolDefinitionFormat = SymbolDisplayFormat.CSharpErrorMessageFormat.Update( - typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, - parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut - | SymbolDisplayParameterOptions.IncludeType - | SymbolDisplayParameterOptions.IncludeName - | SymbolDisplayParameterOptions.IncludeDefaultValue, - miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers - | SymbolDisplayMiscellaneousOptions.UseSpecialTypes - | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); - - public static void WriteDiagnostic( - Diagnostic diagnostic, - string baseDirectoryPath = null, - IFormatProvider formatProvider = null, - string indentation = null, - Verbosity verbosity = Verbosity.Diagnostic) - { - string text = DiagnosticFormatter.FormatDiagnostic(diagnostic, baseDirectoryPath, formatProvider); - - Write(indentation, verbosity); - WriteLine(text, diagnostic.Severity.GetColors(), verbosity); - } - - public static void WriteDiagnostics( - ImmutableArray diagnostics, - string baseDirectoryPath = null, - IFormatProvider formatProvider = null, - string indentation = null, - int maxCount = int.MaxValue, - Verbosity verbosity = Verbosity.None) + internal static class LogHelpers { - if (!diagnostics.Any()) - return; - - if (!ShouldWrite(verbosity)) - return; + private static readonly SymbolDisplayFormat _symbolDefinitionFormat = SymbolDisplayFormat.CSharpErrorMessageFormat.Update( + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, + parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut + | SymbolDisplayParameterOptions.IncludeType + | SymbolDisplayParameterOptions.IncludeName + | SymbolDisplayParameterOptions.IncludeDefaultValue, + miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers + | SymbolDisplayMiscellaneousOptions.UseSpecialTypes + | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); + + public static void WriteDiagnostic( + Diagnostic diagnostic, + string baseDirectoryPath = null, + IFormatProvider formatProvider = null, + string indentation = null, + Verbosity verbosity = Verbosity.Diagnostic) + { + string text = DiagnosticFormatter.FormatDiagnostic(diagnostic, baseDirectoryPath, formatProvider); - int count = 0; + Write(indentation, verbosity); + WriteLine(text, diagnostic.Severity.GetColors(), verbosity); + } - foreach (Diagnostic diagnostic in diagnostics.OrderBy(f => f, DiagnosticComparer.IdThenFilePathThenSpanStart)) + public static void WriteDiagnostics( + ImmutableArray diagnostics, + string baseDirectoryPath = null, + IFormatProvider formatProvider = null, + string indentation = null, + int maxCount = int.MaxValue, + Verbosity verbosity = Verbosity.None) { - WriteDiagnostic(diagnostic, baseDirectoryPath, formatProvider, indentation, verbosity); + if (!diagnostics.Any()) + return; - count++; + if (!ShouldWrite(verbosity)) + return; - if (count > maxCount) + int count = 0; + + foreach (Diagnostic diagnostic in diagnostics.OrderBy(f => f, DiagnosticComparer.IdThenFilePathThenSpanStart)) { - int remainingCount = diagnostics.Length - count; + WriteDiagnostic(diagnostic, baseDirectoryPath, formatProvider, indentation, verbosity); + + count++; - if (remainingCount > 0) + if (count > maxCount) { - Write(indentation, verbosity); - WriteLine($"and {remainingCount} more diagnostics", verbosity); + int remainingCount = diagnostics.Length - count; + + if (remainingCount > 0) + { + Write(indentation, verbosity); + WriteLine($"and {remainingCount} more diagnostics", verbosity); + } } } } - } - public static void WriteSpellingDiagnostic( - SpellingDiagnostic diagnostic, - SpellingFixerOptions options, - SourceText sourceText, - string baseDirectoryPath, - string indentation, - Verbosity verbosity) - { - WriteDiagnostic(diagnostic.Diagnostic, baseDirectoryPath, default(IFormatProvider), indentation, verbosity); + public static void WriteSpellingDiagnostic( + SpellingDiagnostic diagnostic, + SpellingFixerOptions options, + SourceText sourceText, + string baseDirectoryPath, + string indentation, + Verbosity verbosity) + { + WriteDiagnostic(diagnostic.Diagnostic, baseDirectoryPath, default(IFormatProvider), indentation, verbosity); - TextSpan span = diagnostic.Span; - TextLineCollection lines = sourceText.Lines; - int lineIndex = lines.IndexOf(span.Start); - TextLine line = lines[lineIndex]; + TextSpan span = diagnostic.Span; + TextLineCollection lines = sourceText.Lines; + int lineIndex = lines.IndexOf(span.Start); + TextLine line = lines[lineIndex]; - int start = Math.Max(0, lineIndex - options.CodeContext); + int start = Math.Max(0, lineIndex - options.CodeContext); - for (int i = start; i < lineIndex; i++) - WriteTextLine(i); + for (int i = start; i < lineIndex; i++) + WriteTextLine(i); - int index = span.Start - line.Span.Start; - string text = line.ToString(); + int index = span.Start - line.Span.Start; + string text = line.ToString(); - Write(indentation, verbosity); - Write(text.Substring(0, index), ConsoleColors.DarkGray, verbosity); - Write(diagnostic.Value, ConsoleColors.Cyan, verbosity); - WriteLine(text.Substring(index + diagnostic.Length), ConsoleColors.DarkGray, verbosity); + Write(indentation, verbosity); + Write(text.Substring(0, index), ConsoleColors.DarkGray, verbosity); + Write(diagnostic.Value, ConsoleColors.Cyan, verbosity); + WriteLine(text.Substring(index + diagnostic.Length), ConsoleColors.DarkGray, verbosity); - int max = Math.Min(lines.Count - 1, lineIndex + options.CodeContext); + int max = Math.Min(lines.Count - 1, lineIndex + options.CodeContext); - for (int i = lineIndex + 1; i <= max; i++) - WriteTextLine(i); + for (int i = lineIndex + 1; i <= max; i++) + WriteTextLine(i); - void WriteTextLine(int i) - { - Write(indentation, verbosity); - WriteLine(lines[i].ToString(), ConsoleColors.DarkGray, verbosity); + void WriteTextLine(int i) + { + Write(indentation, verbosity); + WriteLine(lines[i].ToString(), ConsoleColors.DarkGray, verbosity); + } } - } - public static void WriteLineSpan( - TextSpan span, - int context, - SourceText sourceText, - string indentation, - Verbosity verbosity) - { - TextLineCollection lines = sourceText.Lines; - int lineIndex = lines.IndexOf(span.Start); - TextLine line = lines[lineIndex]; + public static void WriteLineSpan( + TextSpan span, + int context, + SourceText sourceText, + string indentation, + Verbosity verbosity) + { + TextLineCollection lines = sourceText.Lines; + int lineIndex = lines.IndexOf(span.Start); + TextLine line = lines[lineIndex]; - int start = Math.Max(0, lineIndex - context); + int start = Math.Max(0, lineIndex - context); - for (int i = start; i < lineIndex; i++) - WriteTextLine(i); + for (int i = start; i < lineIndex; i++) + WriteTextLine(i); - int index = span.Start - line.Span.Start; - string text = line.ToString(); + int index = span.Start - line.Span.Start; + string text = line.ToString(); - Write(indentation, verbosity); - Write(text.Substring(0, index), verbosity); - Write(text.Substring(index, span.Length), ConsoleColors.Cyan, verbosity); - WriteLine(text.Substring(index + span.Length), verbosity); + Write(indentation, verbosity); + Write(text.Substring(0, index), verbosity); + Write(text.Substring(index, span.Length), ConsoleColors.Cyan, verbosity); + WriteLine(text.Substring(index + span.Length), verbosity); - int max = Math.Min(lines.Count - 1, lineIndex + context); + int max = Math.Min(lines.Count - 1, lineIndex + context); - for (int i = lineIndex + 1; i <= max; i++) - WriteTextLine(i); + for (int i = lineIndex + 1; i <= max; i++) + WriteTextLine(i); - void WriteTextLine(int i) - { - Write(indentation, verbosity); - WriteLine(lines[i].ToString(), ConsoleColors.DarkGray, verbosity); + void WriteTextLine(int i) + { + Write(indentation, verbosity); + WriteLine(lines[i].ToString(), ConsoleColors.DarkGray, verbosity); + } } - } - public static void WriteAnalyzerExceptionDiagnostics(ImmutableArray diagnostics) - { - foreach (string message in diagnostics - .Where(f => f.IsAnalyzerExceptionDiagnostic()) - .Select(f => f.ToString()) - .Distinct()) + public static void WriteAnalyzerExceptionDiagnostics(ImmutableArray diagnostics) { - WriteLine(message, ConsoleColors.Yellow, Verbosity.Diagnostic); + foreach (string message in diagnostics + .Where(f => f.IsAnalyzerExceptionDiagnostic()) + .Select(f => f.ToString()) + .Distinct()) + { + WriteLine(message, ConsoleColors.Yellow, Verbosity.Diagnostic); + } } - } - public static void WriteFixSummary( - IEnumerable fixedDiagnostics, - IEnumerable unfixedDiagnostics, - IEnumerable unfixableDiagnostics, - string baseDirectoryPath = null, - string indentation = null, - bool addEmptyLine = false, - IFormatProvider formatProvider = null, - Verbosity verbosity = Verbosity.None) - { - WriteDiagnosticRules(unfixableDiagnostics, "Unfixable diagnostics:"); - WriteDiagnosticRules(unfixedDiagnostics, "Unfixed diagnostics:"); - WriteDiagnosticRules(fixedDiagnostics, "Fixed diagnostics:"); - - void WriteDiagnosticRules( - IEnumerable diagnostics, - string title) + public static void WriteFixSummary( + IEnumerable fixedDiagnostics, + IEnumerable unfixedDiagnostics, + IEnumerable unfixableDiagnostics, + string baseDirectoryPath = null, + string indentation = null, + bool addEmptyLine = false, + IFormatProvider formatProvider = null, + Verbosity verbosity = Verbosity.None) { - List<(DiagnosticDescriptor descriptor, ImmutableArray diagnostics)> diagnosticsById = diagnostics - .GroupBy(f => f.Descriptor, DiagnosticDescriptorComparer.Id) - .Select(f => (descriptor: f.Key, diagnostics: f.ToImmutableArray())) - .OrderByDescending(f => f.diagnostics.Length) - .ThenBy(f => f.descriptor.Id) - .ToList(); - - if (diagnosticsById.Count > 0) - { - if (addEmptyLine) - WriteLine(verbosity); - - Write(indentation, verbosity); - WriteLine(title, verbosity); - - int maxIdLength = diagnosticsById.Max(f => f.descriptor.Id.Length); - int maxCountLength = diagnosticsById.Max(f => f.diagnostics.Length.ToString("n0").Length); + WriteDiagnosticRules(unfixableDiagnostics, "Unfixable diagnostics:"); + WriteDiagnosticRules(unfixedDiagnostics, "Unfixed diagnostics:"); + WriteDiagnosticRules(fixedDiagnostics, "Fixed diagnostics:"); - foreach ((DiagnosticDescriptor descriptor, ImmutableArray diagnostics2) in diagnosticsById) + void WriteDiagnosticRules( + IEnumerable diagnostics, + string title) + { + List<(DiagnosticDescriptor descriptor, ImmutableArray diagnostics)> diagnosticsById = diagnostics + .GroupBy(f => f.Descriptor, DiagnosticDescriptorComparer.Id) + .Select(f => (descriptor: f.Key, diagnostics: f.ToImmutableArray())) + .OrderByDescending(f => f.diagnostics.Length) + .ThenBy(f => f.descriptor.Id) + .ToList(); + + if (diagnosticsById.Count > 0) { + if (addEmptyLine) + WriteLine(verbosity); + Write(indentation, verbosity); - WriteLine($" {diagnostics2.Length.ToString("n0").PadLeft(maxCountLength)} {descriptor.Id.PadRight(maxIdLength)} {descriptor.Title.ToString(formatProvider)}", verbosity); + WriteLine(title, verbosity); + + int maxIdLength = diagnosticsById.Max(f => f.descriptor.Id.Length); + int maxCountLength = diagnosticsById.Max(f => f.diagnostics.Length.ToString("n0").Length); - if (baseDirectoryPath != null) + foreach ((DiagnosticDescriptor descriptor, ImmutableArray diagnostics2) in diagnosticsById) { - WriteDiagnostics(diagnostics2, baseDirectoryPath: baseDirectoryPath, formatProvider: formatProvider, indentation: indentation + " ", verbosity: verbosity); + Write(indentation, verbosity); + WriteLine($" {diagnostics2.Length.ToString("n0").PadLeft(maxCountLength)} {descriptor.Id.PadRight(maxIdLength)} {descriptor.Title.ToString(formatProvider)}", verbosity); + + if (baseDirectoryPath is not null) + { + WriteDiagnostics(diagnostics2, baseDirectoryPath: baseDirectoryPath, formatProvider: formatProvider, indentation: indentation + " ", verbosity: verbosity); + } } } } } - } - public static void WriteInfiniteLoopSummary(ImmutableArray diagnostics, ImmutableArray previousDiagnostics, Project project, IFormatProvider formatProvider = null) - { - WriteLine(" Infinite loop detected: Reported diagnostics have been previously fixed", ConsoleColors.Yellow, Verbosity.Normal); + public static void WriteInfiniteLoopSummary(ImmutableArray diagnostics, ImmutableArray previousDiagnostics, Project project, IFormatProvider formatProvider = null) + { + WriteLine(" Infinite loop detected: Reported diagnostics have been previously fixed", ConsoleColors.Yellow, Verbosity.Normal); - string baseDirectoryPath = Path.GetDirectoryName(project.FilePath); + string baseDirectoryPath = Path.GetDirectoryName(project.FilePath); - WriteLine(Verbosity.Detailed); - WriteLine(" Diagnostics:", Verbosity.Detailed); - WriteDiagnostics(diagnostics, baseDirectoryPath: baseDirectoryPath, formatProvider: formatProvider, indentation: " ", verbosity: Verbosity.Detailed); - WriteLine(Verbosity.Detailed); - WriteLine(" Previous diagnostics:", Verbosity.Detailed); - WriteDiagnostics(previousDiagnostics, baseDirectoryPath: baseDirectoryPath, formatProvider: formatProvider, indentation: " ", verbosity: Verbosity.Detailed); - WriteLine(Verbosity.Detailed); - } + WriteLine(Verbosity.Detailed); + WriteLine(" Diagnostics:", Verbosity.Detailed); + WriteDiagnostics(diagnostics, baseDirectoryPath: baseDirectoryPath, formatProvider: formatProvider, indentation: " ", verbosity: Verbosity.Detailed); + WriteLine(Verbosity.Detailed); + WriteLine(" Previous diagnostics:", Verbosity.Detailed); + WriteDiagnostics(previousDiagnostics, baseDirectoryPath: baseDirectoryPath, formatProvider: formatProvider, indentation: " ", verbosity: Verbosity.Detailed); + WriteLine(Verbosity.Detailed); + } - public static void WriteFormattedDocuments(ImmutableArray documentIds, Project project, string solutionDirectory) - { - foreach (DocumentId documentId in documentIds) + public static void WriteFormattedDocuments(ImmutableArray documentIds, Project project, string solutionDirectory) { - Document document = project.GetDocument(documentId); - WriteLine($" Format '{PathUtilities.TrimStart(document.FilePath, solutionDirectory)}'", ConsoleColors.DarkGray, Verbosity.Detailed); + foreach (DocumentId documentId in documentIds) + { + Document document = project.GetDocument(documentId); + WriteLine($" Format '{PathUtilities.TrimStart(document.FilePath, solutionDirectory)}'", ConsoleColors.DarkGray, Verbosity.Detailed); + } } - } - public static void WriteUsedAnalyzers( - ImmutableArray analyzers, - Func predicate, - CodeAnalysisOptions options, - ConsoleColors colors, - Verbosity verbosity) - { - if (!analyzers.Any()) - return; + public static void WriteUsedAnalyzers( + ImmutableArray analyzers, + Func predicate, + CodeAnalysisOptions options, + ConsoleColors colors, + Verbosity verbosity) + { + if (!analyzers.Any()) + return; - if (!ShouldWrite(verbosity)) - return; + if (!ShouldWrite(verbosity)) + return; - IEnumerable descriptors = analyzers - .SelectMany(f => f.SupportedDiagnostics) - .Distinct(DiagnosticDescriptorComparer.Id) - .Where(f => options.IsSupportedDiagnosticId(f.Id)); + IEnumerable descriptors = analyzers + .SelectMany(f => f.SupportedDiagnostics) + .Distinct(DiagnosticDescriptorComparer.Id) + .Where(f => options.IsSupportedDiagnosticId(f.Id)); - if (predicate != null) - descriptors = descriptors.Where(predicate); + if (predicate is not null) + descriptors = descriptors.Where(predicate); - foreach (IGrouping grouping in descriptors - .GroupBy(f => f, DiagnosticDescriptorComparer.IdPrefix) - .OrderBy(f => f.Key, DiagnosticDescriptorComparer.IdPrefix)) - { - int count = grouping.Count(); - string prefix = DiagnosticIdPrefix.GetPrefix(grouping.Key.Id); + foreach (IGrouping grouping in descriptors + .GroupBy(f => f, DiagnosticDescriptorComparer.IdPrefix) + .OrderBy(f => f.Key, DiagnosticDescriptorComparer.IdPrefix)) + { + int count = grouping.Count(); + string prefix = DiagnosticIdPrefix.GetPrefix(grouping.Key.Id); - Write($" {count} supported {((count == 1) ? "diagnostic" : "diagnostics")} with ", colors, verbosity); - Write((string.IsNullOrEmpty(prefix)) ? "no prefix" : $"prefix '{prefix}'", colors, verbosity); + Write($" {count} supported {((count == 1) ? "diagnostic" : "diagnostics")} with ", colors, verbosity); + Write((string.IsNullOrEmpty(prefix)) ? "no prefix" : $"prefix '{prefix}'", colors, verbosity); - using (IEnumerator en = grouping - .OrderBy(f => f.Id) - .GetEnumerator()) - { - if (en.MoveNext()) + using (IEnumerator en = grouping + .OrderBy(f => f.Id) + .GetEnumerator()) { - Write(" (", colors, verbosity); - - while (true) + if (en.MoveNext()) { - Write(en.Current.Id, colors, verbosity); + Write(" (", colors, verbosity); - if (en.MoveNext()) + while (true) { - Write(", ", colors, verbosity); + Write(en.Current.Id, colors, verbosity); + + if (en.MoveNext()) + { + Write(", ", colors, verbosity); + } + else + { + break; + } } - else - { - break; - } - } - Write(")", colors, verbosity); + Write(")", colors, verbosity); + } } - } - WriteLine("", colors, verbosity); + WriteLine("", colors, verbosity); + } } - } - public static void WriteUsedFixers( - ImmutableArray fixers, - CodeAnalysisOptions options, - ConsoleColors colors, - Verbosity verbosity) - { - if (!ShouldWrite(verbosity)) - return; - - foreach (IGrouping grouping in fixers - .SelectMany(f => f.FixableDiagnosticIds) - .Distinct() - .Where(f => options.IsSupportedDiagnosticId(f)) - .GroupBy(f => f, DiagnosticIdComparer.Prefix) - .OrderBy(f => f.Key, DiagnosticIdComparer.Prefix)) + public static void WriteUsedFixers( + ImmutableArray fixers, + CodeAnalysisOptions options, + ConsoleColors colors, + Verbosity verbosity) { - int count = grouping.Count(); - string prefix = DiagnosticIdPrefix.GetPrefix(grouping.Key); + if (!ShouldWrite(verbosity)) + return; + + foreach (IGrouping grouping in fixers + .SelectMany(f => f.FixableDiagnosticIds) + .Distinct() + .Where(f => options.IsSupportedDiagnosticId(f)) + .GroupBy(f => f, DiagnosticIdComparer.Prefix) + .OrderBy(f => f.Key, DiagnosticIdComparer.Prefix)) + { + int count = grouping.Count(); + string prefix = DiagnosticIdPrefix.GetPrefix(grouping.Key); - Write($" {count} fixable {((count == 1) ? "diagnostic" : "diagnostics")} with ", colors, verbosity); - Write((string.IsNullOrEmpty(prefix)) ? "no prefix" : $"prefix '{prefix}'", colors, verbosity); + Write($" {count} fixable {((count == 1) ? "diagnostic" : "diagnostics")} with ", colors, verbosity); + Write((string.IsNullOrEmpty(prefix)) ? "no prefix" : $"prefix '{prefix}'", colors, verbosity); - using (IEnumerator en = grouping - .OrderBy(f => f) - .GetEnumerator()) - { - if (en.MoveNext()) + using (IEnumerator en = grouping + .OrderBy(f => f) + .GetEnumerator()) { - Write(" (", colors, verbosity); - - while (true) + if (en.MoveNext()) { - Write(en.Current, colors, verbosity); + Write(" (", colors, verbosity); - if (en.MoveNext()) + while (true) { - Write(", ", colors, verbosity); + Write(en.Current, colors, verbosity); + + if (en.MoveNext()) + { + Write(", ", colors, verbosity); + } + else + { + break; + } } - else - { - break; - } - } - Write(")", colors, verbosity); + Write(")", colors, verbosity); + } } + + WriteLine("", colors, verbosity); } + } - WriteLine("", colors, verbosity); + public static void WriteMultipleFixersSummary(string diagnosticId, CodeFixProvider fixer1, CodeFixProvider fixer2) + { + WriteLine($" Diagnostic '{diagnosticId}' is fixable with multiple fixers", ConsoleColors.Yellow, Verbosity.Diagnostic); + WriteLine($" Fixer 1: '{fixer1.GetType().FullName}'", ConsoleColors.Yellow, Verbosity.Diagnostic); + WriteLine($" Fixer 2: '{fixer2.GetType().FullName}'", ConsoleColors.Yellow, Verbosity.Diagnostic); } - } - public static void WriteMultipleFixersSummary(string diagnosticId, CodeFixProvider fixer1, CodeFixProvider fixer2) - { - WriteLine($" Diagnostic '{diagnosticId}' is fixable with multiple fixers", ConsoleColors.Yellow, Verbosity.Diagnostic); - WriteLine($" Fixer 1: '{fixer1.GetType().FullName}'", ConsoleColors.Yellow, Verbosity.Diagnostic); - WriteLine($" Fixer 2: '{fixer2.GetType().FullName}'", ConsoleColors.Yellow, Verbosity.Diagnostic); - } + public static void WriteMultipleOperationsSummary(CodeAction fix) + { + WriteLine(" Code action has multiple operations", ConsoleColors.Yellow, Verbosity.Diagnostic); + WriteLine($" Title: {fix.Title}", ConsoleColors.Yellow, Verbosity.Diagnostic); + WriteLine($" EquivalenceKey: {fix.EquivalenceKey}", ConsoleColors.Yellow, Verbosity.Diagnostic); + } - public static void WriteMultipleOperationsSummary(CodeAction fix) - { - WriteLine(" Code action has multiple operations", ConsoleColors.Yellow, Verbosity.Diagnostic); - WriteLine($" Title: {fix.Title}", ConsoleColors.Yellow, Verbosity.Diagnostic); - WriteLine($" EquivalenceKey: {fix.EquivalenceKey}", ConsoleColors.Yellow, Verbosity.Diagnostic); - } + public static void WriteSymbolDefinition( + ISymbol symbol, + string baseDirectoryPath = null, + string indentation = null, + Verbosity verbosity = Verbosity.Diagnostic) + { + StringBuilder sb = StringBuilderCache.GetInstance(); - public static void WriteSymbolDefinition( - ISymbol symbol, - string baseDirectoryPath = null, - string indentation = null, - Verbosity verbosity = Verbosity.Diagnostic) - { - StringBuilder sb = StringBuilderCache.GetInstance(); + sb.Append(indentation); + DiagnosticFormatter.FormatLocation(symbol.Locations[0], baseDirectoryPath, ref sb); + sb.Append(GetSymbolTitle(symbol)); - sb.Append(indentation); - DiagnosticFormatter.FormatLocation(symbol.Locations[0], baseDirectoryPath, ref sb); - sb.Append(GetSymbolTitle(symbol)); + if (symbol.IsKind(SymbolKind.Parameter, SymbolKind.TypeParameter)) + { + sb.Append(" '"); + sb.Append(symbol.Name); + sb.Append("': "); - if (symbol.IsKind(SymbolKind.Parameter, SymbolKind.TypeParameter)) - { - sb.Append(" '"); - sb.Append(symbol.Name); - sb.Append("': "); + if ((symbol.ContainingSymbol as IMethodSymbol)?.MethodKind == MethodKind.LambdaMethod) + { + sb.Append("anonymous function"); + } + else + { + Debug.Assert(symbol.ContainingSymbol.IsKind(SymbolKind.NamedType, SymbolKind.Method, SymbolKind.Property), symbol.Kind.ToString()); - if ((symbol.ContainingSymbol as IMethodSymbol)?.MethodKind == MethodKind.LambdaMethod) - { - sb.Append("anonymous function"); + sb.Append(symbol.ContainingSymbol.ToDisplayString(_symbolDefinitionFormat)); + } } else { - Debug.Assert(symbol.ContainingSymbol.IsKind(SymbolKind.NamedType, SymbolKind.Method, SymbolKind.Property), symbol.Kind.ToString()); - - sb.Append(symbol.ContainingSymbol.ToDisplayString(_symbolDefinitionFormat)); + sb.Append(": "); + sb.Append(symbol.ToDisplayString(_symbolDefinitionFormat)); } - } - else - { - sb.Append(": "); - sb.Append(symbol.ToDisplayString(_symbolDefinitionFormat)); - } - WriteLine(StringBuilderCache.GetStringAndFree(sb), ConsoleColors.Cyan, verbosity); + WriteLine(StringBuilderCache.GetStringAndFree(sb), ConsoleColors.Cyan, verbosity); - static string GetSymbolTitle(ISymbol symbol) - { - switch (symbol.Kind) + static string GetSymbolTitle(ISymbol symbol) { - case SymbolKind.Event: - { - return "event"; - } - case SymbolKind.Field: - { - return (symbol.ContainingType.TypeKind == TypeKind.Enum) ? "enum field" : "field"; - } - case SymbolKind.Local: - { - return "local"; - } - case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; - - switch (methodSymbol.MethodKind) + switch (symbol.Kind) + { + case SymbolKind.Event: + { + return "event"; + } + case SymbolKind.Field: { - case MethodKind.Ordinary: - return "method"; - case MethodKind.LocalFunction: - return "local function"; + return (symbol.ContainingType.TypeKind == TypeKind.Enum) ? "enum field" : "field"; } + case SymbolKind.Local: + { + return "local"; + } + case SymbolKind.Method: + { + var methodSymbol = (IMethodSymbol)symbol; - Debug.Fail(methodSymbol.MethodKind.ToString()); - break; - } - case SymbolKind.NamedType: - { - var typeSymbol = (INamedTypeSymbol)symbol; + switch (methodSymbol.MethodKind) + { + case MethodKind.Ordinary: + return "method"; + case MethodKind.LocalFunction: + return "local function"; + } - switch (typeSymbol.TypeKind) + Debug.Fail(methodSymbol.MethodKind.ToString()); + break; + } + case SymbolKind.NamedType: { - 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"; + 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 SymbolKind.Parameter: + { + return "parameter"; + } + case SymbolKind.Property: + { + return (((IPropertySymbol)symbol).IsIndexer) ? "indexer" : "property"; + } + case SymbolKind.TypeParameter: + { + return "type parameter"; + } + } - Debug.Fail(typeSymbol.TypeKind.ToString()); - break; - } - case SymbolKind.Parameter: - { - return "parameter"; - } - case SymbolKind.Property: - { - return (((IPropertySymbol)symbol).IsIndexer) ? "indexer" : "property"; - } - case SymbolKind.TypeParameter: - { - return "type parameter"; - } + Debug.Fail(symbol.Kind.ToString()); + return symbol.Kind.ToString(); } - - Debug.Fail(symbol.Kind.ToString()); - return symbol.Kind.ToString(); } - } - - public static int WriteCompilerErrors( - ImmutableArray diagnostics, - string baseDirectoryPath = null, - ImmutableHashSet ignoredCompilerDiagnosticIds = null, - IFormatProvider formatProvider = null, - string indentation = null, - int limit = 1000) - { - ignoredCompilerDiagnosticIds ??= ImmutableHashSet.Empty; - using (IEnumerator en = diagnostics - .Where(f => f.Severity == DiagnosticSeverity.Error - && !ignoredCompilerDiagnosticIds.Contains(f.Id)) - .GetEnumerator()) + public static int WriteCompilerErrors( + ImmutableArray diagnostics, + string baseDirectoryPath = null, + ImmutableHashSet ignoredCompilerDiagnosticIds = null, + IFormatProvider formatProvider = null, + string indentation = null, + int limit = 1000) { - if (en.MoveNext()) - { - const int maxCount = 10; - - int count = 0; + ignoredCompilerDiagnosticIds ??= ImmutableHashSet.Empty; - do + using (IEnumerator en = diagnostics + .Where(f => f.Severity == DiagnosticSeverity.Error + && !ignoredCompilerDiagnosticIds.Contains(f.Id)) + .GetEnumerator()) + { + if (en.MoveNext()) { - count++; + const int maxCount = 10; - if (count <= maxCount) - { - WriteDiagnostic( - en.Current, - baseDirectoryPath: baseDirectoryPath, - formatProvider: formatProvider, - indentation: indentation, - verbosity: Verbosity.Normal); - } - else + int count = 0; + + do { - break; + count++; + + if (count <= maxCount) + { + WriteDiagnostic( + en.Current, + baseDirectoryPath: baseDirectoryPath, + formatProvider: formatProvider, + indentation: indentation, + verbosity: Verbosity.Normal); + } + else + { + break; + } } - } - while (en.MoveNext()); + while (en.MoveNext()); - count = 0; + count = 0; - var plus = false; + var plus = false; - while (en.MoveNext()) - { - count++; + while (en.MoveNext()) + { + count++; - if (count == limit) + if (count == limit) + { + plus = true; + break; + } + } + + if (count > maxCount) { - plus = true; - break; + Write(indentation); + WriteLine($"and {count}{((plus) ? "+" : "")} more errors", verbosity: Verbosity.Normal); } - } - if (count > maxCount) - { - Write(indentation); - WriteLine($"and {count}{((plus) ? "+" : "")} more errors", verbosity: Verbosity.Normal); + return count; } - - return count; } - } - return 0; + return 0; + } } } diff --git a/src/Workspaces.Core/Logging/Logger.cs b/src/Workspaces.Core/Logging/Logger.cs index 79b9814bd8..e9090360f9 100644 --- a/src/Workspaces.Core/Logging/Logger.cs +++ b/src/Workspaces.Core/Logging/Logger.cs @@ -2,314 +2,315 @@ using System; -namespace Roslynator; - -internal static class Logger +namespace Roslynator { - public static ConsoleWriter ConsoleOut { get; } = ConsoleWriter.Instance; - - public static TextWriterWithVerbosity Out { get; set; } - - public static void Write(char value) + internal static class Logger { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static ConsoleWriter ConsoleOut { get; } = ConsoleWriter.Instance; - public static void Write(char value, int repeatCount) - { - for (int i = 0; i < repeatCount; i++) + public static TextWriterWithVerbosity Out { get; set; } + + public static void Write(char value) { ConsoleOut.Write(value); Out?.Write(value); } - } - public static void Write(char value, int repeatCount, Verbosity verbosity) - { - for (int i = 0; i < repeatCount; i++) + public static void Write(char value, int repeatCount) { - ConsoleOut.Write(value, verbosity); - Out?.Write(value, verbosity); + for (int i = 0; i < repeatCount; i++) + { + ConsoleOut.Write(value); + Out?.Write(value); + } } - } - public static void Write(char[] buffer) - { - ConsoleOut.Write(buffer); - Out?.Write(buffer); - } + public static void Write(char value, int repeatCount, Verbosity verbosity) + { + for (int i = 0; i < repeatCount; i++) + { + ConsoleOut.Write(value, verbosity); + Out?.Write(value, verbosity); + } + } - public static void Write(char[] buffer, int index, int count) - { - ConsoleOut.Write(buffer, index, count); - Out?.Write(buffer, index, count); - } + public static void Write(char[] buffer) + { + ConsoleOut.Write(buffer); + Out?.Write(buffer); + } - public static void Write(bool value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(char[] buffer, int index, int count) + { + ConsoleOut.Write(buffer, index, count); + Out?.Write(buffer, index, count); + } - public static void Write(int value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(bool value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(uint value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(int value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(long value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(uint value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(ulong value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(long value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(float value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(ulong value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(double value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(float value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(decimal value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(double value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(string value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void Write(decimal value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(string value, Verbosity verbosity) - { - ConsoleOut.Write(value, verbosity: verbosity); - Out?.Write(value, verbosity: verbosity); - } + public static void Write(string value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void Write(string value, ConsoleColors colors) - { - ConsoleOut.Write(value, colors); - Out?.Write(value); - } + public static void Write(string value, Verbosity verbosity) + { + ConsoleOut.Write(value, verbosity: verbosity); + Out?.Write(value, verbosity: verbosity); + } - public static void Write(string value, ConsoleColors colors, Verbosity verbosity) - { - ConsoleOut.Write(value, colors, verbosity: verbosity); - Out?.Write(value, verbosity: verbosity); - } + public static void Write(string value, ConsoleColors colors) + { + ConsoleOut.Write(value, colors); + Out?.Write(value); + } - public static void WriteIf(bool condition, string value) - { - ConsoleOut.WriteIf(condition, value); - Out?.WriteIf(condition, value); - } + public static void Write(string value, ConsoleColors colors, Verbosity verbosity) + { + ConsoleOut.Write(value, colors, verbosity: verbosity); + Out?.Write(value, verbosity: verbosity); + } - public static void WriteIf(bool condition, string value, ConsoleColors colors) - { - ConsoleOut.WriteIf(condition, value, colors); - Out?.WriteIf(condition, value); - } + public static void WriteIf(bool condition, string value) + { + ConsoleOut.WriteIf(condition, value); + Out?.WriteIf(condition, value); + } - public static void Write(object value) - { - ConsoleOut.Write(value); - Out?.Write(value); - } + public static void WriteIf(bool condition, string value, ConsoleColors colors) + { + ConsoleOut.WriteIf(condition, value, colors); + Out?.WriteIf(condition, value); + } - public static void WriteLine() - { - ConsoleOut.WriteLine(); - Out?.WriteLine(); - } + public static void Write(object value) + { + ConsoleOut.Write(value); + Out?.Write(value); + } - public static void WriteLine(Verbosity verbosity) - { - ConsoleOut.WriteLine(verbosity); - Out?.WriteLine(verbosity); - } + public static void WriteLine() + { + ConsoleOut.WriteLine(); + Out?.WriteLine(); + } - public static void WriteLineIf(bool condition) - { - ConsoleOut.WriteLineIf(condition); - Out?.WriteLineIf(condition); - } + public static void WriteLine(Verbosity verbosity) + { + ConsoleOut.WriteLine(verbosity); + Out?.WriteLine(verbosity); + } - public static void WriteLine(char value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLineIf(bool condition) + { + ConsoleOut.WriteLineIf(condition); + Out?.WriteLineIf(condition); + } - public static void WriteLine(char[] buffer) - { - ConsoleOut.WriteLine(buffer); - Out?.WriteLine(buffer); - } + public static void WriteLine(char value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(char[] buffer, int index, int count) - { - ConsoleOut.WriteLine(buffer, index, count); - Out?.WriteLine(buffer, index, count); - } + public static void WriteLine(char[] buffer) + { + ConsoleOut.WriteLine(buffer); + Out?.WriteLine(buffer); + } - public static void WriteLine(bool value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(char[] buffer, int index, int count) + { + ConsoleOut.WriteLine(buffer, index, count); + Out?.WriteLine(buffer, index, count); + } - public static void WriteLine(int value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(bool value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(uint value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(int value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(long value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(uint value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(ulong value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(long value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(float value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(ulong value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(double value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(float value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(decimal value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(double value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(string value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLine(decimal value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(string value, Verbosity verbosity) - { - ConsoleOut.WriteLine(value, verbosity: verbosity); - Out?.WriteLine(value, verbosity: verbosity); - } + public static void WriteLine(string value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteLine(string value, ConsoleColors colors) - { - ConsoleOut.WriteLine(value, colors); - Out?.WriteLine(value); - } + public static void WriteLine(string value, Verbosity verbosity) + { + ConsoleOut.WriteLine(value, verbosity: verbosity); + Out?.WriteLine(value, verbosity: verbosity); + } - public static void WriteLine(string value, ConsoleColors colors, Verbosity verbosity) - { - ConsoleOut.WriteLine(value, colors, verbosity: verbosity); - Out?.WriteLine(value, verbosity: verbosity); - } + public static void WriteLine(string value, ConsoleColors colors) + { + ConsoleOut.WriteLine(value, colors); + Out?.WriteLine(value); + } - public static void WriteLine(LogMessage message) - { - ConsoleOut.WriteLine(message); - Out?.WriteLine(message); - } + public static void WriteLine(string value, ConsoleColors colors, Verbosity verbosity) + { + ConsoleOut.WriteLine(value, colors, verbosity: verbosity); + Out?.WriteLine(value, verbosity: verbosity); + } - public static void WriteLineIf(bool condition, string value) - { - ConsoleOut.WriteLineIf(condition, value); - Out?.WriteLineIf(condition, value); - } + public static void WriteLine(LogMessage message) + { + ConsoleOut.WriteLine(message); + Out?.WriteLine(message); + } - public static void WriteLineIf(bool condition, string value, ConsoleColors colors) - { - ConsoleOut.WriteLineIf(condition, value, colors); - Out?.WriteLineIf(condition, value); - } + public static void WriteLineIf(bool condition, string value) + { + ConsoleOut.WriteLineIf(condition, value); + Out?.WriteLineIf(condition, value); + } - public static void WriteLine(object value) - { - ConsoleOut.WriteLine(value); - Out?.WriteLine(value); - } + public static void WriteLineIf(bool condition, string value, ConsoleColors colors) + { + ConsoleOut.WriteLineIf(condition, value, colors); + Out?.WriteLineIf(condition, value); + } - public static void WriteError( - Exception exception, - ConsoleColor color = ConsoleColor.Red, - Verbosity verbosity = Verbosity.Quiet) - { - WriteError(exception, exception.Message, color, verbosity); - } + public static void WriteLine(object value) + { + ConsoleOut.WriteLine(value); + Out?.WriteLine(value); + } - public static void WriteError( - Exception exception, - string message, - ConsoleColor color = ConsoleColor.Red, - Verbosity verbosity = Verbosity.Quiet) - { - var colors = new ConsoleColors(color); + public static void WriteError( + Exception exception, + ConsoleColor color = ConsoleColor.Red, + Verbosity verbosity = Verbosity.Quiet) + { + WriteError(exception, exception.Message, color, verbosity); + } + + public static void WriteError( + Exception exception, + string message, + ConsoleColor color = ConsoleColor.Red, + Verbosity verbosity = Verbosity.Quiet) + { + var colors = new ConsoleColors(color); - WriteLine(exception.Message, colors, verbosity); + WriteLine(exception.Message, colors, verbosity); - if (exception is AggregateException aggregateException) - WriteInnerExceptions(aggregateException, ""); + if (exception is AggregateException aggregateException) + WriteInnerExceptions(aggregateException, ""); #if DEBUG - WriteLine(exception.ToString()); + WriteLine(exception.ToString()); #endif - void WriteInnerExceptions(AggregateException aggregateException, string indent) - { - indent += " "; - - foreach (Exception innerException in aggregateException.InnerExceptions) + void WriteInnerExceptions(AggregateException aggregateException, string indent) { - WriteLine(indent + "Inner exception: " + innerException.Message, colors, verbosity); + indent += " "; - if (innerException is AggregateException aggregateException2) - WriteInnerExceptions(aggregateException2, indent); - } + foreach (Exception innerException in aggregateException.InnerExceptions) + { + WriteLine(indent + "Inner exception: " + innerException.Message, colors, verbosity); - indent = indent.Substring(2); + if (innerException is AggregateException aggregateException2) + WriteInnerExceptions(aggregateException2, indent); + } + + indent = indent.Substring(2); + } } - } - public static bool ShouldWrite(Verbosity verbosity) - { - return verbosity <= ConsoleOut.Verbosity - || (Out != null && verbosity <= Out.Verbosity); + public static bool ShouldWrite(Verbosity verbosity) + { + return verbosity <= ConsoleOut.Verbosity + || (Out is not null && verbosity <= Out.Verbosity); + } } } diff --git a/src/Workspaces.Core/MemberNameGenerator.cs b/src/Workspaces.Core/MemberNameGenerator.cs index 77ec607e91..41458d464f 100644 --- a/src/Workspaces.Core/MemberNameGenerator.cs +++ b/src/Workspaces.Core/MemberNameGenerator.cs @@ -9,121 +9,122 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; -namespace Roslynator; - -internal static class MemberNameGenerator +namespace Roslynator { - public static async Task EnsureUniqueMemberNameAsync( - string baseName, - ISymbol memberSymbol, - Solution solution, - NameGenerator nameGenerator, - bool isCaseSensitive = true, - CancellationToken cancellationToken = default) + internal static class MemberNameGenerator { - if (memberSymbol == null) - throw new ArgumentNullException(nameof(memberSymbol)); - - if (solution == null) - throw new ArgumentNullException(nameof(solution)); + public static async Task EnsureUniqueMemberNameAsync( + string baseName, + ISymbol memberSymbol, + Solution solution, + NameGenerator nameGenerator, + bool isCaseSensitive = true, + CancellationToken cancellationToken = default) + { + if (memberSymbol is null) + throw new ArgumentNullException(nameof(memberSymbol)); - if (nameGenerator == null) - throw new ArgumentNullException(nameof(nameGenerator)); + if (solution is null) + throw new ArgumentNullException(nameof(solution)); - HashSet reservedNames = await GetReservedNamesAsync(memberSymbol, solution, isCaseSensitive, cancellationToken).ConfigureAwait(false); + if (nameGenerator is null) + throw new ArgumentNullException(nameof(nameGenerator)); - return nameGenerator.EnsureUniqueName(baseName, reservedNames); - } + HashSet reservedNames = await GetReservedNamesAsync(memberSymbol, solution, isCaseSensitive, cancellationToken).ConfigureAwait(false); - public static async Task IsUniqueMemberNameAsync( - string name, - ISymbol memberSymbol, - Solution solution, - bool isCaseSensitive = true, - CancellationToken cancellationToken = default) - { - if (memberSymbol == null) - throw new ArgumentNullException(nameof(memberSymbol)); + return nameGenerator.EnsureUniqueName(baseName, reservedNames); + } - if (solution == null) - throw new ArgumentNullException(nameof(solution)); + public static async Task IsUniqueMemberNameAsync( + string name, + ISymbol memberSymbol, + Solution solution, + bool isCaseSensitive = true, + CancellationToken cancellationToken = default) + { + if (memberSymbol is null) + throw new ArgumentNullException(nameof(memberSymbol)); - HashSet reservedNames = await GetReservedNamesAsync(memberSymbol, solution, isCaseSensitive, cancellationToken).ConfigureAwait(false); + if (solution is null) + throw new ArgumentNullException(nameof(solution)); - return !reservedNames.Contains(name); - } + HashSet reservedNames = await GetReservedNamesAsync(memberSymbol, solution, isCaseSensitive, cancellationToken).ConfigureAwait(false); - private static async Task> GetReservedNamesAsync( - ISymbol memberSymbol, - Solution solution, - bool isCaseSensitive = true, - CancellationToken cancellationToken = default) - { - HashSet reservedNames = GetMemberNames(memberSymbol, isCaseSensitive); + return !reservedNames.Contains(name); + } - foreach (ReferencedSymbol referencedSymbol in await SymbolFinder.FindReferencesAsync(memberSymbol, solution, cancellationToken).ConfigureAwait(false)) + private static async Task> GetReservedNamesAsync( + ISymbol memberSymbol, + Solution solution, + bool isCaseSensitive = true, + CancellationToken cancellationToken = default) { - foreach (ReferenceLocation referenceLocation in referencedSymbol.Locations) + HashSet reservedNames = GetMemberNames(memberSymbol, isCaseSensitive); + + foreach (ReferencedSymbol referencedSymbol in await SymbolFinder.FindReferencesAsync(memberSymbol, solution, cancellationToken).ConfigureAwait(false)) { - if (!referenceLocation.IsImplicit - && !referenceLocation.IsCandidateLocation) + foreach (ReferenceLocation referenceLocation in referencedSymbol.Locations) { - SemanticModel semanticModel = await referenceLocation.Document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - - foreach (ISymbol symbol in semanticModel.LookupSymbols(referenceLocation.Location.SourceSpan.Start)) + if (!referenceLocation.IsImplicit + && !referenceLocation.IsCandidateLocation) { - if (!SymbolEqualityComparer.Default.Equals(memberSymbol, symbol)) - reservedNames.Add(symbol.Name); + SemanticModel semanticModel = await referenceLocation.Document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + + foreach (ISymbol symbol in semanticModel.LookupSymbols(referenceLocation.Location.SourceSpan.Start)) + { + if (!SymbolEqualityComparer.Default.Equals(memberSymbol, symbol)) + reservedNames.Add(symbol.Name); + } } } } - } - return reservedNames; - } + return reservedNames; + } - private static HashSet GetMemberNames(ISymbol memberSymbol, bool isCaseSensitive = true) - { - INamedTypeSymbol containingType = memberSymbol.ContainingType; + private static HashSet GetMemberNames(ISymbol memberSymbol, bool isCaseSensitive = true) + { + INamedTypeSymbol containingType = memberSymbol.ContainingType; - Debug.Assert(containingType != null); + Debug.Assert(containingType is not null); - if (containingType != null) - { - IEnumerable memberNames = containingType - .GetMembers() - .Where(f => !SymbolEqualityComparer.Default.Equals(memberSymbol, f)) - .Select(f => f.Name); + if (containingType is not null) + { + IEnumerable memberNames = containingType + .GetMembers() + .Where(f => !SymbolEqualityComparer.Default.Equals(memberSymbol, f)) + .Select(f => f.Name); - return CreateHashSet(memberNames, isCaseSensitive); - } - else - { - return CreateHashSet(isCaseSensitive); + return CreateHashSet(memberNames, isCaseSensitive); + } + else + { + return CreateHashSet(isCaseSensitive); + } } - } - private static HashSet CreateHashSet(IEnumerable names, bool isCaseSensitive = true) - { - if (isCaseSensitive) - { - return new HashSet(names, NameGenerator.OrdinalComparer); - } - else + private static HashSet CreateHashSet(IEnumerable names, bool isCaseSensitive = true) { - return new HashSet(names, NameGenerator.OrdinalIgnoreCaseComparer); + if (isCaseSensitive) + { + return new HashSet(names, NameGenerator.OrdinalComparer); + } + else + { + return new HashSet(names, NameGenerator.OrdinalIgnoreCaseComparer); + } } - } - private static HashSet CreateHashSet(bool isCaseSensitive = true) - { - if (isCaseSensitive) - { - return new HashSet(NameGenerator.OrdinalComparer); - } - else + private static HashSet CreateHashSet(bool isCaseSensitive = true) { - return new HashSet(NameGenerator.OrdinalIgnoreCaseComparer); + if (isCaseSensitive) + { + return new HashSet(NameGenerator.OrdinalComparer); + } + else + { + return new HashSet(NameGenerator.OrdinalIgnoreCaseComparer); + } } } } diff --git a/src/Workspaces.Core/PathUtilities.cs b/src/Workspaces.Core/PathUtilities.cs index 317113ffdd..afc40e343d 100644 --- a/src/Workspaces.Core/PathUtilities.cs +++ b/src/Workspaces.Core/PathUtilities.cs @@ -4,34 +4,35 @@ using System.IO; using Microsoft.CodeAnalysis; -namespace Roslynator; - -internal static class PathUtilities +namespace Roslynator { - internal static string TrimStart(string path, string basePath, bool trimLeadingDirectorySeparator = true) + internal static class PathUtilities { - if (basePath != null) + internal static string TrimStart(string path, string basePath, bool trimLeadingDirectorySeparator = true) { - if (string.Equals(path, basePath, StringComparison.Ordinal)) - return Path.GetFileName(path); - - if (path.StartsWith(basePath)) + if (basePath is not null) { - int length = basePath.Length; + if (string.Equals(path, basePath, StringComparison.Ordinal)) + return Path.GetFileName(path); - if (trimLeadingDirectorySeparator) + if (path.StartsWith(basePath)) { - while (length < path.Length - && path[length] == Path.DirectorySeparatorChar) + int length = basePath.Length; + + if (trimLeadingDirectorySeparator) { - length++; - } + while (length < path.Length + && path[length] == Path.DirectorySeparatorChar) + { + length++; + } - return path.Remove(0, length); + return path.Remove(0, length); + } } } - } - return path; + return path; + } } } diff --git a/src/Workspaces.Core/ProjectOrSolution.cs b/src/Workspaces.Core/ProjectOrSolution.cs index f7e0e13a97..7b59ab4464 100644 --- a/src/Workspaces.Core/ProjectOrSolution.cs +++ b/src/Workspaces.Core/ProjectOrSolution.cs @@ -3,98 +3,99 @@ using System; using Microsoft.CodeAnalysis; -namespace Roslynator; - -internal readonly struct ProjectOrSolution : IEquatable +namespace Roslynator { - private readonly Project _project; - private readonly Solution _solution; - - internal ProjectOrSolution(Project project) + internal readonly struct ProjectOrSolution : IEquatable { - _project = project ?? throw new ArgumentNullException(nameof(project)); - _solution = null; - } + private readonly Project _project; + private readonly Solution _solution; - internal ProjectOrSolution(Solution solution) - { - _solution = solution ?? throw new ArgumentNullException(nameof(solution)); - _project = null; - } + internal ProjectOrSolution(Project project) + { + _project = project ?? throw new ArgumentNullException(nameof(project)); + _solution = null; + } - public bool IsProject => _project != null; + internal ProjectOrSolution(Solution solution) + { + _solution = solution ?? throw new ArgumentNullException(nameof(solution)); + _project = null; + } - public bool IsSolution => _solution != null; + public bool IsProject => _project is not null; - public bool IsDefault => _project == null && _solution == null; + public bool IsSolution => _solution is not null; - public string FilePath => (IsProject) ? _project.FilePath : _solution?.FilePath; + public bool IsDefault => _project is null && _solution is null; - public VersionStamp Version => (IsProject) ? _project.Version : (_solution?.Version ?? default); + public string FilePath => (IsProject) ? _project.FilePath : _solution?.FilePath; - public Workspace Workspace => (IsProject) ? _project.Solution.Workspace : _solution?.Workspace; + public VersionStamp Version => (IsProject) ? _project.Version : (_solution?.Version ?? default); - public Project AsProject() => _project; + public Workspace Workspace => (IsProject) ? _project.Solution.Workspace : _solution?.Workspace; - public Solution AsSolution() => _solution; + public Project AsProject() => _project; - public override string ToString() - { - return (_project ?? (object)_solution)?.ToString(); - } + public Solution AsSolution() => _solution; - public override bool Equals(object obj) - { - return obj is ProjectOrSolution other - && Equals(other); - } - - public bool Equals(ProjectOrSolution other) - { - if (_project != null) + public override string ToString() { - return _project == other._project; + return (_project ?? (object)_solution)?.ToString(); } - else if (_solution != null) + + public override bool Equals(object obj) { - return _solution == other._solution; + return obj is ProjectOrSolution other + && Equals(other); } - return false; - } + public bool Equals(ProjectOrSolution other) + { + if (_project is not null) + { + return _project == other._project; + } + else if (_solution is not null) + { + return _solution == other._solution; + } + + return false; + } - public override int GetHashCode() - { - return (_project ?? (object)_solution)?.GetHashCode() ?? 0; - } + public override int GetHashCode() + { + return (_project ?? (object)_solution)?.GetHashCode() ?? 0; + } - public static bool operator ==(in ProjectOrSolution left, in ProjectOrSolution right) - { - return left.Equals(right); - } + public static bool operator ==(in ProjectOrSolution left, in ProjectOrSolution right) + { + return left.Equals(right); + } - public static bool operator !=(in ProjectOrSolution left, in ProjectOrSolution right) - { - return !left.Equals(right); - } + public static bool operator !=(in ProjectOrSolution left, in ProjectOrSolution right) + { + return !left.Equals(right); + } - public static implicit operator ProjectOrSolution(Project project) - { - return new ProjectOrSolution(project); - } + public static implicit operator ProjectOrSolution(Project project) + { + return new ProjectOrSolution(project); + } - public static implicit operator Project(in ProjectOrSolution ifOrElse) - { - return ifOrElse.AsProject(); - } + public static implicit operator Project(in ProjectOrSolution ifOrElse) + { + return ifOrElse.AsProject(); + } - public static implicit operator ProjectOrSolution(Solution solution) - { - return new ProjectOrSolution(solution); - } + public static implicit operator ProjectOrSolution(Solution solution) + { + return new ProjectOrSolution(solution); + } - public static implicit operator Solution(in ProjectOrSolution ifOrElse) - { - return ifOrElse.AsSolution(); + public static implicit operator Solution(in ProjectOrSolution ifOrElse) + { + return ifOrElse.AsSolution(); + } } } diff --git a/src/Workspaces.Core/Rename/SymbolData.cs b/src/Workspaces.Core/Rename/SymbolData.cs index 95e52bdd1f..6be2fe11c2 100644 --- a/src/Workspaces.Core/Rename/SymbolData.cs +++ b/src/Workspaces.Core/Rename/SymbolData.cs @@ -22,5 +22,5 @@ public SymbolData(ISymbol symbol, string id, DocumentId documentId) public DocumentId DocumentId { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay => (Symbol != null) ? $"{Symbol.Name} {Id}" : "Uninitialized"; + private string DebuggerDisplay => (Symbol is not null) ? $"{Symbol.Name} {Id}" : "Uninitialized"; } diff --git a/src/Workspaces.Core/Rename/SymbolListHelpers.cs b/src/Workspaces.Core/Rename/SymbolListHelpers.cs index d1586b2f8b..98437adf19 100644 --- a/src/Workspaces.Core/Rename/SymbolListHelpers.cs +++ b/src/Workspaces.Core/Rename/SymbolListHelpers.cs @@ -20,7 +20,7 @@ public static List SortTypeSymbols(IEnumerable symbols) { if (symbol is INamedTypeSymbol typeSymbol) { - if (typeSymbol.ContainingType == null) + if (typeSymbol.ContainingType is null) baseTypeSymbols.Add(typeSymbol); typeSymbols.Add(typeSymbol); @@ -45,7 +45,7 @@ void AnalyzeSymbol() IMethodSymbol delegateMethodSymbol = baseType.DelegateInvokeMethod; - if (delegateMethodSymbol != null) + if (delegateMethodSymbol is not null) results.AddRange(delegateMethodSymbol.Parameters); results.AddRange(baseType.TypeParameters); @@ -73,7 +73,7 @@ public static List SortAndFilterMemberSymbols(IEnumerable symb foreach (ISymbol symbol in symbols .Where(s => { - return s.OverriddenSymbol() == null + return s.OverriddenSymbol() is null && !s.ImplementsInterfaceMember(allInterfaces: true); }) #if DEBUG diff --git a/src/Workspaces.Core/Rename/SymbolRenameResult.cs b/src/Workspaces.Core/Rename/SymbolRenameResult.cs index 0995c81fdf..94b4347019 100644 --- a/src/Workspaces.Core/Rename/SymbolRenameResult.cs +++ b/src/Workspaces.Core/Rename/SymbolRenameResult.cs @@ -21,5 +21,5 @@ public SymbolRenameResult(string oldName, string newName, string symbolId) public string SymbolId { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private string DebuggerDisplay => (OldName != null) ? $"{OldName} {NewName} {SymbolId}" : "Uninitialized"; + private string DebuggerDisplay => (OldName is not null) ? $"{OldName} {NewName} {SymbolId}" : "Uninitialized"; } diff --git a/src/Workspaces.Core/Rename/SymbolRenamer.cs b/src/Workspaces.Core/Rename/SymbolRenamer.cs index 44e46d5d91..04145f4fcc 100644 --- a/src/Workspaces.Core/Rename/SymbolRenamer.cs +++ b/src/Workspaces.Core/Rename/SymbolRenamer.cs @@ -82,7 +82,7 @@ internal class SymbolRenamer Project project = CurrentSolution.GetProject(projects[j]); - if (predicate == null || predicate(project)) + if (predicate is null || predicate(project)) { WriteLine($" Rename {GetPluralName(renameScopes[i])} in '{project.Name}' {$"{j + 1}/{projects.Length}"}", ConsoleColors.Cyan, Verbosity.Minimal); @@ -161,7 +161,7 @@ private List GetRenameScopes() IFindSymbolService service = MefWorkspaceServices.Default.GetService(project.Language); - if (service == null) + if (service is null) return ImmutableArray.Empty; ImmutableArray previousIds = ImmutableArray.Empty; @@ -276,7 +276,7 @@ private List GetRenameScopes() ISymbol symbol = symbolData.Symbol; Document document = CurrentSolution.GetDocument(symbolData.DocumentId); - if (document == null) + if (document is null) { ignoreIds?.Add(symbolData.Id); WriteLine($" Cannot find document for '{symbol.Name}'", ConsoleColors.Yellow, Verbosity.Detailed); @@ -355,7 +355,7 @@ private List GetRenameScopes() i++; } - if (localFunctionIndexes != null) + if (localFunctionIndexes is not null) { await RenameLocalFunctionsAndItsParametersAsync( node, @@ -368,7 +368,7 @@ private List GetRenameScopes() .ConfigureAwait(false); } - if (localSymbolIndexes != null) + if (localSymbolIndexes is not null) { await RenameLocalsAndLambdaParametersAsync( node, @@ -428,7 +428,7 @@ private List GetRenameScopes() { if (indexes.Contains(i)) { - if (semanticModel == null) + if (semanticModel is null) { document = CurrentSolution.GetDocument(documentId); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); @@ -468,8 +468,8 @@ private List GetRenameScopes() i++; } - if (diffTracker != null - && diffTracker2 != null) + if (diffTracker is not null + && diffTracker2 is not null) { diffTracker.Add(diffTracker2); } @@ -576,7 +576,7 @@ private List GetRenameScopes() ISymbol currentSymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken) ?? semanticModel.GetSymbol(node, cancellationToken); - if (currentSymbol == null) + if (currentSymbol is null) { Debug.Fail(symbolId); @@ -584,7 +584,7 @@ private List GetRenameScopes() return false; } - if (diffTracker != null + if (diffTracker is not null && _diffTracker.SpanExists(span, document.Id)) { ignoreIds?.Add(GetSymbolId(currentSymbol)); @@ -593,7 +593,7 @@ private List GetRenameScopes() string currentSymbolId = GetSymbolId(currentSymbol); - if (currentSymbolId != null) + if (currentSymbolId is not null) { if (!string.Equals(symbolId, currentSymbolId, StringComparison.Ordinal)) return false; @@ -624,7 +624,7 @@ private List GetRenameScopes() { string newName2 = GetNewName(newName, symbol, findSymbolService, interactive: interactive); - if (newName2 == null) + if (newName2 is null) { ignoreIds?.Add(symbolId); return true; @@ -690,7 +690,7 @@ private List GetRenameScopes() return true; } else if (ErrorResolution == RenameErrorResolution.Ask - && UserDialog != null) + && UserDialog is not null) { switch (UserDialog.ShowDialog("Rename symbol?")) { @@ -735,7 +735,7 @@ private List GetRenameScopes() } if (Ask - && UserDialog != null + && UserDialog is not null && (compilerErrorCount == 0 || ErrorResolution != RenameErrorResolution.Ask)) { switch (UserDialog.ShowDialog("Rename symbol?")) @@ -787,8 +787,8 @@ private List GetRenameScopes() results.Add(new SymbolRenameResult(symbol.Name, newName, symbolId)); - if (diffTracker == null - && ignoreIds == null) + if (diffTracker is null + && ignoreIds is null) { return true; } @@ -837,7 +837,7 @@ private List GetRenameScopes() diff += identifierDiff; - if (diffTracker != null) + if (diffTracker is not null) { diffTracker.AddLocations(locations, diff, oldSolution); _diffTracker.AddLocations(locations, diff, oldSolution); @@ -878,16 +878,16 @@ private List GetRenameScopes() } #endif if (string.Equals(newName, newIdentifier.ValueText, StringComparison.Ordinal) - && ignoreIds != null) + && ignoreIds is not null) { SyntaxNode newNode = findSymbolService.FindDeclaration(newIdentifier.Parent); symbol = semanticModel.GetDeclaredSymbol(newNode, cancellationToken) ?? semanticModel.GetSymbol(newNode, cancellationToken); - Debug.Assert(symbol != null, GetSymbolId(symbol)); + Debug.Assert(symbol is not null, GetSymbolId(symbol)); - if (symbol != null) + if (symbol is not null) ignoreIds.Add(GetSymbolId(symbol)); } @@ -901,7 +901,7 @@ async Task> GetLocationsAsync(IEnumerable re { TextSpan span = location.SourceSpan; - if (symbol != null) + if (symbol is not null) { // 'this' and 'base' constructor references if (symbol.Name.Length == 4 diff --git a/src/Workspaces.Core/Spelling/Core/Hash.cs b/src/Workspaces.Core/Spelling/Core/Hash.cs index 71d5ebb409..455078c60b 100644 --- a/src/Workspaces.Core/Spelling/Core/Hash.cs +++ b/src/Workspaces.Core/Spelling/Core/Hash.cs @@ -37,6 +37,6 @@ public static int Combine(bool value, int hash) { hash = unchecked(hash * Prime); - return (value != null) ? unchecked(hash + value.GetHashCode()) : hash; + return (value is not null) ? unchecked(hash + value.GetHashCode()) : hash; } } diff --git a/src/Workspaces.Core/Spelling/Core/Spellchecker.cs b/src/Workspaces.Core/Spelling/Core/Spellchecker.cs index 60638cc0c6..55d80ec4e1 100644 --- a/src/Workspaces.Core/Spelling/Core/Spellchecker.cs +++ b/src/Workspaces.Core/Spelling/Core/Spellchecker.cs @@ -125,7 +125,7 @@ public ImmutableArray AnalyzeText(string value) if (match.Length >= Options.MinWordLength && match.Length <= Options.MaxWordLength) { - if (_splitRegex == null) + if (_splitRegex is null) { AnalyzeValue(match.Value, match.Index, null, 0, ref builder); } diff --git a/src/Workspaces.Core/Spelling/Core/SpellingData.cs b/src/Workspaces.Core/Spelling/Core/SpellingData.cs index a63fa7a1e8..e8ca92e993 100644 --- a/src/Workspaces.Core/Spelling/Core/SpellingData.cs +++ b/src/Workspaces.Core/Spelling/Core/SpellingData.cs @@ -49,7 +49,7 @@ public WordCharMap CharIndexMap { get { - if (_charIndexMap == null) + if (_charIndexMap is null) Interlocked.CompareExchange(ref _charIndexMap, WordCharMap.CreateCharIndexMap(Words), null); return _charIndexMap; @@ -60,7 +60,7 @@ public WordCharMap ReversedCharIndexMap { get { - if (_reversedCharIndexMap == null) + if (_reversedCharIndexMap is null) Interlocked.CompareExchange(ref _reversedCharIndexMap, WordCharMap.CreateCharIndexMap(Words, reverse: true), null); return _reversedCharIndexMap; @@ -71,7 +71,7 @@ public WordCharMap ReversedCharIndexMap { get { - if (_charMap == null) + if (_charMap is null) Interlocked.CompareExchange(ref _charMap, Create(), null); return _charMap; diff --git a/src/Workspaces.Core/Spelling/Core/SpellingFix.cs b/src/Workspaces.Core/Spelling/Core/SpellingFix.cs index 56324916b8..666814ff52 100644 --- a/src/Workspaces.Core/Spelling/Core/SpellingFix.cs +++ b/src/Workspaces.Core/Spelling/Core/SpellingFix.cs @@ -19,7 +19,7 @@ public SpellingFix(string value, SpellingFixKind kind) public SpellingFixKind Kind { get; } - public bool IsDefault => Value == null; + public bool IsDefault => Value is null; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => $"{Kind} {Value}"; diff --git a/src/Workspaces.Core/Spelling/Core/SpellingFixComparer.cs b/src/Workspaces.Core/Spelling/Core/SpellingFixComparer.cs index d908982713..0dd22c4259 100644 --- a/src/Workspaces.Core/Spelling/Core/SpellingFixComparer.cs +++ b/src/Workspaces.Core/Spelling/Core/SpellingFixComparer.cs @@ -27,10 +27,10 @@ public int Compare(object x, object y) if (x == y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is SpellingFix a @@ -47,10 +47,10 @@ public int Compare(object x, object y) if (x == y) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x is SpellingFix a @@ -64,7 +64,7 @@ public int Compare(object x, object y) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) return 0; if (obj is SpellingFix type) diff --git a/src/Workspaces.Core/Spelling/Core/SpellingFixProvider.cs b/src/Workspaces.Core/Spelling/Core/SpellingFixProvider.cs index 2aaf19bf71..a8c56a984c 100644 --- a/src/Workspaces.Core/Spelling/Core/SpellingFixProvider.cs +++ b/src/Workspaces.Core/Spelling/Core/SpellingFixProvider.cs @@ -97,7 +97,7 @@ internal static class SpellingFixProvider j--; } - if (matches == null) + if (matches is null) return ImmutableArray.Empty; return matches diff --git a/src/Workspaces.Core/Spelling/Core/WordListLoader.cs b/src/Workspaces.Core/Spelling/Core/WordListLoader.cs index 4d3c79eb01..9a281448b3 100644 --- a/src/Workspaces.Core/Spelling/Core/WordListLoader.cs +++ b/src/Workspaces.Core/Spelling/Core/WordListLoader.cs @@ -38,7 +38,7 @@ internal static class WordListLoader foreach (string word in state.Words) fixes.Remove(word); - if (state.CaseSensitiveWords != null) + if (state.CaseSensitiveWords is not null) { foreach (string word in state.CaseSensitiveWords) fixes.Remove(word); @@ -265,7 +265,7 @@ private static IEnumerable GetFiles(IEnumerable paths) if (s.Length > 0) { - if (caseSensitiveSequences != null + if (caseSensitiveSequences is not null && !IsLower(value)) { caseSensitiveSequences.Add(new WordSequence(s.ToImmutableArray())); @@ -279,7 +279,7 @@ private static IEnumerable GetFiles(IEnumerable paths) else if (value.Length >= minWordLength && value.Length <= maxWordLength) { - if (caseSensitiveWords != null + if (caseSensitiveWords is not null && !IsLower(value)) { caseSensitiveWords.Add(value); diff --git a/src/Workspaces.Core/Spelling/SpellingAnalysisContext.cs b/src/Workspaces.Core/Spelling/SpellingAnalysisContext.cs index 1883a3692c..ed6dc5b73d 100644 --- a/src/Workspaces.Core/Spelling/SpellingAnalysisContext.cs +++ b/src/Workspaces.Core/Spelling/SpellingAnalysisContext.cs @@ -64,7 +64,7 @@ public void AnalyzeText(string value, TextSpan textSpan, SyntaxTree syntaxTree) ImmutableDictionary properties; - if (match.Parent != null) + if (match.Parent is not null) { properties = ImmutableDictionary.CreateRange(new[] { diff --git a/src/Workspaces.Core/Spelling/SpellingAnalyzer.cs b/src/Workspaces.Core/Spelling/SpellingAnalyzer.cs index d33e4839d4..cf5d15be5e 100644 --- a/src/Workspaces.Core/Spelling/SpellingAnalyzer.cs +++ b/src/Workspaces.Core/Spelling/SpellingAnalyzer.cs @@ -32,7 +32,7 @@ internal sealed class SpellingAnalyzer { ISpellingService service = MefWorkspaceServices.Default.GetService(project.Language); - if (service == null) + if (service is null) return ImmutableArray.Empty; ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); @@ -65,7 +65,7 @@ internal sealed class SpellingAnalyzer { SyntaxTree tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); - if (tree == null) + if (tree is null) return ImmutableArray.Empty; if (!options.IncludeGeneratedCode diff --git a/src/Workspaces.Core/Spelling/SpellingDiagnostic.cs b/src/Workspaces.Core/Spelling/SpellingDiagnostic.cs index 9394e9724c..3b3cd2ea67 100644 --- a/src/Workspaces.Core/Spelling/SpellingDiagnostic.cs +++ b/src/Workspaces.Core/Spelling/SpellingDiagnostic.cs @@ -43,7 +43,7 @@ internal abstract class SpellingDiagnostic public int ParentIndex { get; } - public int Offset => (Parent != null) ? Index - ParentIndex : 0; + public int Offset => (Parent is not null) ? Index - ParentIndex : 0; public Location Location => Diagnostic.Location; @@ -55,7 +55,7 @@ internal abstract class SpellingDiagnostic public SyntaxToken Identifier { get; } - public bool IsSymbol => Identifier.Parent != null; + public bool IsSymbol => Identifier.Parent is not null; public string ValueLower => _valueLower ??= Value.ToLowerInvariant(); diff --git a/src/Workspaces.Core/Spelling/SpellingDiagnosticComparer.cs b/src/Workspaces.Core/Spelling/SpellingDiagnosticComparer.cs index e23810e260..2270ed2be1 100644 --- a/src/Workspaces.Core/Spelling/SpellingDiagnosticComparer.cs +++ b/src/Workspaces.Core/Spelling/SpellingDiagnosticComparer.cs @@ -25,10 +25,10 @@ public int Compare(object x, object y) if (x == y) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; if (x is SpellingDiagnostic a @@ -45,10 +45,10 @@ public int Compare(object x, object y) if (x == y) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; if (x is SpellingDiagnostic a @@ -62,7 +62,7 @@ public int Compare(object x, object y) public int GetHashCode(object obj) { - if (obj == null) + if (obj is null) return 0; if (obj is SpellingDiagnostic diagnostic) @@ -78,10 +78,10 @@ public override int Compare(SpellingDiagnostic x, SpellingDiagnostic y) if (object.ReferenceEquals(x, y)) return 0; - if (x == null) + if (x is null) return -1; - if (y == null) + if (y is null) return 1; int result = StringComparer.OrdinalIgnoreCase.Compare( @@ -99,10 +99,10 @@ public override bool Equals(SpellingDiagnostic x, SpellingDiagnostic y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return StringComparer.OrdinalIgnoreCase.Equals( @@ -113,7 +113,7 @@ public override bool Equals(SpellingDiagnostic x, SpellingDiagnostic y) public override int GetHashCode(SpellingDiagnostic obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); return Hash.Combine( diff --git a/src/Workspaces.Core/Spelling/SpellingFixHelpers.cs b/src/Workspaces.Core/Spelling/SpellingFixHelpers.cs index 64313b1c30..1326024ef4 100644 --- a/src/Workspaces.Core/Spelling/SpellingFixHelpers.cs +++ b/src/Workspaces.Core/Spelling/SpellingFixHelpers.cs @@ -137,7 +137,7 @@ internal class SpellingFixHelpers { Write(" Replace '"); - if (containingValue != null) + if (containingValue is not null) { Write(containingValue.Remove(diagnostic.Index)); Write(value); @@ -164,7 +164,7 @@ internal class SpellingFixHelpers Write("with '"); - if (containingValue != null) + if (containingValue is not null) { Write(containingValue.Remove(diagnostic.Index)); Write(fix.Value, ConsoleColors.Cyan); diff --git a/src/Workspaces.Core/Spelling/SpellingFixResultEqualityComparer.cs b/src/Workspaces.Core/Spelling/SpellingFixResultEqualityComparer.cs index ea02375b9d..550f7b63e6 100644 --- a/src/Workspaces.Core/Spelling/SpellingFixResultEqualityComparer.cs +++ b/src/Workspaces.Core/Spelling/SpellingFixResultEqualityComparer.cs @@ -22,10 +22,10 @@ public override bool Equals(SpellingFixResult x, SpellingFixResult y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return StringComparer.CurrentCulture.Equals(x.Value, y.Value) @@ -34,7 +34,7 @@ public override bool Equals(SpellingFixResult x, SpellingFixResult y) public override int GetHashCode(SpellingFixResult obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); return Hash.Combine( @@ -50,10 +50,10 @@ public override bool Equals(SpellingFixResult x, SpellingFixResult y) if (object.ReferenceEquals(x, y)) return true; - if (x == null) + if (x is null) return false; - if (y == null) + if (y is null) return false; return StringComparer.CurrentCulture.Equals(x.Value, y.Value) @@ -62,7 +62,7 @@ public override bool Equals(SpellingFixResult x, SpellingFixResult y) public override int GetHashCode(SpellingFixResult obj) { - if (obj == null) + if (obj is null) throw new ArgumentNullException(nameof(obj)); return Hash.Combine( diff --git a/src/Workspaces.Core/Spelling/SpellingFixer.cs b/src/Workspaces.Core/Spelling/SpellingFixer.cs index 98d2566aee..e40dcf0ef6 100644 --- a/src/Workspaces.Core/Spelling/SpellingFixer.cs +++ b/src/Workspaces.Core/Spelling/SpellingFixer.cs @@ -60,7 +60,7 @@ public async Task> FixSolutionAsync(Func> FixSolutionAsync(Func(project.Language); - if (service == null) + if (service is null) return ImmutableArray.Empty; ImmutableArray previousDiagnostics = ImmutableArray.Empty; @@ -273,7 +273,7 @@ public async Task> FixSolutionAsync(Func> FixSolutionAsync(Func> FixSolutionAsync(Func> FixSolutionAsync(Func> FixSolutionAsync(Func> FixSolutionAsync(Func> FixSolutionAsync(Func nodes = null; @@ -74,10 +74,10 @@ internal static class SyntaxFinder bool allowCandidate = false, CancellationToken cancellationToken = default) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); - if (solution == null) + if (solution is null) throw new ArgumentNullException(nameof(solution)); List infos = null; @@ -99,7 +99,7 @@ internal static class SyntaxFinder FindReferences(grouping, root, allowCandidate, ref nodes); - if (nodes != null) + if (nodes is not null) { var info = new DocumentReferenceInfo(document, root, nodes.ToImmutableArray()); @@ -117,10 +117,10 @@ internal static class SyntaxFinder bool allowCandidate = false, CancellationToken cancellationToken = default) { - if (symbol == null) + if (symbol is null) throw new ArgumentNullException(nameof(symbol)); - if (document == null) + if (document is null) throw new ArgumentNullException(nameof(document)); SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); @@ -157,7 +157,7 @@ internal static class SyntaxFinder { SyntaxNode node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true); - Debug.Assert(node != null); + Debug.Assert(node is not null); (nodes ??= new List()).Add(node); } @@ -167,7 +167,7 @@ internal static class SyntaxFinder private static ImmutableArray ToImmutableArray(IEnumerable nodes) { - if (nodes != null) + if (nodes is not null) { return ImmutableArray.CreateRange(nodes); } diff --git a/src/Workspaces.Core/UnusedSymbolUtility.cs b/src/Workspaces.Core/UnusedSymbolUtility.cs index 7c9ce0642a..95b70461b7 100644 --- a/src/Workspaces.Core/UnusedSymbolUtility.cs +++ b/src/Workspaces.Core/UnusedSymbolUtility.cs @@ -203,7 +203,7 @@ private static bool IsReferencedInDebuggerDisplayAttribute(ISymbol symbol) .Value? .ToString(); - return value != null + return value is not null && IsReferencedInDebuggerDisplayAttribute(value); }