Skip to content

Update cast analyzer to handle switch statement patterns #2004

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

Merged
merged 2 commits into from
Jul 8, 2025
Merged
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
@@ -215,6 +215,34 @@ bool IsDynamicCastAttributePresentOnOperation(IOperation? operation, INamedTypeS
typeSymbol));
}
}, OperationKind.TypePattern);

// This handles the following cases:
//
// case C:
// {
// }
context.RegisterOperationAction(context =>
{
if (context.Operation is IPatternCaseClauseOperation { IsImplicit: false, Pattern: { NarrowedType: INamedTypeSymbol { TypeKind: TypeKind.Class or TypeKind.Enum, IsStatic: false } typeSymbol } patternOperation } &&
typeSymbol.HasAttributeWithType(windowsRuntimeTypeAttribute) &&
patternOperation.InputType.IsReferenceType &&
!context.Compilation.HasImplicitConversion(patternOperation.InputType, typeSymbol) &&
!IsDynamicCastAttributePresentOnOperation(context.Operation, typeSymbol))
{
// Special case: we're already handling declaration patterns above, and we don't want to emit two
// warnings for the same code. This callback is just to handle simple patterns in 'switch' statements.
if (patternOperation is IDeclarationPatternOperation)
{
return;
}

context.ReportDiagnostic(Diagnostic.Create(
typeSymbol.TypeKind is TypeKind.Class ? WinRTRules.RuntimeClassCast : WinRTRules.IReferenceTypeCast,
patternOperation.Syntax.GetLocation(),
ImmutableDictionary.Create<string, string?>().Add(WindowsRuntimeTypeId, typeSymbol.GetFullyQualifiedMetadataName()),
typeSymbol));
}
}, OperationKind.CaseClause);
});
}
}
357 changes: 357 additions & 0 deletions src/Tests/SourceGeneratorTest/DiagnosticAnalyzerTests.cs
Original file line number Diff line number Diff line change
@@ -1168,4 +1168,361 @@ enum E

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchStatement_NoAttribute_Warns()
{
const string source = """
using WinRT;

class Test
{
int M(object obj)
{
switch (obj)
{
case {|CsWinRT1034:C|}: return 42;
default: return 0;
}
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchStatement_WithAttribute_DoesNotWarn()
{
const string source = """
using WinRT;

class Test
{
[DynamicWindowsRuntimeCast(typeof(C))]
int M(object obj)
{
switch (obj)
{
case C: return 42;
default: return 0;
}
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchStatement_WithDeclaration_NoAttribute_Warns()
{
const string source = """
using WinRT;

class Test
{
int M(object obj)
{
switch (obj)
{
case {|CsWinRT1034:C c|}: return c.GetHashCode();
default: return 0;
}
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchStatement_WithDeclaration_WithAttribute_DoesNotWarn()
{
const string source = """
using WinRT;

class Test
{
[DynamicWindowsRuntimeCast(typeof(C))]
int M(object obj)
{
switch (obj)
{
case C c: return c.GetHashCode();
default: return 0;
}
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_NoAttribute_Warns()
{
const string source = """
using WinRT;

class Test
{
int M(object obj)
{
return obj switch
{
{|CsWinRT1034:C|} => 42,
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithAttribute_DoesNotWarn()
{
const string source = """
using WinRT;

class Test
{
[DynamicWindowsRuntimeCast(typeof(C))]
int M(object obj)
{
return obj switch
{
C => 42,
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithCondition_NoAttribute_Warns()
{
const string source = """
using WinRT;

class Test
{
int M(object obj)
{
return obj switch
{
{ } when {|CsWinRT1034:obj is C|} => 42,
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithCondition_WithAttribute_DoesNotWarn()
{
const string source = """
using WinRT;

class Test
{
[DynamicWindowsRuntimeCast(typeof(C))]
int M(object obj)
{
return obj switch
{
{ } when obj is C => 42,
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithConditionAndDeclaration_NoAttribute_Warns()
{
const string source = """
using WinRT;

class Test
{
int M(object obj)
{
return obj switch
{
{ } when {|CsWinRT1034:obj is C c|} => c.GetHashCode(),
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithConditionAndDeclaration_WithAttribute_DoesNotWarn()
{
const string source = """
using WinRT;

class Test
{
[DynamicWindowsRuntimeCast(typeof(C))]
int M(object obj)
{
return obj switch
{
{ } when obj is C c => c.GetHashCode(),
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithTuple_NoAttribute_Warns()
{
const string source = """
using WinRT;

class Test
{
int M(object obj)
{
return obj switch
{
({|CsWinRT1034:C|}, _) => 42,
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithTuple_WithAttribute_DoesNotWarn()
{
const string source = """
using WinRT;

class Test
{
[DynamicWindowsRuntimeCast(typeof(C))]
int M(object obj)
{
return obj switch
{
(C, _) => 42,
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithTuple2_NoAttribute_Warns()
{
const string source = """
using WinRT;

class Test
{
int M(object obj, object obj2)
{
return (obj, obj2) switch
{
({|CsWinRT1034:C c|}, _) => c.GetHashCode(),
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}

[TestMethod]
public async Task RuntimeClassCast_InvalidCast_SwitchExpression_WithTuple2_WithAttribute_DoesNotWarn()
{
const string source = """
using WinRT;

class Test
{
[DynamicWindowsRuntimeCast(typeof(C))]
int M(object obj, object obj2)
{
return (obj, obj2) switch
{
(C c, _) => c.GetHashCode(),
_ => 0
};
}
}

[WindowsRuntimeType("SomeContract")]
class C;
""";

await CSharpAnalyzerTest<RuntimeClassCastAnalyzer>.VerifyAnalyzerAsync(source, editorconfig: [("CsWinRTAotWarningLevel", "3")]);
}
}
Loading
Oops, something went wrong.