Skip to content

use some pattern matching #6045

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static bool TryHandleITestDataRow(
out string? displayNameFromTestDataRow,
out IList<string>? testCategoriesFromTestDataRow)
{
if (d.Length == 1 && d[0] is ITestDataRow testDataRow)
if (d is [ITestDataRow testDataRow])
{
object? dataFromTestDataRow = testDataRow.Value;
ignoreMessageFromTestDataRow = testDataRow.IgnoreMessage;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,7 @@ private static (SyntaxNode ExpressionOrStatement, SyntaxNode NodeToReplace)? Try
{
return (expressionStatement.Expression, statement);
}
else if (statement is LocalDeclarationStatementSyntax localDeclarationStatementSyntax &&
localDeclarationStatementSyntax.Declaration.Variables.Count == 1 &&
localDeclarationStatementSyntax.Declaration.Variables[0].Initializer is { } initializer)
else if (statement is LocalDeclarationStatementSyntax { Declaration.Variables: [{ Initializer: { } initializer }] })
{
return (initializer.Value, statement);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ private static void AnalyzeGenericMethod(
// It also happens with [DataRow((object[]?)null)] which resolves
// to the params object[] constructor
// In this case, the argument is simply "null".
if (constructorArgument.Kind == TypedConstantKind.Array && constructorArgument.IsNull)
if (constructorArgument is { Kind: TypedConstantKind.Array, IsNull: true })
{
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ private static void AnalyzeOperation(OperationAnalysisContext context, INamedTyp
}

IArgumentOperation? conditionArgument = invocationOperation.Arguments.FirstOrDefault(x => x.Parameter?.Name == "condition");
if (conditionArgument != null
&& conditionArgument.Value is IUnaryOperation { OperatorKind: UnaryOperatorKind.Not })
if (conditionArgument is { Value: IUnaryOperation { OperatorKind: UnaryOperatorKind.Not } })
{
context.ReportDiagnostic(invocationOperation.CreateDiagnostic(Rule));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -304,13 +304,11 @@ private static void AnalyzeDisplayNameSource(SymbolAnalysisContext context, Attr
continue;
}

if (namedArgument.Key == "DynamicDataDisplayName"
&& namedArgument.Value.Value is string name)
if (namedArgument is { Key: "DynamicDataDisplayName", Value.Value: string name })
{
memberName = name;
}
else if (namedArgument.Key == "DynamicDataDisplayNameDeclaringType"
&& namedArgument.Value.Value is INamedTypeSymbol type)
else if (namedArgument is { Key: "DynamicDataDisplayNameDeclaringType", Value.Value: INamedTypeSymbol type })
{
declaringType = type;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static bool DerivesFrom([NotNullWhen(returnValue: true)] this ITypeSymbol
}

public static bool IsNullableValueType([NotNullWhen(returnValue: true)] this ITypeSymbol? typeSymbol)
=> typeSymbol != null && typeSymbol.IsValueType && typeSymbol.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
=> typeSymbol is { IsValueType: true } && typeSymbol.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;

public static bool IsNullableOfBoolean([NotNullWhen(returnValue: true)] this ITypeSymbol? typeSymbol)
=> typeSymbol.IsNullableValueType() && ((INamedTypeSymbol)typeSymbol).TypeArguments[0].SpecialType == SpecialType.System_Boolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,11 @@ private static bool AssignsParameterToMember(IParameterSymbol parameter, ISymbol
operation = expressionStatementOperation.Operation;
}

if (operation is ISimpleAssignmentOperation assignmentOperation &&
assignmentOperation.Target is IMemberReferenceOperation targetMemberReference &&
SymbolEqualityComparer.Default.Equals(targetMemberReference.Member, member))
if (operation is ISimpleAssignmentOperation { Target: IMemberReferenceOperation { Member: { } targetMember }, Value: { } assignmentValue } &&
SymbolEqualityComparer.Default.Equals(targetMember, member))
{
// Extract parameter reference from the value, unwrapping from coalesce operation if necessary
IOperation effectiveValue = assignmentOperation.Value;
IOperation effectiveValue = assignmentValue;
if (effectiveValue is ICoalesceOperation coalesceOperation)
{
effectiveValue = coalesceOperation.Value;
Expand Down Expand Up @@ -139,8 +138,7 @@ private static void CollectTestContextFieldsAssignedInConstructor(
operation = expressionStatementOperation.Operation;
}

if (operation is ISimpleAssignmentOperation assignmentOperation &&
assignmentOperation.Target is IMemberReferenceOperation { Member: IFieldSymbol { } candidateField })
if (operation is ISimpleAssignmentOperation { Target: IMemberReferenceOperation { Member: IFieldSymbol candidateField } } assignmentOperation)
{
// Extract parameter reference from the value, unwrapping from coalesce operation if necessary
IOperation effectiveValue = assignmentOperation.Value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo

// Report diagnostic if CooperativeCancellation is not explicitly set to true
if (timeoutAttribute is not null
&& !timeoutAttribute.NamedArguments.Any(x => x.Key == "CooperativeCancellation" && x.Value.Value is bool boolValue && boolValue))
&& !timeoutAttribute.NamedArguments.Any(x => x is { Key: "CooperativeCancellation", Value.Value: true }))
{
if (timeoutAttribute.ApplicationSyntaxReference?.GetSyntax() is { } syntax)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ internal static class AnalyzerSeverityDecider
return DiagnosticSeverity.Error;
}

if (rule.IsEnabledByDefault && rule.DefaultSeverity >= DiagnosticSeverity.Info)
if (rule is { IsEnabledByDefault: true, DefaultSeverity: >= DiagnosticSeverity.Info })
{
// Recommended mode will elevate info to warning only if the rule is enabled by default.
return DiagnosticSeverity.Warning;
Expand All @@ -101,7 +101,7 @@ internal static class AnalyzerSeverityDecider

private static DiagnosticSeverity? DecideForModeDefault(DiagnosticDescriptor rule)
{
if (rule.IsEnabledByDefault && rule.DefaultSeverity >= DiagnosticSeverity.Warning)
if (rule is { IsEnabledByDefault: true, DefaultSeverity: >= DiagnosticSeverity.Warning })
{
// Default mode will enable warnings only if the rule is enabled by default.
return rule.DefaultSeverity;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ public static bool TryGetTestExecutionTimeout(this AttributeData attribute, INam

private static bool TryGetTimeoutValue(this AttributeData attribute, INamedTypeSymbol? timeSpanSymbol, out TimeSpan timeout)
{
if (attribute.ConstructorArguments.Length == 1
&& attribute.ConstructorArguments[0].Type is { } executionTimeoutCtorArgType
&& attribute.ConstructorArguments[0].Value is { } executionTimeoutCtorArgValue)
if (attribute.ConstructorArguments is [{ Type: { } executionTimeoutCtorArgType, Value: { } executionTimeoutCtorArgValue }])
{
if (executionTimeoutCtorArgType.SpecialType is SpecialType.System_Int32 or SpecialType.System_Int64)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ public static bool IsDisposeImplementation(this IMethodSymbol? method, INamedTyp

// Identify the implementor of IDisposable.Dispose in the given method's containing type and check
// if it is the given method.
return method.ReturnsVoid
&& method.Parameters.IsEmpty
&& method.IsImplementationOfInterfaceMethod(null, iDisposable, "Dispose");
return method is { ReturnsVoid: true, Parameters.IsEmpty: true }
&& method.IsImplementationOfInterfaceMethod(null, iDisposable, "Dispose");
}

/// <summary>
Expand Down
36 changes: 0 additions & 36 deletions src/Analyzers/MSTest.SourceGeneration/Helpers/SystemPolyfills.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static bool IsValidTestMethodShape(this IMethodSymbol methodSymbol, WellK
}

// We don't support async void
if (methodSymbol.ReturnsVoid && methodSymbol.IsAsync)
if (methodSymbol is { ReturnsVoid: true, IsAsync: true })
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
<PropertyGroup>
<!-- C# Source generators have to target netstandard -->
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<!-- Disable Polyfill validation for source generators -->
<PolyfillTargetsForNuget>true</PolyfillTargetsForNuget>
<!-- Generates a package at build -->
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<!-- Do not include the generator as a lib dependency -->
Expand Down Expand Up @@ -46,6 +48,7 @@ This package provides the C# source generators for MSTest test framework.]]>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="all" />
<!-- Analyzers to help write analyzers/generators -->
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all" />
<PackageReference Include="Polyfill" PrivateAssets="all" />
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one is likely to cause us issues, if not now, later. This project targets netstandard2.0 and has IVT exposed to test project (not netstandard2.0). So likely going to cause us issues, unless either IVT is removed and make the needed members public, or EmbeddedAttribute is used.

</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ private static IEnumerable<string> GetInlineArguments(IMethodSymbol methodSymbol
Stack<(TypedConstant Argument, bool HasNextArg, bool IsInArray, int ClosingCurlyBraceCount)> argumentStack = new();

bool hasManyArgsButExpectsSingleArray =
methodSymbol.Parameters.Length == 1
&& methodSymbol.Parameters[0].Type.TypeKind == TypeKind.Array
methodSymbol.Parameters is [{ Type.TypeKind: TypeKind.Array }]
&& argumentsAttributeArguments.Values.Length > 1;

if (hasManyArgsButExpectsSingleArray)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public async Task OnTestHostProcessExitedAsync(ITestHostProcessInformation testH
{
if (cancellation.IsCancellationRequested
|| testHostProcessInformation.HasExitedGracefully
|| (AppDomain.CurrentDomain.GetData("ProcessKilledByHangDump") is string processKilledByHangDump && processKilledByHangDump == "true"))
|| AppDomain.CurrentDomain.GetData("ProcessKilledByHangDump") is "true")
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ public void Render(AnsiTerminalTestProgressFrame previousFrame, TestProgressStat
// quickly determine if the detail has changed since the last render.

// Don't go up if we did not render any lines in previous frame or we already cleared them.
if (previousFrame.RenderedLines != null && previousFrame.RenderedLines.Count > 0)
if (previousFrame.RenderedLines is { Count: > 0 })
{
// Move cursor back to 1st line of progress.
// + 2 because we output and empty line right below.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ public bool IsCurrentTestApplicationHostMonoMuxer
get
{
string? processPath = GetProcessPath(_environment, _process);
return processPath is not null
&& Path.GetFileNameWithoutExtension(processPath) is { } processName
&& processName is "mono" or "mono-sgen";
return Path.GetFileNameWithoutExtension(processPath) is "mono" or "mono-sgen";
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ public void GetTestFromMethodShouldSetDescription()
MSTest.TestAdapter.ObjectModel.UnitTestElement testElement = typeEnumerator.GetTestFromMethod(methodInfo, true, _warnings);

Verify(testElement.Traits is not null);
Verify(testElement.Traits.Any(t => t.Name == "Description" && t.Value == "Dummy description"));
Verify(testElement.Traits.Any(t => t is { Name: "Description", Value: "Dummy description" }));
}

public void GetTestFromMethodShouldSetWorkItemIds()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public static async Task<DotnetMuxerResult> RunAsync(

string extraArgs = warnAsError ? " /warnaserror" : string.Empty;
extraArgs += suppressPreviewDotNetMessage ? " -p:SuppressNETCoreSdkPreviewMessage=true" : string.Empty;
if (args.IndexOf("-- ", StringComparison.Ordinal) is int platformArgsIndex && platformArgsIndex > 0)
if (args.IndexOf("-- ", StringComparison.Ordinal) is int platformArgsIndex and > 0)
{
args = args.Insert(platformArgsIndex, extraArgs + " ");
}
Expand Down Expand Up @@ -150,7 +150,7 @@ private static async Task<DotnetMuxerResult> CallTheMuxerCoreAsync(string args,
// We do this here rather than in the caller so that different retries produce different binlog file names.
binlogFullPath = Path.Combine(TempDirectory.TestSuiteDirectory, $"{binlogBaseFileName}-{Interlocked.Increment(ref s_binlogCounter)}.binlog");
string binlogArg = $" -bl:\"{binlogFullPath}\"";
if (args.IndexOf("-- ", StringComparison.Ordinal) is int platformArgsIndex && platformArgsIndex > 0)
if (args.IndexOf("-- ", StringComparison.Ordinal) is int platformArgsIndex and > 0)
{
args = args.Insert(platformArgsIndex, binlogArg + " ");
}
Expand Down
Loading