Skip to main content

native_host/
native_host.rs

1//! Executable contract witness. This is a synthetic guest, not a script engine.
2
3use blitz_script::native_host::{
4    NativeCallbackError, NativeGuest, NativeHost, NativeIntrinsic, RealmScope, RetainedCallback,
5};
6use std::rc::Rc;
7
8type Callback = RetainedCallback<Rc<u8>, Rc<()>>;
9
10struct Guest {
11    scope: RealmScope<Rc<u8>>,
12    root: Option<Rc<()>>,
13    intrinsic: Option<NativeIntrinsic<Self>>,
14    calls: usize,
15}
16
17impl NativeGuest for Guest {
18    type Value = i64;
19    type RealmId = Rc<u8>;
20    type CallbackId = Rc<()>;
21    type Error = &'static str;
22
23    fn scope(&self) -> RealmScope<Self::RealmId> {
24        self.scope.clone()
25    }
26
27    fn retain_callback(&mut self, value: &i64) -> Result<Callback, Self::Error> {
28        if *value != 7 || self.root.is_some() {
29            return Err("not an available callback");
30        }
31        let root = Rc::new(());
32        self.root = Some(Rc::clone(&root));
33        Ok(RetainedCallback::new(
34            Rc::clone(self.scope.realm()),
35            self.scope.generation(),
36            root,
37        ))
38    }
39
40    fn release_callback(&mut self, callback: &Callback) -> Result<(), Self::Error> {
41        if !self.current(callback) {
42            return Err("callback unavailable");
43        }
44        self.root = None;
45        Ok(())
46    }
47
48    fn register_intrinsic(
49        &mut self,
50        name: &'static str,
51        arity: u8,
52        callback: NativeIntrinsic<Self>,
53    ) -> Result<(), Self::Error> {
54        if name != "increment" || arity != 1 {
55            return Err("invalid intrinsic");
56        }
57        self.intrinsic = Some(callback);
58        Ok(())
59    }
60
61    fn invoke_retained_callback(
62        &mut self,
63        callback: &Callback,
64        arguments: &[i64],
65    ) -> Result<i64, Self::Error> {
66        if !self.current(callback) {
67            return Err("callback unavailable");
68        }
69        self.calls += 1;
70        self.intrinsic.ok_or("intrinsic unavailable")?(self, arguments)
71    }
72}
73
74impl Guest {
75    fn current(&self, callback: &Callback) -> bool {
76        callback.is_current_in(&self.scope)
77            && self
78                .root
79                .as_ref()
80                .is_some_and(|root| Rc::ptr_eq(root, callback.callback()))
81    }
82}
83
84impl NativeHost for Guest {
85    type Guest = Self;
86
87    fn guest(&self) -> &Self {
88        self
89    }
90
91    fn guest_mut(&mut self) -> &mut Self {
92        self
93    }
94}
95
96fn main() {
97    let mut guest = Guest {
98        scope: RealmScope::new(Rc::new(1), 1),
99        root: None,
100        intrinsic: None,
101        calls: 0,
102    };
103    guest
104        .register_intrinsic("increment", 1, |_, arguments| {
105            arguments
106                .first()
107                .copied()
108                .map(|value| value + 1)
109                .ok_or("missing argument")
110        })
111        .expect("register compiled intrinsic");
112    let callback = guest.retain_callback(&7).expect("retain callback");
113    assert_eq!(
114        NativeHost::invoke_retained_callback(&mut guest, &callback, &[5]),
115        Ok(6)
116    );
117    let foreign = RetainedCallback::new(Rc::new(2), 1, Rc::clone(callback.callback()));
118    assert_eq!(
119        NativeHost::invoke_retained_callback(&mut guest, &foreign, &[5]),
120        Err(NativeCallbackError::StaleCallback)
121    );
122    assert_eq!(
123        guest.calls, 1,
124        "foreign scope must not enter guest dispatch"
125    );
126    guest.release_callback(&callback).expect("release callback");
127    assert!(NativeHost::invoke_retained_callback(&mut guest, &callback.clone(), &[5]).is_err());
128    assert_eq!(guest.calls, 1, "release must revoke cloned tokens");
129    let next = guest.retain_callback(&7).expect("retain next callback");
130    guest.scope = RealmScope::new(Rc::clone(guest.scope.realm()), 2);
131    assert_eq!(
132        NativeHost::invoke_retained_callback(&mut guest, &next, &[5]),
133        Err(NativeCallbackError::StaleCallback)
134    );
135    assert_eq!(
136        guest.calls, 1,
137        "stale generation must not enter guest dispatch"
138    );
139    println!("typed native dispatch, root release, realm and generation checks passed");
140}