-
Notifications
You must be signed in to change notification settings - Fork 17
Description
Chapter
Associated Items
Guideline Title
Recursive function are not allowed
Category
Required
Status
Draft
Release Begin
1.3.0
Release End
latest
FLS Paragraph ID
fls_vjgkg8kfi93
Decidability
Undecidable
Scope
System
Tags
stack-overflow
Amplification
Any function shall not call itself directly or indirectly
Exception(s)
Recursion may be permitted under the following conditions:
- The recursion termination condition is simple, explicit, and well-defined.
- The function calls itself directly, or with strictly limited and clearly documented indirection.
- The maximum recursion depth is statically bounded and justified, ensuring no risk of stack overflow.
- The rationale for using recursion, rather than iteration, is clearly documented and reviewed.
- The code is accompanied by tests that exercise the recursion boundary conditions.
Rationale
Recursive functions can easily cause stack overflows, which may result in exceptions or, in some cases, undefined behavior (typically some embedded systems). Although the Rust compiler supports tail call optimization, this optimization is not guaranteed and depends on the specific implementation and function structure. There is an open RFC to guarantee tail call optimization in the Rust compiler, but this feature has not yet been stabilized. Until tail call optimization is guaranteed and stabilized, developers should avoid using recursive functions to prevent potential stack overflows and ensure program reliability.
Non-Compliant Example - Prose
The below function concat_strings
is not complaint because it call itself and depending on depth of data provided as input it could generate an stack overflow exception or undefine behavior.
Non-Compliant Example - Code
// Recursive enum to represent a string or a list of `MyEnum`
enum MyEnum {
Str(String),
List(Vec<MyEnum>),
}
// Concatenates strings from a nested structure of `MyEnum` using recursion.
fn concat_strings(input: &[MyEnum]) -> String {
let mut result = String::new();
for item in input {
match item {
MyEnum::Str(s) => result.push_str(s),
MyEnum::List(list) => result.push_str(&concat_strings(list)),
}
}
result
}
Compliant Example - Prose
The following code implements the same functionality using iteration instead of recursion. The stack
variable is used to maintain the processing context at each step of the loop. This approach provides explicit control over memory usage. If the stack grows beyond a predefined limit due to the structure or size of the input, the function returns an error rather than risking a stack overflow or out-of-memory exception. This ensures more predictable and robust behavior in resource-constrained environments.
Compliant Example - Code
// Recursive enum to represent a string or a list of `MyEnum`
enum MyEnum {
Str(String),
List(Vec<MyEnum>),
}
/// Concatenates strings from a nested structure of `MyEnum` without using recursion.
/// Returns an error if the stack size exceeds `MAX_STACK_SIZE`.
fn concat_strings_non_recursive(input: &[MyEnum]) -> Result<String, &'static str> {
const MAX_STACK_SIZE: usize = 1000;
let mut result = String::new();
let mut stack = Vec::new();
// Add all items to the stack
stack.extend(input.iter());
while let Some(item) = stack.pop() {
match item {
MyEnum::Str(s) => result.insert_str(0, s),
MyEnum::List(list) => {
// Add list items to the stack
for sub_item in list.iter() {
stack.push(sub_item);
if stack.len() > MAX_STACK_SIZE {
return Err("Too big structure");
}
}
}
}
}
Ok(result)
}