Lifecycle hooks: @OnStart/@OnQuit, @OnDespawn, @OnAttach (like @OnSpawn)

Adds the rest of the game/entity/property lifecycle as @-hooks, each firing at
one timeline moment and reducing to ordinary code:

- @OnStart / @OnQuit (program): @OnStart aliases the Start phase; @OnQuit runs in
  the frame loop's done: block, after the loop stops and before teardown.
- @OnDespawn(Model) (entity): a destructor. Despawn doesn't statically know the
  entity's model, so hooks compile to @on_despawn_<Model>(entity) functions and
  emit_despawn dispatches on @L_kind. Symmetric with @OnSpawn.
- @OnAttach(Property): fires in emit_init_component once a property is attached
  and seeded, with the property bound by name.

Registries + parsing mirror @OnSpawn. examples/lifecycle.ludic narrates the whole
timeline (output 1 700 50 950 2). Behaviour-preserving (goldens byte-identical,
despawn users unaffected when no hooks registered); test.sh 16/16, fixpoint holds.

Deferred: @OnDetach (per-property runtime dispatch) and scene @OnEnter/@OnExit
(need scene support in the compiler).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Orkun ÇAKILKAYA 2026-08-27 21:15:50 +03:00
parent 28abd3a2c3
commit 6e11212cf2
8 changed files with 3993 additions and 3258 deletions

View file

@ -37,6 +37,16 @@ fn emit_init_component(e: ptr, comp: ptr, rec: Node) -> void {
j = j + 1
}
}
# @OnAttach(Property) runs once the property is attached and seeded
let ab = onattach_body(comp)
if not ptr_is_null(ab) {
let save = nloc
let vslot = emit_alloca("ptr")
emit(" store ptr "); emit(slot); emit(", ptr "); emit(vslot); emit("\n")
loc_push(comp, vslot, comp)
emit_block(ab)
nloc = save
}
}
# bind each of a model's properties to entity `e`'s component storage, so an
@ -87,5 +97,21 @@ fn emit_spawn(st: Node) -> void {
fn emit_despawn(st: Node) -> void {
let v = emit_expr(st.a)
# @OnDespawn: dispatch on the entity's kind and run the matching model's hook
if len(g_ondespawn) > 0 {
let me = itoa(MAX_ENT)
let kp = nreg(); emit(" "); emit(kp); emit(" = getelementptr inbounds ["); emit(me); emit(" x i32], ptr @L_kind, i32 0, i32 "); emit(v.code); emit("\n")
let kind = emit_bind(sconcat("load i32, ptr ", kp))
let i = 0
while i < len(g_ondespawn) {
let mname = g_ondespawn[i].s
let c = emit_bind(sconcat("icmp eq i32 ", sconcat(kind, sconcat(", ", itoa(find_arch_id(mname))))))
let yes = lbl("dh"); let no = lbl("dhn")
emit(" br i1 "); emit(c); emit(", label %"); emit(yes); emit(", label %"); emit(no); emit("\n")
emit(yes); emit(":\n call void @on_despawn_"); emit(mname); emit("(i32 "); emit(v.code); emit(")\n")
emit(" br label %"); emit(no); emit("\n"); emit(no); emit(":\n")
i = i + 1
}
}
emit(" call void @L_free_entity(i32 "); emit(v.code); emit(")\n")
}