---
source: framec/tests/c_snapshots.rs
expression: "compile_fixture(\"07_forward\", \"c\")"
---
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>

// ============================================================================
// Forward_FrameDict - String-keyed dictionary
// ============================================================================

typedef struct Forward_FrameDictEntry {
    char* key;
    void* value;
    struct Forward_FrameDictEntry* next;
} Forward_FrameDictEntry;

typedef struct {
    Forward_FrameDictEntry** buckets;
    int bucket_count;
    int size;
} Forward_FrameDict;

static unsigned int Forward_hash_string(const char* str) {
    unsigned int hash = 5381;
    int c;
    while ((c = *str++)) {
        hash = ((hash << 5) + hash) + c;
    }
    return hash;
}

static Forward_FrameDict* Forward_FrameDict_new(void) {
    Forward_FrameDict* d = malloc(sizeof(Forward_FrameDict));
    d->bucket_count = 16;
    d->buckets = calloc(d->bucket_count, sizeof(Forward_FrameDictEntry*));
    d->size = 0;
    return d;
}

static void Forward_FrameDict_set(Forward_FrameDict* d, const char* key, void* value) {
    unsigned int idx = Forward_hash_string(key) % d->bucket_count;
    Forward_FrameDictEntry* entry = d->buckets[idx];
    while (entry) {
        if (strcmp(entry->key, key) == 0) {
            entry->value = value;
            return;
        }
        entry = entry->next;
    }
    Forward_FrameDictEntry* new_entry = malloc(sizeof(Forward_FrameDictEntry));
    new_entry->key = strdup(key);
    new_entry->value = value;
    new_entry->next = d->buckets[idx];
    d->buckets[idx] = new_entry;
    d->size++;
}

static void* Forward_FrameDict_get(Forward_FrameDict* d, const char* key) {
    unsigned int idx = Forward_hash_string(key) % d->bucket_count;
    Forward_FrameDictEntry* entry = d->buckets[idx];
    while (entry) {
        if (strcmp(entry->key, key) == 0) {
            return entry->value;
        }
        entry = entry->next;
    }
    return NULL;
}

static int Forward_FrameDict_has(Forward_FrameDict* d, const char* key) {
    unsigned int idx = Forward_hash_string(key) % d->bucket_count;
    Forward_FrameDictEntry* entry = d->buckets[idx];
    while (entry) {
        if (strcmp(entry->key, key) == 0) {
            return 1;
        }
        entry = entry->next;
    }
    return 0;
}

static Forward_FrameDict* Forward_FrameDict_copy(Forward_FrameDict* src) {
    Forward_FrameDict* dst = Forward_FrameDict_new();
    for (int i = 0; i < src->bucket_count; i++) {
        Forward_FrameDictEntry* entry = src->buckets[i];
        while (entry) {
            Forward_FrameDict_set(dst, entry->key, entry->value);
            entry = entry->next;
        }
    }
    return dst;
}

static void Forward_FrameDict_destroy(Forward_FrameDict* d) {
    for (int i = 0; i < d->bucket_count; i++) {
        Forward_FrameDictEntry* entry = d->buckets[i];
        while (entry) {
            Forward_FrameDictEntry* next = entry->next;
            free(entry->key);
            free(entry);
            entry = next;
        }
    }
    free(d->buckets);
    free(d);
}

// ============================================================================
// Forward_FrameVec - Dynamic array
// ============================================================================

typedef struct {
    void** items;
    int size;
    int capacity;
} Forward_FrameVec;

static Forward_FrameVec* Forward_FrameVec_new(void) {
    Forward_FrameVec* v = malloc(sizeof(Forward_FrameVec));
    v->capacity = 8;
    v->size = 0;
    v->items = malloc(sizeof(void*) * v->capacity);
    return v;
}

static void Forward_FrameVec_push(Forward_FrameVec* v, void* item) {
    if (v->size >= v->capacity) {
        v->capacity *= 2;
        v->items = realloc(v->items, sizeof(void*) * v->capacity);
    }
    v->items[v->size++] = item;
}

static void* Forward_FrameVec_pop(Forward_FrameVec* v) {
    if (v->size == 0) return NULL;
    return v->items[--v->size];
}

static void* Forward_FrameVec_last(Forward_FrameVec* v) {
    if (v->size == 0) return NULL;
    return v->items[v->size - 1];
}

