use crate::{FuncId, Label, Program, Reg};
pub const SUPPLEMENT_SLOTS: usize = 8;
pub const TAG_SUPP_ENTER: u16 = 0xBF10;
pub const TAG_SUPP_JUDGE: u16 = 0xBF11;
pub const TAG_SUPP_FOLLOW: u16 = 0xBF12;
pub const TAG_SUPP_REJECT: u16 = 0xBF13;
pub const TAG_SUPP_REPLACE: u16 = 0xBF14;
pub const TAG_SUPP_ATTACH: u16 = 0xBF15;
pub const TAG_SUPP_DETACH: u16 = 0xBF16;
pub const TAG_SUPP_DELIVER: u16 = 0xBF17;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SupplementError {
EmptyName,
AlreadyInstalled,
}
impl std::fmt::Display for SupplementError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SupplementError::EmptyName => f.write_str("supplement door name must be non-empty"),
SupplementError::AlreadyInstalled => {
f.write_str("a supplement door for this name is already in the program")
}
}
}
}
impl std::error::Error for SupplementError {}
pub fn install_supplement_door(
program: &mut Program,
registry_name: &str,
) -> Result<FuncId, SupplementError> {
if registry_name.is_empty() {
return Err(SupplementError::EmptyName);
}
let door_name = format!("supplement-door:{registry_name}");
let judge_name = format!("supplement-judge:{registry_name}");
if program.function_index(&door_name).is_some() || program.function_index(&judge_name).is_some()
{
return Err(SupplementError::AlreadyInstalled);
}
let judge = emit_judge(program, &judge_name);
Ok(emit_door(program, &door_name, registry_name, judge))
}
pub fn supplement_enter(f: &mut crate::Fn<'_>, door: Reg, payload: Reg) -> Reg {
let hop = f.hop_fresh(i32::from(TAG_SUPP_ENTER), payload);
f.ask(door, hop)
}
pub fn supplement_attach(f: &mut crate::Fn<'_>, door: Reg, index: Reg, cap: Reg) -> Reg {
let packed = f.window(2);
f.mov(packed.at(0), index);
f.mov(packed.at(1), cap);
let record = f.record_pack(&[packed.at(0), packed.at(1)]);
let hop = f.hop_fresh(i32::from(TAG_SUPP_ATTACH), record);
f.ask(door, hop)
}
pub fn supplement_detach(f: &mut crate::Fn<'_>, door: Reg, index: Reg) -> Reg {
let hop = f.hop_fresh(i32::from(TAG_SUPP_DETACH), index);
f.ask(door, hop)
}
#[derive(Clone, Copy)]
struct ChainCode {
len: Reg,
slots: [Reg; SUPPLEMENT_SLOTS],
empty: Reg,
current: Reg,
reply_body: Reg,
follow: Label,
reject: Label,
}
fn emit_judge(program: &mut Program, name: &str) -> FuncId {
program.function(name, 2, |f| {
let slot = f.reg(0);
let current = f.reg(1);
let request = f.hop_fresh(i32::from(TAG_SUPP_JUDGE), current);
let reply = f.ask(slot, request);
let got = f.hop_tag(reply);
let body = f.hop_payload(reply);
let verdict = f.load_i32(i32::from(TAG_SUPP_FOLLOW));
let out = f.local();
f.mov(out, current);
let reject_lbl = f.label();
let replace_lbl = f.label();
let pack = f.label();
let is_exit = f.eq_imm(got, i32::from(crate::TAG_SYS_EXIT));
let not_exit = f.label();
f.branch_if_falsy(is_exit, not_exit);
f.jump(reject_lbl);
f.bind(not_exit);
let is_reject = f.eq_imm(got, i32::from(TAG_SUPP_REJECT));
let not_reject = f.label();
f.branch_if_falsy(is_reject, not_reject);
f.jump(reject_lbl);
f.bind(not_reject);
let is_replace = f.eq_imm(got, i32::from(TAG_SUPP_REPLACE));
let not_replace = f.label();
f.branch_if_falsy(is_replace, not_replace);
f.jump(replace_lbl);
f.bind(not_replace);
let is_follow = f.eq_imm(got, i32::from(TAG_SUPP_FOLLOW));
let not_follow = f.label();
f.branch_if_falsy(is_follow, not_follow);
f.jump(pack);
f.bind(not_follow);
f.jump(reject_lbl);
f.bind(reject_lbl);
f.set(verdict, i32::from(TAG_SUPP_REJECT));
f.jump(pack);
f.bind(replace_lbl);
f.set(verdict, i32::from(TAG_SUPP_REPLACE));
f.mov(out, body);
f.jump(pack);
f.bind(pack);
let packed = f.window(2);
f.mov(packed.at(0), verdict);
f.mov(packed.at(1), out);
let rec = f.record_pack(&[packed.at(0), packed.at(1)]);
f.return_(rec);
})
}
fn emit_door(program: &mut Program, name: &str, registry_name: &str, judge: FuncId) -> FuncId {
program.function(name, 1, |f| {
let owner = f.reg(0);
let registered = f.load_str(registry_name);
f.register_name(registered);
let empty = f.load_i32(0);
let len = f.load_i32(0);
let mut slots = [empty; SUPPLEMENT_SLOTS];
for slot in &mut slots {
*slot = f.load_i32(0);
}
let chain = ChainCode {
len,
slots,
empty,
current: f.local(),
reply_body: f.local(),
follow: f.label(),
reject: f.label(),
};
let loop_lbl = f.label();
f.bind(loop_lbl);
let msg = f.receive();
let got = f.hop_tag(msg);
let payload = f.hop_payload(msg);
let is_attach = f.eq_imm(got, i32::from(TAG_SUPP_ATTACH));
let not_attach = f.label();
f.branch_if_falsy(is_attach, not_attach);
emit_attach(f, payload, &chain);
f.bind(not_attach);
let is_detach = f.eq_imm(got, i32::from(TAG_SUPP_DETACH));
let not_detach = f.label();
f.branch_if_falsy(is_detach, not_detach);
emit_detach(f, payload, &chain);
f.bind(not_detach);
let is_enter = f.eq_imm(got, i32::from(TAG_SUPP_ENTER));
let not_enter = f.label();
f.branch_if_falsy(is_enter, not_enter);
emit_enter(f, owner, payload, judge, &chain);
f.bind(not_enter);
f.mov(chain.reply_body, chain.empty);
f.jump(chain.reject);
f.bind(chain.follow);
f.send_reply(msg, i32::from(TAG_SUPP_FOLLOW), chain.reply_body);
f.jump(loop_lbl);
f.bind(chain.reject);
f.send_reply(msg, i32::from(TAG_SUPP_REJECT), chain.reply_body);
f.jump(loop_lbl);
})
}
fn emit_attach(f: &mut crate::Fn<'_>, payload: Reg, chain: &ChainCode) {
let idx = f.record_get(payload, 0);
let cap = f.record_get(payload, 1);
let negative = f.lt_imm(idx, 0);
let nonneg = f.label();
f.branch_if_falsy(negative, nonneg);
f.mov(chain.reply_body, chain.empty);
f.jump(chain.reject);
f.bind(nonneg);
let fits = f.le(idx, chain.len);
let bad = f.label();
f.branch_if_falsy(fits, bad);
let room = f.lt_imm(chain.len, SUPPLEMENT_SLOTS as i32);
f.branch_if_falsy(room, bad);
for i in (1..SUPPLEMENT_SLOTS).rev() {
let at = f.load_i32(i as i32);
let idx_before = f.lt(idx, at);
let skip = f.label();
f.branch_if_falsy(idx_before, skip);
let within = f.le(at, chain.len);
f.branch_if_falsy(within, skip);
f.mov(chain.slots[i], chain.slots[i - 1]);
f.bind(skip);
}
for (i, slot) in chain.slots.iter().enumerate() {
let is_i = f.eq_imm(idx, i as i32);
let skip = f.label();
f.branch_if_falsy(is_i, skip);
f.mov(*slot, cap);
f.bind(skip);
}
f.add_imm(chain.len, 1);
f.mov(chain.reply_body, chain.len);
f.jump(chain.follow);
f.bind(bad);
f.mov(chain.reply_body, chain.empty);
f.jump(chain.reject);
}
fn emit_detach(f: &mut crate::Fn<'_>, idx: Reg, chain: &ChainCode) {
let negative = f.lt_imm(idx, 0);
let nonneg = f.label();
f.branch_if_falsy(negative, nonneg);
f.mov(chain.reply_body, chain.empty);
f.jump(chain.reject);
f.bind(nonneg);
let in_range = f.lt(idx, chain.len);
let bad = f.label();
f.branch_if_falsy(in_range, bad);
for i in 0..SUPPLEMENT_SLOTS - 1 {
let at = f.load_i32(i as i32);
let idx_le = f.le(idx, at);
let skip = f.label();
f.branch_if_falsy(idx_le, skip);
let next = f.load_i32((i + 1) as i32);
let next_in = f.lt(next, chain.len);
f.branch_if_falsy(next_in, skip);
f.mov(chain.slots[i], chain.slots[i + 1]);
f.bind(skip);
}
let last = f.local();
f.mov(last, chain.len);
f.sub_imm(last, 1);
for (i, slot) in chain.slots.iter().enumerate() {
let is_last = f.eq_imm(last, i as i32);
let skip = f.label();
f.branch_if_falsy(is_last, skip);
f.mov(*slot, chain.empty);
f.bind(skip);
}
f.sub_imm(chain.len, 1);
f.mov(chain.reply_body, chain.len);
f.jump(chain.follow);
f.bind(bad);
f.mov(chain.reply_body, chain.empty);
f.jump(chain.reject);
}
fn emit_enter(f: &mut crate::Fn<'_>, owner: Reg, payload: Reg, judge: FuncId, chain: &ChainCode) {
f.mov(chain.current, payload);
for (i, slot) in chain.slots.iter().enumerate() {
let at = f.load_i32(i as i32);
let live = f.lt(at, chain.len);
let skip = f.label();
f.branch_if_falsy(live, skip);
let ret = f.call(judge, &[*slot, chain.current]);
let verdict = f.record_get(ret, 0);
let next = f.record_get(ret, 1);
let rejected = f.eq_imm(verdict, i32::from(TAG_SUPP_REJECT));
let keep = f.label();
f.branch_if_falsy(rejected, keep);
f.mov(chain.reply_body, chain.current);
f.jump(chain.reject);
f.bind(keep);
let replaced = f.eq_imm(verdict, i32::from(TAG_SUPP_REPLACE));
let same = f.label();
f.branch_if_falsy(replaced, same);
f.mov(chain.current, next);
f.bind(same);
f.bind(skip);
}
let hop = f.hop_fresh(i32::from(TAG_SUPP_DELIVER), chain.current);
let reply = f.ask(owner, hop);
let got = f.hop_tag(reply);
let body = f.hop_payload(reply);
let replaced = f.eq_imm(got, i32::from(TAG_SUPP_REPLACE));
let not_replace = f.label();
f.branch_if_falsy(replaced, not_replace);
f.mov(chain.current, body);
f.mov(chain.reply_body, chain.current);
f.jump(chain.follow);
f.bind(not_replace);
let followed = f.eq_imm(got, i32::from(TAG_SUPP_FOLLOW));
let not_follow = f.label();
f.branch_if_falsy(followed, not_follow);
f.mov(chain.reply_body, chain.current);
f.jump(chain.follow);
f.bind(not_follow);
f.mov(chain.reply_body, chain.current);
f.jump(chain.reject);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Opcode, Program};
fn function_traps(chunk: &crate::Chunk, id: u32) -> bool {
let Some(func) = chunk.function(id) else {
return true;
};
let start = func.entry as usize;
let end = chunk
.functions
.iter()
.map(|function| function.entry)
.filter(|entry| *entry > func.entry)
.min()
.unwrap_or(chunk.code.len() as u32) as usize;
chunk.code[start..end]
.iter()
.any(|instruction| instruction.op == Opcode::Trap)
}
#[test]
fn empty_name_is_rejected() {
let mut program = Program::new("chain");
assert_eq!(
install_supplement_door(&mut program, ""),
Err(SupplementError::EmptyName)
);
}
#[test]
fn second_door_for_the_same_name_is_rejected() -> Result<(), SupplementError> {
let mut program = Program::new("chain");
let _door = install_supplement_door(&mut program, "front")?;
assert_eq!(
install_supplement_door(&mut program, "front"),
Err(SupplementError::AlreadyInstalled)
);
Ok(())
}
#[test]
fn door_frame_verifies_without_a_trap() -> Result<(), SupplementError> {
let mut program = Program::new("chain");
let door = install_supplement_door(&mut program, "front")?;
let judge = program
.function_index("supplement-judge:front")
.unwrap_or(u32::MAX);
let chunk = program.build();
if let Err(err) = crate::verify(&chunk) {
panic!("{err}");
}
assert!(
!function_traps(&chunk, door),
"door frame emitted Trap (register file overflow)"
);
assert!(
!function_traps(&chunk, judge),
"judge frame emitted Trap (register file overflow)"
);
Ok(())
}
}