Add MA0181 - Report use of explicit casts#952
Conversation
Co-authored-by: meziantou <509220+meziantou@users.noreply.github.com>
Co-authored-by: meziantou <509220+meziantou@users.noreply.github.com>
|
@copilot There are errors on ci |
…ntax Co-authored-by: meziantou <509220+meziantou@users.noreply.github.com>
... Fixed in commit df960ea. The issue was that the analyzer was checking Warning Firewall rules blocked me from connecting to one or more addresses (expand for details)I tried to connect to the following addresses, but was blocked by firewall rules:
If you need me to access, download, or install something from one of these locations, you can either:
|
| var operation = (IConversionOperation)context.Operation; | ||
|
|
||
| // Only report cast expressions (explicit cast syntax like (int)value) | ||
| if (operation.Syntax is not CastExpressionSyntax) | ||
| return; | ||
|
|
||
| // Do not report if it's a user-defined conversion | ||
| if (operation.Conversion.IsUserDefined) | ||
| return; | ||
|
|
||
| context.ReportDiagnostic(Rule, operation); |
There was a problem hiding this comment.
@copilot you can do better and not use the syntax at all. the conversionOperation has all the info needed
There was a problem hiding this comment.
Done in commit 08e7489. Refactored to use IConversionOperation properties instead of syntax analysis:
!operation.Conversion.IsImplicit- excludes implicit conversions!operation.IsTryCast- excludesasoperator!operation.Conversion.IsUserDefined- excludes user-defined conversions
The key was adding the IsTryCast check that was missing from the original implementation.
…tax analysis Co-authored-by: meziantou <509220+meziantou@users.noreply.github.com>
|
@copilot Tests fail: |
…IsImplicit Co-authored-by: meziantou <509220+meziantou@users.noreply.github.com>
Fixed in commit 9338e3a. The issue was using
Numeric casts like |
Fix Applied
Changed from
operation.Conversion.IsImplicittooperation.IsImplicit:operation.IsImplicitchecks if the operation is implicit in source code (compiler-generated)operation.Conversion.IsImplicitchecks if the conversion is semantically implicit(int)charValuehave explicit syntax but semantically implicit conversionsoperation.IsImplicitcorrectly identifies all explicit casts in source codeThis avoids syntax analysis while properly detecting all cast expressions.
Original prompt
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.