static void* Forward_FrameVec_get(Forward_FrameVec* v, int index) {
    if (index < 0 || index >= v->size) return NULL;
    return v->items[index];
}

static int Forward_FrameVec_size(Forward_FrameVec* v) {
    return v->size;
}

static void Forward_FrameVec_destroy(Forward_FrameVec* v) {
    if (!v) return;
    free(v->items);
    free(v);
}

static Forward_FrameVec* Forward_FrameVec_copy(Forward_FrameVec* src) {
    if (!src) return NULL;
    Forward_FrameVec* v = Forward_FrameVec_new();
    for (int i = 0; i < src->size; i++) {
        Forward_FrameVec_push(v, src->items[i]);
    }
    return v;
}

// ============================================================================
// Forward_pack_double / Forward_unpack_double — bit-pun doubles through void*
// ============================================================================

static inline void* Forward_pack_double(double v) {
    void* p = 0;
    memcpy(&p, &v, sizeof(double));
    return p;
}

static inline double Forward_unpack_double(void* p) {
    double d;
    memcpy(&d, &p, sizeof(double));
    return d;
}

// ============================================================================
// Forward_FrameEvent - Event routing object
// ============================================================================

typedef struct {
    const char* _message;
    Forward_FrameVec* _parameters;
    int _owns_parameters;
} Forward_FrameEvent;

static Forward_FrameEvent* Forward_FrameEvent_new(const char* message, Forward_FrameVec* parameters, int owns_parameters) {
    Forward_FrameEvent* e = malloc(sizeof(Forward_FrameEvent));
    e->_message = message;
    e->_parameters = parameters;
    e->_owns_parameters = owns_parameters;
    return e;
}

static void Forward_FrameEvent_destroy(Forward_FrameEvent* e) {
    if (e->_owns_parameters && e->_parameters) Forward_FrameVec_destroy(e->_parameters);
    free(e);
}

// ============================================================================
// Forward_FrameContext - Interface call context
// ============================================================================

typedef struct {
    Forward_FrameEvent* event;
    void* _return;
    Forward_FrameDict* _data;
    int _transitioned;
} Forward_FrameContext;

static Forward_FrameContext* Forward_FrameContext_new(Forward_FrameEvent* event, void* default_return) {
    Forward_FrameContext* ctx = malloc(sizeof(Forward_FrameContext));
    ctx->event = event;
    ctx->_return = default_return;
    ctx->_data = Forward_FrameDict_new();
    ctx->_transitioned = 0;
    return ctx;
}

static void Forward_FrameContext_destroy(Forward_FrameContext* ctx) {
    Forward_FrameDict_destroy(ctx->_data);
    free(ctx);
}

// ============================================================================
// Forward_Compartment - State closure
// ============================================================================

typedef struct Forward_Compartment {
    const char* state;
    Forward_FrameVec* state_args;
    Forward_FrameDict* state_vars;
    Forward_FrameVec* enter_args;
    Forward_FrameVec* exit_args;
    Forward_FrameEvent* forward_event;
    struct Forward_Compartment* parent_compartment;
    int _ref_count;
} Forward_Compartment;

static Forward_Compartment* Forward_Compartment_new(const char* state) {
    Forward_Compartment* c = malloc(sizeof(Forward_Compartment));
    c->state = state;
    c->state_args = Forward_FrameVec_new();
    c->state_vars = Forward_FrameDict_new();
    c->enter_args = Forward_FrameVec_new();
    c->exit_args = Forward_FrameVec_new();
    c->forward_event = NULL;
    c->parent_compartment = NULL;
    c->_ref_count = 1;
    return c;
}

static Forward_Compartment* Forward_Compartment_ref(Forward_Compartment* c) {
    if (c) c->_ref_count++;
    return c;
}

static void Forward_Compartment_unref(Forward_Compartment* c);
static void Forward_Compartment_unref(Forward_Compartment* c) {
    if (c == NULL) return;
    c->_ref_count--;
    if (c->_ref_count <= 0) {
        Forward_Compartment_unref(c->parent_compartment);
        Forward_FrameVec_destroy(c->state_args);
        Forward_FrameDict_destroy(c->state_vars);
        Forward_FrameVec_destroy(c->enter_args);
        Forward_FrameVec_destroy(c->exit_args);
        free(c);
    }
}

