Skip to content

A generic function that calls itself overflows the compiler's stack (rc 139, no diagnostic) #2533

Closed

Description

@ehartford

Repro

fn depth[T](xs: List[T]) -> isize:
    if xs.len() == 0: 0 else: 1 + depth(xs)
fn main:
    let xs: List[i32] = [1, 2, 3]
    print(f"{depth(xs)}")

with check exits 139 with no diagnostic (v0.15.3.0-g8182ccfb1). Any generic free function that calls itself: the if-tail form overflows the stack; the explicit-return form (return 1 + depth(xs)) survives only because some cutoff ends it after about 450 body checks, and then compiles a body that was checked hundreds of times.

Where (lldb, installed compiler)

The cycle in the backtrace: check_fn_body_concrete (SemaCheck.w:6763) → check_fn_body_with_sig_at → … → check_call → check_generic_call (SemaCheck.w:28248) → check_fn_body_concrete. check_generic_call fills generic_specialization_cache only after the body check returns, so the recursive call inside the body finds no entry and instantiates the same key again, without end. Sema.check_fn_body_concrete hit 735 times before EXC_BAD_ACCESS at the stack top.

Fix

A specialization key in flight is recorded before its body check; a call that meets its own instance takes the declared return type for the instance and binds to the signature the body check added before it began (add_sig at SemaCheck.w:6700). With no annotation it reads Unit, as a non-generic recursive call does under D43 today. Branch generic-recursion, fixture behav_generic_fn_calls_itself.w.

Surfaced by the generic quicksort (fn quicksort[T](xs: List[T]) -> List[T]).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions