Create rule S4325: Redundant casts should be avoided (#4729)
* Add rust to rule S4325 * Update RSPEC --------- Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com> Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
This commit is contained in:
parent
c5bb992c80
commit
ef35f53a80
@ -31,4 +31,4 @@
|
||||
"compatibleLanguages": [
|
||||
"ts"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
@ -1,2 +1,35 @@
|
||||
{
|
||||
"title": "Redundant casts and non-null assertions should be avoided",
|
||||
"type": "CODE_SMELL",
|
||||
"code": {
|
||||
"impacts": {
|
||||
"MAINTAINABILITY": "LOW"
|
||||
},
|
||||
"attribute": "CLEAR"
|
||||
},
|
||||
"status": "ready",
|
||||
"remediation": {
|
||||
"func": "Constant\/Issue",
|
||||
"constantCost": "1min"
|
||||
},
|
||||
"tags": [
|
||||
"redundant",
|
||||
"type-dependent"
|
||||
],
|
||||
"extra": {
|
||||
"replacementRules": [
|
||||
|
||||
],
|
||||
"legacyKeys": [
|
||||
|
||||
]
|
||||
},
|
||||
"defaultSeverity": "Minor",
|
||||
"ruleSpecification": "RSPEC-4325",
|
||||
"sqKey": "S4325",
|
||||
"scope": "Main",
|
||||
"defaultQualityProfiles": [
|
||||
"Sonar way"
|
||||
],
|
||||
"quickfix": "covered"
|
||||
}
|
||||
|
7
rules/S4325/rust/metadata.json
Normal file
7
rules/S4325/rust/metadata.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"title": "Redundant casts should be avoided",
|
||||
"tags": [
|
||||
"redundant",
|
||||
"clippy"
|
||||
]
|
||||
}
|
28
rules/S4325/rust/rule.adoc
Normal file
28
rules/S4325/rust/rule.adoc
Normal file
@ -0,0 +1,28 @@
|
||||
== Why is this an issue?
|
||||
|
||||
In Rust, type casting is a mechanism used to convert a value from one type to another. This is often necessary when working with different types that are compatible but not the same. However, unnecessary casts can occur when the type conversion is redundant because the compiler already knows the type based on the context or explicit type declarations.
|
||||
|
||||
Unnecessary casts should be avoided in Rust code as they add unnecessary complexity, clutter the code, and can lead to confusion. They also make the code less idiomatic and harder to read.
|
||||
|
||||
[source,rust,diff-id=1,diff-type=noncompliant]
|
||||
----
|
||||
fn get_length(value: &str) -> usize {
|
||||
let length = value.len() as usize; // Noncompliant: 'value.len()' already returns a 'usize'
|
||||
length
|
||||
}
|
||||
----
|
||||
|
||||
Remove all unnecessary casts based on the contextual typing information, as inferred by the Rust compiler.
|
||||
|
||||
[source,rust,diff-id=1,diff-type=compliant]
|
||||
----
|
||||
fn get_length(value: &str) -> usize {
|
||||
let length = value.len();
|
||||
length
|
||||
}
|
||||
----
|
||||
|
||||
== Resources
|
||||
=== Documentation
|
||||
|
||||
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
|
Loading…
x
Reference in New Issue
Block a user