static Forward_Compartment* Forward_Compartment_copy(Forward_Compartment* src) {
    Forward_Compartment* c = malloc(sizeof(Forward_Compartment));
    c->state = src->state;
    c->state_args = Forward_FrameVec_copy(src->state_args);
    c->state_vars = Forward_FrameDict_copy(src->state_vars);
    c->enter_args = Forward_FrameVec_copy(src->enter_args);
    c->exit_args = Forward_FrameVec_copy(src->exit_args);
    c->forward_event = src->forward_event;  // Shallow copy OK
    c->parent_compartment = src->parent_compartment;
    return c;
}

static void Forward_Compartment_destroy(Forward_Compartment* c) {
    Forward_FrameVec_destroy(c->state_args);
    Forward_FrameDict_destroy(c->state_vars);
    Forward_FrameVec_destroy(c->enter_args);
    Forward_FrameVec_destroy(c->exit_args);
    free(c);
}

// Helper macros for context access
#define Forward_CTX(self) ((Forward_FrameContext*)Forward_FrameVec_last((self)->_context_stack))
#define Forward_PARAM(self, key) Forward_FrameDict_get(Forward_CTX(self)->event->_parameters, key)
#define Forward_RETURN(self) Forward_CTX(self)->_return
#define Forward_DATA(self, key) Forward_FrameDict_get(Forward_CTX(self)->_data, key)
#define Forward_DATA_SET(self, key, val) Forward_FrameDict_set(Forward_CTX(self)->_data, key, val)

// Forward declarations
typedef struct Forward Forward;
static void Forward_kernel(Forward* self, Forward_FrameEvent* __e);
static void Forward_router(Forward* self, Forward_FrameEvent* __e);
static void Forward_transition(Forward* self, Forward_Compartment* next);
static int Forward_hsm_chain(Forward* self, const char* leaf, const char*** out_chain);
static Forward_Compartment* Forward_prepareEnter(Forward* self, const char* leaf, Forward_FrameVec* state_args, Forward_FrameVec* enter_args);
static void Forward_prepareExit(Forward* self, Forward_FrameVec* exit_args);
static void Forward_state_Start(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment);
static void Forward_state_Middle(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment);
static void Forward_state_End(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment);
static void Forward_s_Start_hdl_user_run(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment);
static void Forward_s_Middle_hdl_user_finish(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment);
static void Forward_s_Middle_hdl_user_run(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment);
static void Forward_s_End_hdl_user_finish(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment);
void Forward_run (Forward* self);
void Forward_finish (Forward* self);

struct Forward {
    Forward_FrameVec* _state_stack;
    Forward_Compartment* __compartment;
    Forward_Compartment* __next_compartment;
    Forward_FrameVec* _context_stack;
    int starts;
    int middles;
};

Forward* Forward_new(void) {
    Forward* self = calloc(1, sizeof(Forward));
    self->_state_stack = Forward_FrameVec_new();
    self->_context_stack = Forward_FrameVec_new();
    self->starts = 0;
    self->middles = 0;
    Forward_FrameVec* __sa = NULL;
    Forward_FrameVec* __ea = NULL;
    self->__compartment = Forward_prepareEnter(self, "Start", __sa, __ea);
    self->__next_compartment = NULL;
    Forward_FrameEvent* __e = Forward_FrameEvent_new("$>", self->__compartment->enter_args, 0);
    Forward_FrameContext* __ctx = Forward_FrameContext_new(__e, NULL);
    Forward_FrameVec_push(self->_context_stack, __ctx);
    Forward_FrameContext* __init_ctx = (Forward_FrameContext*)Forward_FrameVec_pop(self->_context_stack);
    Forward_FrameContext_destroy(__init_ctx);
    Forward_FrameEvent_destroy(__e);
    return self;
}

Forward* Forward_create(void) {
    Forward* self = Forward_new();
    self->_state_stack = Forward_FrameVec_new();
    self->_context_stack = Forward_FrameVec_new();
    self->starts = 0;
    self->middles = 0;
    Forward_FrameVec* __sa = NULL;
    Forward_FrameVec* __ea = NULL;
    self->__compartment = Forward_prepareEnter(self, "Start", __sa, __ea);
    self->__next_compartment = NULL;
    Forward_FrameEvent* __e = Forward_FrameEvent_new("$>", self->__compartment->enter_args, 0);
    Forward_FrameContext* __ctx = Forward_FrameContext_new(__e, NULL);
    Forward_FrameVec_push(self->_context_stack, __ctx);
    Forward_kernel(self, __e);
    Forward_FrameContext* __init_ctx = (Forward_FrameContext*)Forward_FrameVec_pop(self->_context_stack);
    Forward_FrameContext_destroy(__init_ctx);
    Forward_FrameEvent_destroy(__e);
    return self;
}

