Function body is nothing but a call to itself
ID |
rust.correctness.unconditional_recursion |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
Rust |
Description
Detects a function or method whose entire body is a direct call to itself, written as $F(..), self.$F(..) or Self::$F(..), with or without an explicit return. Only this shape is reported: a body that also contains a conditional, a match or any other statement may well hold the base case, and proving otherwise needs control-flow analysis.
Rationale
With nothing else in the body there is no base case, so every call makes another call until the stack is exhausted. Stack overflow in Rust aborts the process with SIGSEGV and cannot be caught, so no destructor runs and no in-flight work is flushed. The usual cause is a getter or trait method that reads its own name instead of the backing field or the inner value.
The following code illustrates the pattern detected by this rule:
use std::fmt;
pub struct Buf {
items: Vec<u8>,
total: usize,
}
impl Buf {
// FLAGGED: Function body is nothing but a call to itself
pub fn len(&self) -> usize {
self.len()
}
}
Remediation
Point the call at what it was meant to reach — the field (self.items.len()), the inner value (self.0.next()), or the helper that was renamed. Where the recursion is intended, add the base case that returns before the self-call, and prefer an explicit loop with a Vec used as a stack when the depth is driven by untrusted input.