/* =============================================================================
 * 03_setjmp_longjmp.c -- a nonlocal jump: C's version of throw/catch
 * =============================================================================
 *
 * [Idea]
 *   return and ret unwind ONE stack frame. Sometimes you need to bail out of a
 *   DEEP call chain in one leap -- an error found five calls down, recovered at
 *   the top -- without every function in between checking and propagating an
 *   error code. setjmp/longjmp do exactly that:
 *     - setjmp(buf) saves the current register/stack state into buf and returns 0.
 *     - longjmp(buf, v) from anywhere later restores that state, so control
 *       reappears AT the setjmp call site, which this time returns v (nonzero).
 *   It is a controlled form of exceptional control flow: the "try" is setjmp,
 *   the "throw" is longjmp, the "catch" is the setjmp!=0 branch.
 *
 * [What it answers]
 *   - How do you jump out of nested calls without unwinding frame by frame?
 *   - Why does setjmp "return twice" (0 the first time, v after a longjmp)?
 *   - When is this the right tool, and what are its sharp edges?
 *
 * Build & run:    make run
 *
 * This demo is fully deterministic: the same output every run.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

/* The saved landing point. A longjmp(err_env, code) anywhere below returns
   control to the setjmp(err_env) call in main. */
static jmp_buf err_env;

/* A deep computation: parse "digits" and sum them, but ABORT on a non-digit.
   Instead of returning an error up through every level, it longjmps straight
   back to main's recovery point. */
static int digit_value(char c)
{
    if (c < '0' || c > '9') {
        printf("    digit_value: '%c' is not a digit -- longjmp back to main\n", c);
        longjmp(err_env, 42);        /* the "throw": jump out, carrying code 42 */
    }
    return c - '0';
}

static int sum_digits(const char *s)
{
    int total = 0;
    for (const char *p = s; *p; p++) {
        printf("    sum_digits: adding '%c'\n", *p);
        total += digit_value(*p);    /* may never return (it may longjmp) */
    }
    return total;
}

int main(void)
{
    /* setjmp returns 0 the first time (we just saved the landing point);
       after a longjmp it "returns again" here with the longjmp's value. */
    int code = setjmp(err_env);

    if (code == 0) {
        /* ---- the TRY block: first time through ---- */
        printf("[try] parsing \"345\" (all digits)\n");
        printf("[try] sum = %d\n", sum_digits("345"));

        printf("[try] parsing \"3x5\" (has a non-digit)\n");
        printf("[try] sum = %d\n", sum_digits("3x5"));   /* will longjmp mid-way */

        printf("[try] this line is NEVER reached\n");
    } else {
        /* ---- the CATCH block: we arrived here via longjmp ---- */
        printf("[catch] recovered via longjmp with code %d; "
               "the deep call was abandoned cleanly\n", code);
    }

    printf("[done] program continues normally after recovery\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   [try] parsing "345" (all digits)
 *       sum_digits: adding '3' / '4' / '5'
 *   [try] sum = 12
 *   [try] parsing "3x5" (has a non-digit)
 *       sum_digits: adding '3'
 *       sum_digits: adding 'x'
 *       digit_value: 'x' is not a digit -- longjmp back to main
 *   [catch] recovered via longjmp with code 42; the deep call was abandoned
 *   [done] program continues normally after recovery
 *
 *   - The first parse ("345") returns normally: sum = 3+4+5 = 12.
 *   - The second hits 'x' two calls deep and longjmps STRAIGHT to main's setjmp,
 *     skipping the rest of sum_digits and the "NEVER reached" line. setjmp,
 *     which first returned 0, now "returns" 42 -- one call site, two returns.
 *   - This is try/throw/catch in C. Its sharp edge: locals in the function that
 *     called setjmp may hold indeterminate values after a longjmp unless marked
 *     `volatile`; and longjmp is not safe to use to leave a signal handler in
 *     general. Use it sparingly, for genuine nonlocal error recovery.
 */