static int Forward_hsm_chain(Forward* self, const char* leaf, const char*** out_chain) {
    if (false) { (void)0; }
        else if (strcmp(leaf, "Start") == 0) {
            static const char* __chain[] = { "Start" };
            *out_chain = __chain;
            return 1;
        }
        else if (strcmp(leaf, "Middle") == 0) {
            static const char* __chain[] = { "Middle" };
            *out_chain = __chain;
            return 1;
        }
        else if (strcmp(leaf, "End") == 0) {
            static const char* __chain[] = { "End" };
            *out_chain = __chain;
            return 1;
        }
        *out_chain = NULL;
        return 0;
}

static Forward_Compartment* Forward_prepareEnter(Forward* self, const char* leaf, Forward_FrameVec* state_args, Forward_FrameVec* enter_args) {
    const char** chain = NULL;
    int n = Forward_hsm_chain(self, leaf, &chain);
    Forward_Compartment* comp = NULL;
    for (int i = 0; i < n; i++) {
        Forward_Compartment* nc = Forward_Compartment_new(chain[i]);
        if (state_args) {
            for (int j = 0; j < state_args->size; j++) Forward_FrameVec_push(nc->state_args, state_args->items[j]);
        }
        if (enter_args) {
            for (int j = 0; j < enter_args->size; j++) Forward_FrameVec_push(nc->enter_args, enter_args->items[j]);
        }
        nc->parent_compartment = comp;  // adopts ref
        comp = nc;
    }
    return comp;
}

static void Forward_prepareExit(Forward* self, Forward_FrameVec* exit_args) {
    Forward_Compartment* comp = self->__compartment;
    while (comp != NULL) {
        // Clear any prior exit_args before copying the new ones in.
        while (comp->exit_args->size > 0) comp->exit_args->size--;
        if (exit_args) {
            for (int j = 0; j < exit_args->size; j++) Forward_FrameVec_push(comp->exit_args, exit_args->items[j]);
        }
        comp = comp->parent_compartment;
    }
}

static void Forward_kernel(Forward* self, Forward_FrameEvent* __e) {
    Forward_router(self, __e);
    while (self->__next_compartment != NULL) {
        Forward_Compartment* next_compartment = self->__next_compartment;
        self->__next_compartment = NULL;
        // Exit the current (leaf) state
        Forward_FrameEvent* __exit_event = Forward_FrameEvent_new("<$", self->__compartment->exit_args, 0);
        Forward_router(self, __exit_event);
        Forward_FrameEvent_destroy(__exit_event);
        Forward_Compartment_unref(self->__compartment);
        self->__compartment = next_compartment;
        if (next_compartment->forward_event == NULL) {
            // No forwarded event — synthesize a fresh $>
            Forward_FrameEvent* __enter_event = Forward_FrameEvent_new("$>", self->__compartment->enter_args, 0);
            Forward_router(self, __enter_event);
            Forward_FrameEvent_destroy(__enter_event);
        } else if (strcmp(next_compartment->forward_event->_message, "$>") == 0) {
            // Forwarded event IS $> — dispatch directly so the
            // destination's $> handler receives the caller's payload.
            // The forward_event is borrowed (owned by the wrapper that
            // queued the transition) — do NOT destroy it here.
            Forward_FrameEvent* forward_event = next_compartment->forward_event;
            next_compartment->forward_event = NULL;
            Forward_router(self, forward_event);
        } else {
            // Forwarded event is not $> — initialize the destination
            // with a fresh $>, then dispatch the forward to it. The
            // forward_event is borrowed; only the synthesized $> belongs
            // to the kernel and is freed here.
            Forward_FrameEvent* forward_event = next_compartment->forward_event;
            next_compartment->forward_event = NULL;
            Forward_FrameEvent* __enter_event = Forward_FrameEvent_new("$>", self->__compartment->enter_args, 0);
            Forward_router(self, __enter_event);
            Forward_FrameEvent_destroy(__enter_event);
            Forward_router(self, forward_event);
        }
        // Mark every stacked context as having transitioned. Read by
        // @@:self.X() guard so outer self-calls short-circuit.
        for (int __i = 0; __i < self->_context_stack->size; __i++) {
            ((Forward_FrameContext*)self->_context_stack->items[__i])->_transitioned = 1;
        }
    }
}

