Skip to main content

byteflow/
supplement.rs

1//! Ordered chain of flow supplements in front of an owner.
2//!
3//! [`install_supplement_door`] adds a door function to a [`Program`]. The
4//! host spawns it with the owner Cap in `r0`. The door registers
5//! `registry_name` and then serves three `Ask`s:
6//!
7//! | Tag | Payload | Effect |
8//! |-----|---------|--------|
9//! | [`TAG_SUPP_ATTACH`] | record `[index: Int, cap: Cap]` | Insert that Cap at `index` (`index == len` appends). |
10//! | [`TAG_SUPP_DETACH`] | `Int` index | Remove that slot. |
11//! | [`TAG_SUPP_ENTER`] | any value | Walk the chain, then deliver what remains to the owner. |
12//!
13//! Each supplement receives [`TAG_SUPP_JUDGE`] and answers
14//! [`TAG_SUPP_FOLLOW`] (keep the value), [`TAG_SUPP_REJECT`] (stop; the
15//! owner is not asked), or [`TAG_SUPP_REPLACE`] (continue with the reply
16//! payload). A supplement that exits first is [`TAG_SUPP_REJECT`]: the
17//! door does not skip a dead step. The owner is asked with
18//! [`TAG_SUPP_DELIVER`] and uses the same three answers. The door's reply
19//! to the caller is [`TAG_SUPP_FOLLOW`] with the final value, or
20//! [`TAG_SUPP_REJECT`].
21//!
22//! The chain is eight Cap registers inside the door. Tables cannot store
23//! a Cap, and `list_get` takes a constant index, so the walk is unrolled.
24//! Nothing in this module hooks mailbox delivery: the door is an ordinary
25//! flow, and the caller chooses it by Cap.
26//!
27//! # Addressing
28//!
29//! `Ask` needs [`CapRights::ASK`](crate::CapRights::ASK). Bytecode
30//! [`Fn::whereis`](crate::Fn::whereis) mints only
31//! [`CapRights::SEND`](crate::CapRights::SEND). The name the door
32//! registers stores an
33//! [`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING) token whose
34//! holder is the door. Pass that token from [`Runtime::whereis`](crate::Runtime::whereis)
35//! as a spawn argument; the runtime reissues it to the caller with `ASK`.
36//!
37//! The door calls `make_msg`, `msg_tag`, `msg_payload`, `msg_request_id`,
38//! and `msg_reply_cap`. Start the runtime with [`std_native_table`](crate::std_native_table).
39//!
40//! When the door exits, the scheduler revokes every Cap the door holds
41//! and sweeps the registry name. Caps the host still holds stay valid.
42//!
43//! ```
44//! use byteflow::{install_supplement_door, Program};
45//!
46//! fn main() -> Result<(), byteflow::SupplementError> {
47//!     let mut program = Program::new("chain");
48//!     let _door = install_supplement_door(&mut program, "front")?;
49//!     let _chunk = program.build();
50//!     Ok(())
51//! }
52//! ```
53
54use crate::{FuncId, Label, Program, Reg};
55
56/// Slots in one door. Index `0` is asked first.
57pub const SUPPLEMENT_SLOTS: usize = 8;
58
59/// Caller → door: judge `payload`, then deliver what the chain left.
60pub const TAG_SUPP_ENTER: u16 = 0xBF10;
61/// Door → supplement: judge this value.
62pub const TAG_SUPP_JUDGE: u16 = 0xBF11;
63/// Keep the value and continue.
64pub const TAG_SUPP_FOLLOW: u16 = 0xBF12;
65/// Stop the chain. The owner is not asked.
66pub const TAG_SUPP_REJECT: u16 = 0xBF13;
67/// Continue with the reply payload in place of the current value.
68pub const TAG_SUPP_REPLACE: u16 = 0xBF14;
69/// Caller → door: insert a Cap. Payload is record `[index, cap]`.
70pub const TAG_SUPP_ATTACH: u16 = 0xBF15;
71/// Caller → door: drop the slot at this `Int` index.
72pub const TAG_SUPP_DETACH: u16 = 0xBF16;
73/// Door → owner: the value the chain allowed through.
74pub const TAG_SUPP_DELIVER: u16 = 0xBF17;
75
76/// Why a door could not be added to the program.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum SupplementError {
79    /// `register_name` rejects an empty name, so the door is not emitted.
80    EmptyName,
81    /// This program already contains a door for the same registry name.
82    AlreadyInstalled,
83}
84
85impl std::fmt::Display for SupplementError {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        match self {
88            SupplementError::EmptyName => f.write_str("supplement door name must be non-empty"),
89            SupplementError::AlreadyInstalled => {
90                f.write_str("a supplement door for this name is already in the program")
91            }
92        }
93    }
94}
95
96impl std::error::Error for SupplementError {}
97
98/// Add the door and its judge helper to `program`.
99///
100/// The returned function has arity 1: `r0` is the owner Cap. Spawn it,
101/// then wait until [`Runtime::whereis`](crate::Runtime::whereis) returns
102/// the registered token before asking the door.
103pub fn install_supplement_door(
104    program: &mut Program,
105    registry_name: &str,
106) -> Result<FuncId, SupplementError> {
107    if registry_name.is_empty() {
108        return Err(SupplementError::EmptyName);
109    }
110    let door_name = format!("supplement-door:{registry_name}");
111    let judge_name = format!("supplement-judge:{registry_name}");
112    if program.function_index(&door_name).is_some() || program.function_index(&judge_name).is_some()
113    {
114        return Err(SupplementError::AlreadyInstalled);
115    }
116    let judge = emit_judge(program, &judge_name);
117    Ok(emit_door(program, &door_name, registry_name, judge))
118}
119
120/// `Ask` the door to judge `payload`. The reply hop is [`TAG_SUPP_FOLLOW`]
121/// or [`TAG_SUPP_REJECT`].
122pub fn supplement_enter(f: &mut crate::Fn<'_>, door: Reg, payload: Reg) -> Reg {
123    let hop = f.hop_fresh(i32::from(TAG_SUPP_ENTER), payload);
124    f.ask(door, hop)
125}
126
127/// `Ask` the door to insert `cap` at `index` (`Int`). `index == len` appends.
128/// A successful reply's payload is the new length.
129pub fn supplement_attach(f: &mut crate::Fn<'_>, door: Reg, index: Reg, cap: Reg) -> Reg {
130    let packed = f.window(2);
131    f.mov(packed.at(0), index);
132    f.mov(packed.at(1), cap);
133    let record = f.record_pack(&[packed.at(0), packed.at(1)]);
134    let hop = f.hop_fresh(i32::from(TAG_SUPP_ATTACH), record);
135    f.ask(door, hop)
136}
137
138/// `Ask` the door to drop the slot at `index` (`Int`).
139/// A successful reply's payload is the new length.
140pub fn supplement_detach(f: &mut crate::Fn<'_>, door: Reg, index: Reg) -> Reg {
141    let hop = f.hop_fresh(i32::from(TAG_SUPP_DETACH), index);
142    f.ask(door, hop)
143}
144
145#[derive(Clone, Copy)]
146struct ChainCode {
147    len: Reg,
148    slots: [Reg; SUPPLEMENT_SLOTS],
149    empty: Reg,
150    current: Reg,
151    reply_body: Reg,
152    follow: Label,
153    reject: Label,
154}
155
156fn emit_judge(program: &mut Program, name: &str) -> FuncId {
157    program.function(name, 2, |f| {
158        let slot = f.reg(0);
159        let current = f.reg(1);
160        let request = f.hop_fresh(i32::from(TAG_SUPP_JUDGE), current);
161        let reply = f.ask(slot, request);
162        let got = f.hop_tag(reply);
163        let body = f.hop_payload(reply);
164        let verdict = f.load_i32(i32::from(TAG_SUPP_FOLLOW));
165        let out = f.local();
166        f.mov(out, current);
167
168        let reject_lbl = f.label();
169        let replace_lbl = f.label();
170        let pack = f.label();
171
172        let is_exit = f.eq_imm(got, i32::from(crate::TAG_SYS_EXIT));
173        let not_exit = f.label();
174        f.branch_if_falsy(is_exit, not_exit);
175        f.jump(reject_lbl);
176        f.bind(not_exit);
177
178        let is_reject = f.eq_imm(got, i32::from(TAG_SUPP_REJECT));
179        let not_reject = f.label();
180        f.branch_if_falsy(is_reject, not_reject);
181        f.jump(reject_lbl);
182        f.bind(not_reject);
183
184        let is_replace = f.eq_imm(got, i32::from(TAG_SUPP_REPLACE));
185        let not_replace = f.label();
186        f.branch_if_falsy(is_replace, not_replace);
187        f.jump(replace_lbl);
188        f.bind(not_replace);
189
190        let is_follow = f.eq_imm(got, i32::from(TAG_SUPP_FOLLOW));
191        let not_follow = f.label();
192        f.branch_if_falsy(is_follow, not_follow);
193        f.jump(pack);
194        f.bind(not_follow);
195        f.jump(reject_lbl);
196
197        f.bind(reject_lbl);
198        f.set(verdict, i32::from(TAG_SUPP_REJECT));
199        f.jump(pack);
200
201        f.bind(replace_lbl);
202        f.set(verdict, i32::from(TAG_SUPP_REPLACE));
203        f.mov(out, body);
204        f.jump(pack);
205
206        f.bind(pack);
207        let packed = f.window(2);
208        f.mov(packed.at(0), verdict);
209        f.mov(packed.at(1), out);
210        let rec = f.record_pack(&[packed.at(0), packed.at(1)]);
211        f.return_(rec);
212    })
213}
214
215fn emit_door(program: &mut Program, name: &str, registry_name: &str, judge: FuncId) -> FuncId {
216    program.function(name, 1, |f| {
217        let owner = f.reg(0);
218        let registered = f.load_str(registry_name);
219        f.register_name(registered);
220        let empty = f.load_i32(0);
221        let len = f.load_i32(0);
222        let mut slots = [empty; SUPPLEMENT_SLOTS];
223        for slot in &mut slots {
224            *slot = f.load_i32(0);
225        }
226        let chain = ChainCode {
227            len,
228            slots,
229            empty,
230            current: f.local(),
231            reply_body: f.local(),
232            follow: f.label(),
233            reject: f.label(),
234        };
235        let loop_lbl = f.label();
236        f.bind(loop_lbl);
237        let msg = f.receive();
238        let got = f.hop_tag(msg);
239        let payload = f.hop_payload(msg);
240
241        let is_attach = f.eq_imm(got, i32::from(TAG_SUPP_ATTACH));
242        let not_attach = f.label();
243        f.branch_if_falsy(is_attach, not_attach);
244        emit_attach(f, payload, &chain);
245        f.bind(not_attach);
246
247        let is_detach = f.eq_imm(got, i32::from(TAG_SUPP_DETACH));
248        let not_detach = f.label();
249        f.branch_if_falsy(is_detach, not_detach);
250        emit_detach(f, payload, &chain);
251        f.bind(not_detach);
252
253        let is_enter = f.eq_imm(got, i32::from(TAG_SUPP_ENTER));
254        let not_enter = f.label();
255        f.branch_if_falsy(is_enter, not_enter);
256        emit_enter(f, owner, payload, judge, &chain);
257        f.bind(not_enter);
258
259        f.mov(chain.reply_body, chain.empty);
260        f.jump(chain.reject);
261
262        // One reply tail for every path. Unrolling `send_reply` at each
263        // branch would spend a fresh register window per site and overflow
264        // the 255-slot frame.
265        f.bind(chain.follow);
266        f.send_reply(msg, i32::from(TAG_SUPP_FOLLOW), chain.reply_body);
267        f.jump(loop_lbl);
268        f.bind(chain.reject);
269        f.send_reply(msg, i32::from(TAG_SUPP_REJECT), chain.reply_body);
270        f.jump(loop_lbl);
271    })
272}
273
274fn emit_attach(f: &mut crate::Fn<'_>, payload: Reg, chain: &ChainCode) {
275    let idx = f.record_get(payload, 0);
276    let cap = f.record_get(payload, 1);
277    let negative = f.lt_imm(idx, 0);
278    let nonneg = f.label();
279    f.branch_if_falsy(negative, nonneg);
280    f.mov(chain.reply_body, chain.empty);
281    f.jump(chain.reject);
282    f.bind(nonneg);
283
284    let fits = f.le(idx, chain.len);
285    let bad = f.label();
286    f.branch_if_falsy(fits, bad);
287    let room = f.lt_imm(chain.len, SUPPLEMENT_SLOTS as i32);
288    f.branch_if_falsy(room, bad);
289
290    // Shift the tail up so `idx` is a free slot. `i` walks from the back
291    // so a slot is copied before it is overwritten.
292    for i in (1..SUPPLEMENT_SLOTS).rev() {
293        let at = f.load_i32(i as i32);
294        let idx_before = f.lt(idx, at);
295        let skip = f.label();
296        f.branch_if_falsy(idx_before, skip);
297        let within = f.le(at, chain.len);
298        f.branch_if_falsy(within, skip);
299        f.mov(chain.slots[i], chain.slots[i - 1]);
300        f.bind(skip);
301    }
302    for (i, slot) in chain.slots.iter().enumerate() {
303        let is_i = f.eq_imm(idx, i as i32);
304        let skip = f.label();
305        f.branch_if_falsy(is_i, skip);
306        f.mov(*slot, cap);
307        f.bind(skip);
308    }
309    f.add_imm(chain.len, 1);
310    f.mov(chain.reply_body, chain.len);
311    f.jump(chain.follow);
312    f.bind(bad);
313    f.mov(chain.reply_body, chain.empty);
314    f.jump(chain.reject);
315}
316
317fn emit_detach(f: &mut crate::Fn<'_>, idx: Reg, chain: &ChainCode) {
318    let negative = f.lt_imm(idx, 0);
319    let nonneg = f.label();
320    f.branch_if_falsy(negative, nonneg);
321    f.mov(chain.reply_body, chain.empty);
322    f.jump(chain.reject);
323    f.bind(nonneg);
324
325    let in_range = f.lt(idx, chain.len);
326    let bad = f.label();
327    f.branch_if_falsy(in_range, bad);
328
329    for i in 0..SUPPLEMENT_SLOTS - 1 {
330        let at = f.load_i32(i as i32);
331        let idx_le = f.le(idx, at);
332        let skip = f.label();
333        f.branch_if_falsy(idx_le, skip);
334        let next = f.load_i32((i + 1) as i32);
335        let next_in = f.lt(next, chain.len);
336        f.branch_if_falsy(next_in, skip);
337        f.mov(chain.slots[i], chain.slots[i + 1]);
338        f.bind(skip);
339    }
340    let last = f.local();
341    f.mov(last, chain.len);
342    f.sub_imm(last, 1);
343    for (i, slot) in chain.slots.iter().enumerate() {
344        let is_last = f.eq_imm(last, i as i32);
345        let skip = f.label();
346        f.branch_if_falsy(is_last, skip);
347        f.mov(*slot, chain.empty);
348        f.bind(skip);
349    }
350    f.sub_imm(chain.len, 1);
351    f.mov(chain.reply_body, chain.len);
352    f.jump(chain.follow);
353    f.bind(bad);
354    f.mov(chain.reply_body, chain.empty);
355    f.jump(chain.reject);
356}
357
358fn emit_enter(f: &mut crate::Fn<'_>, owner: Reg, payload: Reg, judge: FuncId, chain: &ChainCode) {
359    f.mov(chain.current, payload);
360    for (i, slot) in chain.slots.iter().enumerate() {
361        let at = f.load_i32(i as i32);
362        let live = f.lt(at, chain.len);
363        let skip = f.label();
364        f.branch_if_falsy(live, skip);
365        let ret = f.call(judge, &[*slot, chain.current]);
366        let verdict = f.record_get(ret, 0);
367        let next = f.record_get(ret, 1);
368        let rejected = f.eq_imm(verdict, i32::from(TAG_SUPP_REJECT));
369        let keep = f.label();
370        f.branch_if_falsy(rejected, keep);
371        f.mov(chain.reply_body, chain.current);
372        f.jump(chain.reject);
373        f.bind(keep);
374        let replaced = f.eq_imm(verdict, i32::from(TAG_SUPP_REPLACE));
375        let same = f.label();
376        f.branch_if_falsy(replaced, same);
377        f.mov(chain.current, next);
378        f.bind(same);
379        f.bind(skip);
380    }
381
382    let hop = f.hop_fresh(i32::from(TAG_SUPP_DELIVER), chain.current);
383    let reply = f.ask(owner, hop);
384    let got = f.hop_tag(reply);
385    let body = f.hop_payload(reply);
386    let replaced = f.eq_imm(got, i32::from(TAG_SUPP_REPLACE));
387    let not_replace = f.label();
388    f.branch_if_falsy(replaced, not_replace);
389    f.mov(chain.current, body);
390    f.mov(chain.reply_body, chain.current);
391    f.jump(chain.follow);
392    f.bind(not_replace);
393    let followed = f.eq_imm(got, i32::from(TAG_SUPP_FOLLOW));
394    let not_follow = f.label();
395    f.branch_if_falsy(followed, not_follow);
396    f.mov(chain.reply_body, chain.current);
397    f.jump(chain.follow);
398    f.bind(not_follow);
399    f.mov(chain.reply_body, chain.current);
400    f.jump(chain.reject);
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406    use crate::{Opcode, Program};
407
408    fn function_traps(chunk: &crate::Chunk, id: u32) -> bool {
409        let Some(func) = chunk.function(id) else {
410            return true;
411        };
412        let start = func.entry as usize;
413        let end = chunk
414            .functions
415            .iter()
416            .map(|function| function.entry)
417            .filter(|entry| *entry > func.entry)
418            .min()
419            .unwrap_or(chunk.code.len() as u32) as usize;
420        chunk.code[start..end]
421            .iter()
422            .any(|instruction| instruction.op == Opcode::Trap)
423    }
424
425    #[test]
426    fn empty_name_is_rejected() {
427        let mut program = Program::new("chain");
428        assert_eq!(
429            install_supplement_door(&mut program, ""),
430            Err(SupplementError::EmptyName)
431        );
432    }
433
434    #[test]
435    fn second_door_for_the_same_name_is_rejected() -> Result<(), SupplementError> {
436        let mut program = Program::new("chain");
437        let _door = install_supplement_door(&mut program, "front")?;
438        assert_eq!(
439            install_supplement_door(&mut program, "front"),
440            Err(SupplementError::AlreadyInstalled)
441        );
442        Ok(())
443    }
444
445    #[test]
446    fn door_frame_verifies_without_a_trap() -> Result<(), SupplementError> {
447        let mut program = Program::new("chain");
448        let door = install_supplement_door(&mut program, "front")?;
449        let judge = program
450            .function_index("supplement-judge:front")
451            .unwrap_or(u32::MAX);
452        let chunk = program.build();
453        if let Err(err) = crate::verify(&chunk) {
454            panic!("{err}");
455        }
456        assert!(
457            !function_traps(&chunk, door),
458            "door frame emitted Trap (register file overflow)"
459        );
460        assert!(
461            !function_traps(&chunk, judge),
462            "judge frame emitted Trap (register file overflow)"
463        );
464        Ok(())
465    }
466}