CARDIAC › rust-cardiac › Message codes › RCE0013
RCE0013error
Recursion.
error[RCE0013]: recursion ({path}) needs a stack, which only a function calling itself gets here
Recursion the compiler can't give a stack: through more than one function, or of a function whose locals it can't push.
Each function on CARDIAC has cells of its own for its locals, laid out once: there is no stack. A second call of a function before the first returns would write over the first's cells.
A function that calls itself as the last thing it does compiles: the call becomes a loop. So do functions that call one another as the last thing each does (is_even and is_odd): they become one function. A function that calls itself anywhere else gets a stack of its own, in the memory the program leaves over: the locals it still reads after the call are pushed before it and popped after, and a call past the stack's end panics with stack overflow. That takes about 30 cells, and only where its locals and its result are numbers or bools with no reference among them. Recursion through two or more functions, other than at their ends, and recursion of a function that returns a struct or holds a reference, are refused: write them as a loop.
// compiles, with a stack (deep inputs panic: stack overflow)
fn sum(n: i16) -> i16 {
if n == 0 { 0 } else { n + sum(n - 1) }
}
// refused: f calls g, and g calls f, other than at the end
fn f(n: i16) -> i16 { if n == 0 { 0 } else { 1 + g(n - 1) } }
fn g(n: i16) -> i16 { f(n) * 2 }
// compiles, and needs no stack at all
fn sum_loop(mut n: i16) -> i16 {
let mut s = 0;
while n > 0 {
s += n;
n -= 1;
}
s
}
In a terminal: cargo cardiac help RCE0013.