Skip to content

Commit

Permalink
Use pattern matching to check for null (dotnet#996)
Browse files Browse the repository at this point in the history
  • Loading branch information
josefpihrt authored and JochemHarmes committed Oct 30, 2023
1 parent b6a85f2 commit 0a4ddba
Show file tree
Hide file tree
Showing 638 changed files with 27,885 additions and 27,764 deletions.
2 changes: 2 additions & 0 deletions .editorconfig
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
Expand Up @@ -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",
Expand Down
Expand Up @@ -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;

Expand Down
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down
Expand Up @@ -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);
Expand Down
Expand Up @@ -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;
Expand Down
Expand Up @@ -66,7 +66,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)

ImmutableArray<ulong> 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();

Expand Down Expand Up @@ -209,7 +209,7 @@ private static bool AreSeparatedWithEmptyLine(SeparatedSyntaxList<EnumMemberDecl

for (int i = 0; i < members.Count; i++)
{
if (members[i].EqualsValue == null)
if (members[i].EqualsValue is null)
{
IFieldSymbol fieldSymbol = semanticModel.GetDeclaredSymbol(members[i], cancellationToken);

Expand All @@ -230,7 +230,7 @@ private static bool AreSeparatedWithEmptyLine(SeparatedSyntaxList<EnumMemberDecl
value = SymbolUtility.GetEnumValueAsUInt64(fieldSymbol.ConstantValue, enumSymbol);
}

if (value != null)
if (value is not null)
{
reservedValues.Add(value.Value);

Expand Down Expand Up @@ -292,7 +292,7 @@ IEnumerable<ExpressionSyntax> GetExpressionsToRewrite()
{
ExpressionSyntax expression = member.EqualsValue?.Value.WalkDownParentheses();

if (expression != null
if (expression is not null
&& semanticModel.GetDeclaredSymbol(member, cancellationToken) is IFieldSymbol fieldSymbol
&& fieldSymbol.HasConstantValue)
{
Expand Down
Expand Up @@ -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));
Expand Down
Expand Up @@ -153,9 +153,9 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
SyntaxList<StatementSyntax> 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);
}
Expand Down
Expand Up @@ -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()));

Expand Down Expand Up @@ -336,11 +336,11 @@ private static ImmutableArray<ArgumentSyntax> 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);

Expand Down
Expand Up @@ -112,7 +112,7 @@ SyntaxList<XmlNodeSyntax> GetNewContent()
? ((XmlElementSyntax)element).GetAttributeValue("name")
: ((XmlEmptyElementSyntax)element).GetAttributeValue("name");

if (value != null)
if (value is not null)
{
ranks[element] = indexOf(nodes, value);
}
Expand Down
Expand Up @@ -37,7 +37,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
ct =>
{
TypeDeclarationSyntax newTypeDeclaration = typeDeclaration.ReplaceNodes(
typeDeclaration.Members.OfType<MethodDeclarationSyntax>().Where(f => f.Modifiers.Contains(SyntaxKind.PartialKeyword) && f.BodyOrExpressionBody() != null),
typeDeclaration.Members.OfType<MethodDeclarationSyntax>().Where(f => f.Modifiers.Contains(SyntaxKind.PartialKeyword) && f.BodyOrExpressionBody() is not null),
(f, _) => f.RemoveModifier(SyntaxKind.PartialKeyword));
int count = newTypeDeclaration.Members.Count;
Expand Down
Expand Up @@ -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));

Expand Down
Expand Up @@ -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<ReferencedSymbol> referencedSymbols = await SymbolFinder.FindReferencesAsync(symbol, document.Solution(), cancellationToken).ConfigureAwait(false);

Expand Down Expand Up @@ -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));

Expand Down
Expand Up @@ -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);
Expand All @@ -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);
}
Expand All @@ -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];

Expand All @@ -173,7 +173,7 @@ public static PropertyDeclarationSyntax CreateAutoProperty(PropertyDeclarationSy
{
AccessorListSyntax accessorList = property.AccessorList;

if (accessorList != null)
if (accessorList is not null)
{
SyntaxList<AccessorDeclarationSyntax> newAccessors = accessorList
.Accessors
Expand Down Expand Up @@ -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)
Expand Down
Expand Up @@ -57,7 +57,7 @@ private static string CreateSummaryElement(string indent, string text = null)
sb.Append(indent);
sb.AppendLine("/// </summary>");

if (text == null)
if (text is null)
sb.Append(indent);

return sb.ToString();
Expand Down
Expand Up @@ -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;
Expand Down
Expand Up @@ -137,7 +137,7 @@ internal abstract class DocumentationCommentRefactoring<TNode> where TNode : Syn
{
XmlElementSyntax previousElement = GetPreviousElement(comment, element);

if (previousElement != null)
if (previousElement is not null)
{
insertIndex = previousElement.FullSpan.End;
}
Expand Down
Expand Up @@ -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;

Expand Down Expand Up @@ -120,7 +120,7 @@ private static bool ShouldBeFormatted(AccessorDeclarationSyntax accessor)
{
BlockSyntax body = accessor.Body;

if (body != null)
if (body is not null)
{
SyntaxList<StatementSyntax> statements = body.Statements;

Expand All @@ -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)
{
Expand Down
Expand Up @@ -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;

Expand Down
Expand Up @@ -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);

Expand Down Expand Up @@ -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())
Expand All @@ -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
Expand Down

0 comments on commit 0a4ddba

Please sign in to comment.