Skip to content
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

Fix enum pattern matching #86

Merged
merged 2 commits into from
Aug 7, 2024
Merged

Conversation

GerardSmit
Copy link
Contributor

When using is pattern matching with enums, the enum value is dropped. For example:

_ = System.Data.ConnectionState.Closed is System.Data.ConnectionState.Closed;

Gets converted to:

_ = System.Data.ConnectionState.Closed is global::System.Data.ConnectionState;

This PR checks if the type is an enum and doesn't match the base typeSyntax (because the right-side is missing) and then adds it back.

return typeSymbol switch
{
null => typeSyntax,
{ TypeKind: TypeKind.Enum } when typeSyntax is QualifiedNameSyntax { Right: IdentifierNameSyntax r } && (r.Identifier.ValueText != typeSymbol.Name || typeSymbol.ToString() != typeSyntax.WithoutTrivia().ToString())
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've added a quick check with r.Identifier.ValueText != typeSymbol.Name which is almost always true, because typeSymbol.ToString() is allocating a string. The edge case is if the enum value and enum have the same name, e.g.

enum Test { Test }

This would fail with r.Identifier.ValueText != typeSymbol.Name. I've added a unit test for this.

@@ -0,0 +1,2 @@
//HintName: Test.Class.MethodAsync.g.cs
_ = System.Data.ConnectionState.Closed is global::System.Data.ConnectionState.Closed;
Copy link
Contributor

Choose a reason for hiding this comment

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

I think it should be:

_ = global::System.Data.ConnectionState.Closed is global::System.Data.ConnectionState.Closed;

@virzak virzak merged commit d85b0a1 into zompinc:master Aug 7, 2024
3 checks passed
@virzak
Copy link
Contributor

virzak commented Aug 8, 2024

Thanks a lot for the PR.

I expanded your test case to cover using static class.

The change is in the latest nuget package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants