Create rule S7440: Formatting trait implementations should not be recursive (#4783)

* Create rule S7440

* 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:
github-actions[bot] 2025-03-19 13:06:39 +00:00 committed by GitHub
parent 314d4b0ed2
commit 6919fdfd79
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,2 @@
{
}

View File

@ -0,0 +1,24 @@
{
"title": "Formatting trait implementations should not be recursive",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"clippy"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7440",
"sqKey": "S7440",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "MEDIUM"
},
"attribute": "LOGICAL"
}
}

View File

@ -0,0 +1,38 @@
== Why is this an issue?
Recursive calls in formatting trait implementations (e.g., `Display`) will lead to infinite recursion and a stack overflow.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
use std::fmt;
struct Structure(i32);
impl fmt::Display for Structure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_string()) // Noncompliant
}
}
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
use std::fmt;
struct Structure(i32);
impl fmt::Display for Structure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0) // Compliant
}
}
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#recursive_format_impl