static void Forward_router(Forward* self, Forward_FrameEvent* __e) {
    if (strcmp(self->__compartment->state, "Start") == 0) {
        Forward_state_Start(self, __e, self->__compartment);
    } else if (strcmp(self->__compartment->state, "Middle") == 0) {
        Forward_state_Middle(self, __e, self->__compartment);
    } else if (strcmp(self->__compartment->state, "End") == 0) {
        Forward_state_End(self, __e, self->__compartment);
    }
}

static void Forward_transition(Forward* self, Forward_Compartment* next_compartment) {
    self->__next_compartment = next_compartment;
}

void Forward_destroy(Forward* self) {
    // Unref current compartment (may free if not on stack)
    if (self->__compartment) Forward_Compartment_unref(self->__compartment);
    if (self->__next_compartment) Forward_Compartment_unref(self->__next_compartment);
    // Unref all state stack entries
    if (self->_state_stack) {
        for (int __i = 0; __i < self->_state_stack->size; __i++) {
            Forward_Compartment_unref((Forward_Compartment*)self->_state_stack->items[__i]);
        }
        Forward_FrameVec_destroy(self->_state_stack);
    }
    if (self->_context_stack) Forward_FrameVec_destroy(self->_context_stack);
    free(self);
}

void Forward_run(Forward* self) {
    Forward_FrameEvent* __e = Forward_FrameEvent_new("run", NULL, 0);
    Forward_FrameContext* __ctx = Forward_FrameContext_new(__e, NULL);
    Forward_FrameVec_push(self->_context_stack, __ctx);
    Forward_kernel(self, __e);
    Forward_FrameContext* __result_ctx = (Forward_FrameContext*)Forward_FrameVec_pop(self->_context_stack);
    Forward_FrameContext_destroy(__result_ctx);
    Forward_FrameEvent_destroy(__e);
}

void Forward_finish(Forward* self) {
    Forward_FrameEvent* __e = Forward_FrameEvent_new("finish", NULL, 0);
    Forward_FrameContext* __ctx = Forward_FrameContext_new(__e, NULL);
    Forward_FrameVec_push(self->_context_stack, __ctx);
    Forward_kernel(self, __e);
    Forward_FrameContext* __result_ctx = (Forward_FrameContext*)Forward_FrameVec_pop(self->_context_stack);
    Forward_FrameContext_destroy(__result_ctx);
    Forward_FrameEvent_destroy(__e);
}

static void Forward_state_Start(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment) {
    if (strcmp(__e->_message, "run") == 0) {
        Forward_s_Start_hdl_user_run(self, __e, compartment);
        return;
    }
}

static void Forward_state_Middle(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment) {
    if (strcmp(__e->_message, "finish") == 0) {
        Forward_s_Middle_hdl_user_finish(self, __e, compartment);
        return;
    }
    if (strcmp(__e->_message, "run") == 0) {
        Forward_s_Middle_hdl_user_run(self, __e, compartment);
        return;
    }
}

static void Forward_state_End(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment) {
    if (strcmp(__e->_message, "finish") == 0) {
        Forward_s_End_hdl_user_finish(self, __e, compartment);
        return;
    }
}

static void Forward_s_Start_hdl_user_run(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment) {
    self.starts = self.starts + 1;
    Forward_Compartment* __compartment = Forward_prepareEnter(self, "Middle", NULL, NULL);
    __compartment->forward_event = __e;
    Forward_transition(self, __compartment);
    return;
}

static void Forward_s_Middle_hdl_user_finish(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment) {
    {
        Forward_FrameVec* __sa = NULL;
        Forward_FrameVec* __ea = NULL;
        Forward_Compartment* __compartment = Forward_prepareEnter(self, "End", __sa, __ea);
        Forward_transition(self, __compartment);
    }
    return;
}

static void Forward_s_Middle_hdl_user_run(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment) {
    self.middles = self.middles + 1
}

static void Forward_s_End_hdl_user_finish(Forward* self, Forward_FrameEvent* __e, Forward_Compartment* compartment) {
}
