Skip to main content

day_bridge/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! daybridge runtime (docs/bridge.md, DESIGN.md §15.6): foreign-language implementations of a
5//! Rust API.
6//!
7//! A crate declares one API and supplies implementations per platform; `day build` generates the
8//! adapters and the glue. This crate is the small runtime half: the [`bridge!`] macro, the
9//! [`Error`] that crosses every boundary, the [`Support`] an arm reports, and the callback tier
10//! ([`Done`], [`Registry`] and [`Completion`]) that lets an arm answer after it has returned.
11//!
12//! ```ignore
13//! day_bridge::bridge! {
14//!     #[day_bridge::declare]
15//!     extern "day" {
16//!         fn speak_native(text: &str, done: day_bridge::Done<bool>) -> Result<(), day_bridge::Error>;
17//!     }
18//!
19//!     #[day_bridge::impl(rust, platforms = [other])]
20//!     fn speak_native(_text: &str, done: day_bridge::Done<bool>) -> Result<(), day_bridge::Error> {
21//!         done.complete(Err(day_bridge::Error::Unsupported));
22//!         Ok(())
23//!     }
24//! }
25//! ```
26//!
27//! The generator is [`day_build::bridge`](../day_build/bridge/index.html), called from the crate's
28//! `build.rs`. Nothing here parses anything: see [`bridge!`] for why.
29
30use std::fmt;
31use std::future::Future;
32use std::pin::Pin;
33use std::task::{Context, Poll};
34
35/// What a target's arm promises, re-exported from day-spec so a bridged crate's `available()`
36/// answers in the same vocabulary as `day::capability()`.
37pub use day_process::Support;
38
39/// The single error type crossing a bridge boundary (docs/bridge.md "Errors").
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum Error {
42    /// No arm claims this target: what the `other` fallback returns.
43    Unsupported,
44    /// The arm failed: a Swift `throws`, a Kotlin exception, a thrown JS error, a nonzero C status.
45    /// The string is the platform's own message, which is the only detail that survives.
46    Foreign(String),
47    /// An argument or result was not valid UTF-8.
48    Encoding,
49    /// The platform runtime was unavailable (no JVM, no `Context`, COM init refused), or a
50    /// completion never came because the call never went out.
51    Runtime,
52}
53
54impl fmt::Display for Error {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            Error::Unsupported => write!(f, "unsupported on this platform"),
58            Error::Foreign(msg) => write!(f, "{msg}"),
59            Error::Encoding => write!(f, "invalid UTF-8 across the bridge"),
60            Error::Runtime => write!(f, "platform runtime unavailable"),
61        }
62    }
63}
64
65impl std::error::Error for Error {}
66
67// ---------------------------------------------------------------------------
68// The callback tier (docs/bridge.md "Callbacks")
69// ---------------------------------------------------------------------------
70
71/// The closures waiting on one declared function's completions, keyed by token. The generator
72/// emits one `static` per `Done` declaration; a foreign arm receives the token and the generated
73/// completion export resolves it here.
74pub struct Registry<T: 'static> {
75    inner: day_async::TokenRegistry<Result<T, Error>>,
76}
77
78impl<T: Send + 'static> Default for Registry<T> {
79    fn default() -> Self {
80        Self::new()
81    }
82}
83
84impl<T: Send + 'static> Registry<T> {
85    /// An empty registry. `const`, so a generated `static` can own it.
86    #[must_use]
87    pub const fn new() -> Self {
88        Self {
89            inner: day_async::TokenRegistry::new(),
90        }
91    }
92
93    /// Resolve `token` with `value`. `false` when nothing waits under it: already completed,
94    /// cancelled, or never issued, every one of which is a no-op by contract.
95    pub fn complete(&self, token: u64, value: Result<T, Error>) -> bool {
96        self.inner.complete(token, value)
97    }
98
99    /// Whether a closure still waits under `token`.
100    pub fn is_pending(&self, token: u64) -> bool {
101        self.inner.contains(token)
102    }
103
104    /// Forget `token` without resolving it: the future that waited was dropped.
105    fn cancel(&self, token: u64) -> bool {
106        self.inner.remove(token)
107    }
108}
109
110/// One outstanding completion, handed to an arm. A Rust arm calls [`Done::complete`]; a foreign
111/// arm receives [`Done::token`] and completes through the generated symbol.
112///
113/// A `Done` fires **at most once**: completing consumes it, and a completion arriving after the
114/// token was cancelled or already answered finds nothing and does nothing.
115pub struct Done<T: Send + 'static> {
116    token: u64,
117    registry: &'static Registry<T>,
118}
119
120impl<T: Send + 'static> Done<T> {
121    /// Register `cb` and produce the handle the arm receives.
122    pub fn new(
123        registry: &'static Registry<T>,
124        cb: impl FnOnce(Result<T, Error>) + Send + 'static,
125    ) -> Self {
126        Self {
127            token: registry.inner.insert(cb),
128            registry,
129        }
130    }
131
132    /// The number a foreign arm carries and hands back to the completion symbol.
133    #[must_use]
134    pub fn token(&self) -> u64 {
135        self.token
136    }
137
138    /// Hand the token to a foreign arm: the closure stays registered until the generated
139    /// completion symbol resolves it, or the waiting future is dropped.
140    #[must_use]
141    pub fn into_token(self) -> u64 {
142        self.token
143    }
144
145    /// Resolve the waiting closure. A Rust arm's way of answering.
146    pub fn complete(self, value: Result<T, Error>) {
147        self.registry.complete(self.token, value);
148    }
149}
150
151/// The awaitable form of a `Done` declaration: what a generated `<fn>_future` returns.
152///
153/// Resolves with the arm's answer, or with [`Error::Runtime`] when the arm returned without
154/// ever completing (the call never went out). Dropping it cancels the wait (a late completion
155/// then finds nothing) and runs the cancel hook the generated code attached, when the
156/// declaration named a cancel arm.
157pub struct Completion<T: Send + 'static> {
158    rx: day_async::Oneshot<Result<T, Error>>,
159    token: u64,
160    registry: &'static Registry<T>,
161    on_drop: Option<Box<dyn FnOnce() + Send>>,
162}
163
164impl<T: Send + 'static> Completion<T> {
165    /// Run `f` when this future is dropped before completing: the generated cancel arm.
166    #[must_use]
167    pub fn on_cancel(mut self, f: impl FnOnce() + Send + 'static) -> Self {
168        self.on_drop = Some(Box::new(f));
169        self
170    }
171
172    /// Whether the answer has arrived.
173    #[must_use]
174    pub fn is_ready(&self) -> bool {
175        self.rx.is_ready()
176    }
177
178    /// The token the arm was handed: what a declared cancel arm takes.
179    #[must_use]
180    pub fn token(&self) -> u64 {
181        self.token
182    }
183}
184
185impl<T: Send + 'static> Future for Completion<T> {
186    type Output = Result<T, Error>;
187
188    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
189        match Pin::new(&mut self.rx).poll(cx) {
190            Poll::Ready(Ok(v)) => Poll::Ready(v),
191            Poll::Ready(Err(day_async::Dropped)) => Poll::Ready(Err(Error::Runtime)),
192            Poll::Pending => Poll::Pending,
193        }
194    }
195}
196
197impl<T: Send + 'static> Drop for Completion<T> {
198    fn drop(&mut self) {
199        if self.registry.cancel(self.token)
200            && let Some(f) = self.on_drop.take()
201        {
202            f();
203        }
204    }
205}
206
207/// Start a `Done` call in callback form: what a generated `<fn>_async` does.
208///
209/// `call` receives the handle and runs the arm. The callback fires exactly once: with the arm's
210/// answer when it completes, or with the arm's error when it fails to start (the same error
211/// this returns), so a caller may rely on either channel alone. `Ok` carries the token, which
212/// is what a declared cancel arm takes to find the request it started.
213///
214/// # Errors
215///
216/// Returns the error `call` returned when the arm fails to start; `cb` receives the same error.
217pub fn start_async<T: Send + 'static>(
218    registry: &'static Registry<T>,
219    cb: impl FnOnce(Result<T, Error>) + Send + 'static,
220    call: impl FnOnce(Done<T>) -> Result<(), Error>,
221) -> Result<u64, Error> {
222    let done = Done::new(registry, cb);
223    let token = done.token();
224    match call(done) {
225        Ok(()) => Ok(token),
226        Err(e) => {
227            registry.complete(token, Err(e.clone()));
228            Err(e)
229        }
230    }
231}
232
233/// Start a `Done` call in future form: what a generated `<fn>_future` does.
234pub fn start_future<T: Send + 'static>(
235    registry: &'static Registry<T>,
236    call: impl FnOnce(Done<T>) -> Result<(), Error>,
237) -> Completion<T> {
238    let (tx, rx) = day_async::oneshot();
239    let done = Done::new(registry, move |v| tx.send(v));
240    let token = done.token();
241    if let Err(e) = call(done) {
242        // Registered before the call, so the slot is still there unless the arm completed it
243        // on its way out, in which case this finds nothing, and the arm's answer stands.
244        registry.complete(token, Err(e));
245    }
246    Completion {
247        rx,
248        token,
249        registry,
250        on_drop: None,
251    }
252}
253
254// ---------------------------------------------------------------------------
255// The stream tier (docs/bridge.md "Streams")
256// ---------------------------------------------------------------------------
257
258/// One delivery on an `Emit<T>` stream: a value, the end, or a failure. The last two are
259/// terminal: nothing is delivered after either.
260#[derive(Clone, Debug, PartialEq, Eq)]
261pub enum Item<T> {
262    Value(T),
263    End,
264    Failed(Error),
265}
266
267type StreamCallback<T> = Box<dyn FnMut(Item<T>) + Send>;
268
269struct SlotState<T> {
270    queue: std::collections::VecDeque<Item<T>>,
271    /// A thread is draining `queue` into the callback; others only enqueue.
272    delivering: bool,
273    /// A terminal item was enqueued, or the consumer stopped: later pushes are refused.
274    accepting: bool,
275    /// The consumer stopped: queued items are dropped undelivered.
276    stopped: bool,
277}
278
279struct StreamSlot<T> {
280    state: std::sync::Mutex<SlotState<T>>,
281    callback: std::sync::Mutex<Option<StreamCallback<T>>>,
282}
283
284fn lock_ignoring_poison<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
285    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
286}
287
288/// The consumers of one `Emit<T>` declaration's streams, keyed by token: the stream
289/// counterpart of [`Registry`]. The generator emits one `static` per declaration.
290///
291/// Delivery rules that make a token safe to hand to a platform thread:
292///
293/// - **In order, one at a time.** Items pushed from several threads (a response callback and
294///   a writer thread, say) reach the consumer serially, in push order. The first pusher drains
295///   the queue; the others only enqueue.
296/// - **Re-entrancy is allowed.** The consumer may stop its own stream, or cause another push to
297///   it, from inside the callback: neither waits on the callback's lock.
298/// - **Terminal once.** After `End` or `Failed` is pushed, further pushes return `false`;
299///   after [`Streams::stop`], queued items are dropped.
300pub struct Streams<T: 'static> {
301    slots: std::sync::Mutex<std::collections::BTreeMap<u64, std::sync::Arc<StreamSlot<T>>>>,
302}
303
304impl<T: Send + 'static> Default for Streams<T> {
305    fn default() -> Self {
306        Self::new()
307    }
308}
309
310impl<T: Send + 'static> Streams<T> {
311    /// An empty set of streams. `const`, so a generated `static` can own it.
312    #[must_use]
313    pub const fn new() -> Self {
314        Self {
315            slots: std::sync::Mutex::new(std::collections::BTreeMap::new()),
316        }
317    }
318
319    fn insert(&self, cb: impl FnMut(Item<T>) + Send + 'static) -> u64 {
320        let token = day_async::next_token();
321        let slot = std::sync::Arc::new(StreamSlot {
322            state: std::sync::Mutex::new(SlotState {
323                queue: std::collections::VecDeque::new(),
324                delivering: false,
325                accepting: true,
326                stopped: false,
327            }),
328            callback: std::sync::Mutex::new(Some(Box::new(cb))),
329        });
330        lock_ignoring_poison(&self.slots).insert(token, slot);
331        token
332    }
333
334    /// Deliver what a generated export received: status 0 is a value (or a failure, when the
335    /// value did not convert), 2 the end, anything else a failure.
336    pub fn deliver(&self, token: u64, status: i32, outcome: Result<T, Error>) -> bool {
337        let item = match (status, outcome) {
338            (0, Ok(v)) => Item::Value(v),
339            (2, _) => Item::End,
340            (_, Err(e)) => Item::Failed(e),
341            (_, Ok(_)) => Item::Failed(Error::Runtime),
342        };
343        self.push(token, item)
344    }
345
346    /// Push a value. `false` when the stream has ended, failed, or been stopped.
347    pub fn emit(&self, token: u64, value: T) -> bool {
348        self.push(token, Item::Value(value))
349    }
350
351    /// End the stream.
352    pub fn end(&self, token: u64) -> bool {
353        self.push(token, Item::End)
354    }
355
356    /// Fail the stream.
357    pub fn fail(&self, token: u64, error: Error) -> bool {
358        self.push(token, Item::Failed(error))
359    }
360
361    /// Whether a consumer still listens under `token`.
362    pub fn is_open(&self, token: u64) -> bool {
363        lock_ignoring_poison(&self.slots).contains_key(&token)
364    }
365
366    /// The consumer stops listening: queued items are dropped, later pushes refused, and the
367    /// callback released as soon as no delivery is running.
368    pub fn stop(&self, token: u64) -> bool {
369        let Some(slot) = lock_ignoring_poison(&self.slots).remove(&token) else {
370            return false;
371        };
372        {
373            let mut st = lock_ignoring_poison(&slot.state);
374            st.stopped = true;
375            st.accepting = false;
376            st.queue.clear();
377        }
378        // From inside the callback this lock is held by the same thread: `try_lock` then fails
379        // and the draining loop releases the callback when it returns.
380        if let Ok(mut cb) = slot.callback.try_lock() {
381            *cb = None;
382        }
383        true
384    }
385
386    fn push(&self, token: u64, item: Item<T>) -> bool {
387        let terminal = !matches!(item, Item::Value(_));
388        let slot = {
389            let mut map = lock_ignoring_poison(&self.slots);
390            if terminal {
391                map.remove(&token)
392            } else {
393                map.get(&token).cloned()
394            }
395        };
396        let Some(slot) = slot else {
397            return false;
398        };
399        {
400            let mut st = lock_ignoring_poison(&slot.state);
401            if !st.accepting {
402                return false;
403            }
404            st.queue.push_back(item);
405            if terminal {
406                st.accepting = false;
407            }
408            if st.delivering {
409                return true;
410            }
411            st.delivering = true;
412        }
413        loop {
414            let next = {
415                let mut st = lock_ignoring_poison(&slot.state);
416                if st.stopped {
417                    st.queue.clear();
418                }
419                if let Some(item) = st.queue.pop_front() {
420                    item
421                } else {
422                    st.delivering = false;
423                    break;
424                }
425            };
426            let ends = !matches!(next, Item::Value(_));
427            let mut cb = lock_ignoring_poison(&slot.callback);
428            if let Some(f) = cb.as_mut() {
429                f(next);
430            }
431            if ends || lock_ignoring_poison(&slot.state).stopped {
432                *cb = None;
433            }
434        }
435        true
436    }
437}
438
439/// One open stream, handed to an arm. A Rust arm calls [`Emit::emit`] and then [`Emit::end`] or
440/// [`Emit::fail`]; a foreign arm receives [`Emit::token`] and delivers through the generated
441/// `<fn>_emit` / `<fn>_end` / `<fn>_fail` helpers.
442pub struct Emit<T: Send + 'static> {
443    token: u64,
444    streams: &'static Streams<T>,
445}
446
447impl<T: Send + 'static> Clone for Emit<T> {
448    fn clone(&self) -> Self {
449        Self {
450            token: self.token,
451            streams: self.streams,
452        }
453    }
454}
455
456impl<T: Send + 'static> Emit<T> {
457    /// Register `cb` and produce the handle the arm receives.
458    pub fn new(streams: &'static Streams<T>, cb: impl FnMut(Item<T>) + Send + 'static) -> Self {
459        Self {
460            token: streams.insert(cb),
461            streams,
462        }
463    }
464
465    /// The number a foreign arm carries and hands back to the generated helpers.
466    #[must_use]
467    pub fn token(&self) -> u64 {
468        self.token
469    }
470
471    /// Hand the token to a foreign arm; the consumer stays registered until the stream ends,
472    /// fails, or is stopped.
473    #[must_use]
474    pub fn into_token(self) -> u64 {
475        self.token
476    }
477
478    /// Deliver a value. `false` once the stream is over.
479    pub fn emit(&self, value: T) -> bool {
480        self.streams.emit(self.token, value)
481    }
482
483    /// End the stream.
484    pub fn end(&self) -> bool {
485        self.streams.end(self.token)
486    }
487
488    /// Fail the stream.
489    #[must_use]
490    pub fn fail(&self, error: Error) -> bool {
491        self.streams.fail(self.token, error)
492    }
493
494    /// Whether the consumer still listens.
495    #[must_use]
496    pub fn is_open(&self) -> bool {
497        self.streams.is_open(self.token)
498    }
499}
500
501/// Start an `Emit` call: what a generated `<fn>_stream` does. `cb` receives every item, in
502/// order, from whichever thread the platform delivers on. When the arm fails to start, `cb`
503/// receives that failure (once) and this returns it. `Ok` carries the token a stop call takes.
504///
505/// # Errors
506///
507/// Returns the error `call` returned when the arm fails to start; `cb` receives the same error.
508pub fn start_stream<T: Send + 'static>(
509    streams: &'static Streams<T>,
510    cb: impl FnMut(Item<T>) + Send + 'static,
511    call: impl FnOnce(Emit<T>) -> Result<(), Error>,
512) -> Result<u64, Error> {
513    let emit = Emit::new(streams, cb);
514    let token = emit.token();
515    match call(emit) {
516        Ok(()) => Ok(token),
517        Err(e) => {
518            streams.fail(token, e.clone());
519            Err(e)
520        }
521    }
522}
523
524/// Run a generated completion export's body with panics contained: the export is called from
525/// C, the JVM, or the browser, and a panic unwinding into any of them is fatal.
526pub fn guard(f: impl FnOnce()) {
527    day_process::ffi_guard::contain((), f);
528}
529
530/// Take ownership of a buffer the web shim allocated with `day_dom_alloc(len)` and filled: the
531/// (ptr, len) a JavaScript completion passes a string or bytes through (docs/web.md).
532///
533/// # Safety
534///
535/// `ptr` must come from a `Vec::<u8>::with_capacity(len)` the shim filled with `len` bytes and
536/// handed over; this is the one reconstitution, and the caller must never touch it again.
537#[doc(hidden)]
538#[expect(
539    clippy::same_length_and_capacity,
540    reason = "the safety contract is a buffer allocated with capacity `len` and filled with `len` bytes"
541)]
542pub unsafe fn __take_wasm(ptr: *mut u8, len: usize) -> Vec<u8> {
543    if ptr.is_null() || len == 0 {
544        return Vec::new();
545    }
546    // SAFETY: the caller's contract above.
547    unsafe { Vec::from_raw_parts(ptr, len, len) }
548}
549
550/// The HarmonyOS side of the callback tier: how generated Rust reaches an ArkTS arm, and how a
551/// completion comes back (docs/bridge.md "Callbacks"). Every ArkTS arm runs on the JS thread; the
552/// ArkUI shim owns that dispatch, and this module finds the shim's entry at run time so a bridged
553/// crate keeps no link-time dependency on the toolkit ([`arkts::lookup`], which
554/// day-part-permissions shares).
555#[cfg(all(target_os = "linux", target_env = "ohos"))]
556pub mod arkts {
557    use std::ffi::{c_char, c_int, c_void};
558
559    /// One argument crossing to ArkTS: `kind` selects the field (0 bool, 1 i32, 2 i64,
560    /// 3 f64, 4 str, 5 bytes), matching `DayArkArg` in the ArkUI shim.
561    #[repr(C)]
562    pub struct Arg {
563        pub kind: i32,
564        pub i: i64,
565        pub f: f64,
566        pub ptr: *const u8,
567        pub len: usize,
568    }
569
570    impl Arg {
571        fn plain(kind: i32, i: i64, f: f64) -> Self {
572            Self {
573                kind,
574                i,
575                f,
576                ptr: std::ptr::null(),
577                len: 0,
578            }
579        }
580        #[must_use]
581        pub fn bool(v: bool) -> Self {
582            Self::plain(0, i64::from(v), 0.0)
583        }
584        #[must_use]
585        pub fn i32(v: i32) -> Self {
586            Self::plain(1, i64::from(v), 0.0)
587        }
588        #[must_use]
589        pub fn i64(v: i64) -> Self {
590            Self::plain(2, v, 0.0)
591        }
592        #[must_use]
593        pub fn f64(v: f64) -> Self {
594            Self::plain(3, 0, v)
595        }
596        #[must_use]
597        pub fn str(v: &str) -> Self {
598            Self {
599                kind: 4,
600                i: 0,
601                f: 0.0,
602                ptr: v.as_ptr(),
603                len: v.len(),
604            }
605        }
606        #[must_use]
607        pub fn bytes(v: &[u8]) -> Self {
608            Self {
609                kind: 5,
610                i: 0,
611                f: 0.0,
612                ptr: v.as_ptr(),
613                len: v.len(),
614            }
615        }
616    }
617
618    type InvokeFn = unsafe extern "C" fn(*const c_char, *const Arg, usize, u64, *mut Arg) -> c_int;
619    type OnJsThreadFn = unsafe extern "C" fn() -> c_int;
620
621    unsafe extern "C" {
622        fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
623        fn dladdr(addr: *const c_void, info: *mut DlInfo) -> c_int;
624        fn dlopen(filename: *const c_char, flags: c_int) -> *mut c_void;
625    }
626
627    /// `Dl_info` (dlfcn.h).
628    #[repr(C)]
629    #[expect(
630        clippy::struct_field_names,
631        reason = "the fields keep the names C's `Dl_info` gives them"
632    )]
633    struct DlInfo {
634        dli_fname: *const c_char,
635        dli_fbase: *mut c_void,
636        dli_sname: *const c_char,
637        dli_saddr: *mut c_void,
638    }
639
640    const RTLD_NOW: c_int = 2;
641    /// Only a library already loaded; never load a second copy.
642    const RTLD_NOLOAD: c_int = 4;
643
644    /// A symbol of the app's own native library, where day-toolkit-arkui's exports live (this crate is
645    /// linked into the same `libentry.so`).
646    ///
647    /// The process-wide lookup comes first, but it cannot be the only one: HarmonyOS's ArkTS
648    /// module loader opens `libentry.so` with LOCAL symbol visibility, so `dlsym(NULL, …)` does
649    /// not see its symbols, and every bridged call failed as "platform runtime unavailable"
650    /// without ever reaching ArkTS. The library holding this very function is the one to ask.
651    #[must_use]
652    pub fn lookup(name: &std::ffi::CStr) -> *mut c_void {
653        // SAFETY: a plain symbol lookup in the running process.
654        let global = unsafe { dlsym(std::ptr::null_mut(), name.as_ptr()) };
655        if !global.is_null() {
656            return global;
657        }
658        let own = own_library();
659        if own.is_null() {
660            return std::ptr::null_mut();
661        }
662        // SAFETY: `own` is a live handle to a loaded library.
663        unsafe { dlsym(own, name.as_ptr()) }
664    }
665
666    /// A handle to the library this code is linked into, or null.
667    fn own_library() -> *mut c_void {
668        static HANDLE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
669        *HANDLE.get_or_init(|| {
670            let mut info = DlInfo {
671                dli_fname: std::ptr::null(),
672                dli_fbase: std::ptr::null_mut(),
673                dli_sname: std::ptr::null(),
674                dli_saddr: std::ptr::null_mut(),
675            };
676            // SAFETY: `lookup` is a function in this library; dladdr only reads its address and
677            // fills `info`, whose `dli_fname` then names this library's file.
678            let found = unsafe { dladdr(lookup as *const c_void, &raw mut info) } != 0;
679            if !found || info.dli_fname.is_null() {
680                return 0;
681            }
682            // SAFETY: a valid C string from dladdr; NOLOAD only returns an already-loaded library.
683            unsafe { dlopen(info.dli_fname, RTLD_NOW | RTLD_NOLOAD) as usize }
684        }) as *mut c_void
685    }
686
687    /// Call the ArkTS function registered under `symbol` with `args`, on the JS thread. `done`
688    /// is the completion token (0 for a synchronous function): the shim passes it as the
689    /// trailing argument, and completes it itself when the arm returns a promise. A call from
690    /// the JS thread runs inline; from any other thread it is posted and the caller parks until
691    /// the loop has run it, so `Ok` still means the arm accepted the call.
692    ///
693    /// # Errors
694    ///
695    /// Returns the errors of [`invoke_value`].
696    pub fn invoke(symbol: &str, args: &[Arg], done: u64) -> Result<(), super::Error> {
697        invoke_value(symbol, args, done).map(|_| ())
698    }
699
700    /// [`invoke`], keeping the arm's return value: a scalar the shim marshals into an [`Arg`]
701    /// (`i` for booleans and integers, `f` for numbers, both set for a JS number). What a
702    /// declaration returning `Result<T, Error>` reads its `T` from.
703    ///
704    /// # Errors
705    ///
706    /// Returns `Error::Runtime` when the ArkUI bridge is not loaded or cannot run the arm,
707    /// `Error::Encoding` when `symbol` contains a NUL byte, and `Error::Foreign` when the arm fails.
708    pub fn invoke_value(symbol: &str, args: &[Arg], done: u64) -> Result<Arg, super::Error> {
709        let entry = lookup(c"day_arkui_bridge_invoke");
710        if entry.is_null() {
711            return Err(super::Error::Runtime);
712        }
713        let Ok(name) = std::ffi::CString::new(symbol) else {
714            return Err(super::Error::Encoding);
715        };
716        let mut ret = Arg::plain(-1, 0, 0.0);
717        // SAFETY: the symbol is day-toolkit-arkui's export with exactly this signature.
718        let invoke: InvokeFn = unsafe { std::mem::transmute(entry) };
719        match unsafe { invoke(name.as_ptr(), args.as_ptr(), args.len(), done, &raw mut ret) } {
720            0 => Ok(ret),
721            2 => Err(super::Error::Runtime),
722            _ => Err(super::Error::Foreign(format!("{symbol} failed"))),
723        }
724    }
725
726    /// Whether the caller is on the JS thread: the UI thread of a Day app on HarmonyOS, where
727    /// a blocking wait for an ArkTS answer would deadlock. `false` when no host is running.
728    #[must_use]
729    pub fn on_js_thread() -> bool {
730        let entry = lookup(c"day_arkui_bridge_on_js_thread");
731        if entry.is_null() {
732            return false;
733        }
734        // SAFETY: the symbol is day-toolkit-arkui's export with exactly this signature.
735        let f: OnJsThreadFn = unsafe { std::mem::transmute(entry) };
736        unsafe { f() != 0 }
737    }
738
739    /// Copy a buffer the shim passes to a completion export; it is valid only during the call.
740    ///
741    /// # Safety
742    ///
743    /// `ptr` must point at `len` readable bytes, or be null.
744    #[doc(hidden)]
745    #[must_use]
746    pub unsafe fn __bytes(ptr: *const u8, len: usize) -> Vec<u8> {
747        if ptr.is_null() || len == 0 {
748            return Vec::new();
749        }
750        // SAFETY: the caller's contract above.
751        unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec()
752    }
753}
754
755/// Declare a crate's bridge: the API and its per-platform implementations.
756///
757/// **The body is discarded.** This macro expands to the code day-build generated from the same
758/// source text, which is what lets an arm contain Swift, Kotlin, ArkTS, JavaScript, C, or C++; the
759/// tokens are never resolved by rustc, only lexed. DESIGN.md §5.1's "no required macro anywhere in
760/// the framework" still holds: this is opt-in sugar that lowers to plain generated Rust.
761///
762/// The generated file is read by a small procedural macro (`day_macros::bridge_generated`) rather
763/// than `include!`d, so its code is attributed to this call in the crate's source. A panic location
764/// in it then names a path that is the same wherever the project is built; an `include!`d file's
765/// location is its absolute `OUT_DIR` path, which made `day rebuild` fail on bridged parts.
766///
767/// Foreign code inside an arm must nevertheless *lex* as Rust tokens, which idiomatic JavaScript and
768/// ArkTS do not: a backtick is not a Rust token, and `'zh-CN'` lexes as a malformed lifetime. That
769/// is why inline arms carry their body in a raw string.
770#[macro_export]
771macro_rules! bridge {
772    ($($body:tt)*) => {
773        $crate::__bridge_generated!();
774    };
775}
776
777#[doc(hidden)]
778pub use day_macros::bridge_generated as __bridge_generated;
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783    use std::sync::{Arc, Mutex};
784    use std::task::{Wake, Waker};
785
786    fn block_on<F: Future>(mut fut: F) -> F::Output {
787        struct Unpark(std::thread::Thread);
788        impl Wake for Unpark {
789            fn wake(self: Arc<Self>) {
790                self.0.unpark();
791            }
792        }
793        let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
794        let mut cx = Context::from_waker(&waker);
795        // SAFETY: `fut` lives on this stack frame and is never moved after being pinned.
796        let mut fut = unsafe { Pin::new_unchecked(&mut fut) };
797        loop {
798            if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
799                return v;
800            }
801            std::thread::park();
802        }
803    }
804
805    static REG: Registry<bool> = Registry::new();
806
807    #[test]
808    fn a_rust_arm_completes_and_the_future_resolves() {
809        let fut = start_future(&REG, |done| {
810            std::thread::spawn(move || done.complete(Ok(true)));
811            Ok(())
812        });
813        assert_eq!(block_on(fut), Ok(true));
814    }
815
816    #[test]
817    fn a_foreign_style_token_round_trip() {
818        let fut = start_future(&REG, |done| {
819            let token = done.into_token();
820            assert!(REG.is_pending(token));
821            std::thread::spawn(move || {
822                assert!(REG.complete(token, Ok(false)));
823                assert!(!REG.complete(token, Ok(true)), "at most once");
824            });
825            Ok(())
826        });
827        assert_eq!(block_on(fut), Ok(false));
828    }
829
830    #[test]
831    fn an_arm_that_fails_to_start_fails_the_future_with_its_own_error() {
832        let fut = start_future(&REG, |_done| Err(Error::Foreign("no engine".into())));
833        assert_eq!(block_on(fut), Err(Error::Foreign("no engine".into())));
834    }
835
836    #[test]
837    fn an_arm_that_returns_ok_without_completing_leaves_the_future_pending() {
838        let fut = start_future(&REG, |done| {
839            let _ = done.into_token();
840            Ok(())
841        });
842        assert!(!fut.is_ready());
843    }
844
845    #[test]
846    fn dropping_the_future_cancels_the_slot_and_runs_the_hook() {
847        let hook = Arc::new(Mutex::new(false));
848        let h = hook.clone();
849        let mut token = 0;
850        let fut = start_future(&REG, |done| {
851            token = done.into_token();
852            Ok(())
853        })
854        .on_cancel(move || *h.lock().unwrap() = true);
855        assert!(REG.is_pending(token));
856        drop(fut);
857        assert!(!REG.is_pending(token));
858        assert!(*hook.lock().unwrap());
859        assert!(
860            !REG.complete(token, Ok(true)),
861            "a late completion is a no-op"
862        );
863    }
864
865    #[test]
866    fn the_callback_form_fires_exactly_once_on_start_failure() {
867        let hits = Arc::new(Mutex::new(0));
868        let h = hits.clone();
869        let r = start_async(
870            &REG,
871            move |v| {
872                assert_eq!(v, Err(Error::Runtime));
873                *h.lock().unwrap() += 1;
874            },
875            |_done| Err(Error::Runtime),
876        );
877        assert_eq!(r, Err(Error::Runtime));
878        assert_eq!(*hits.lock().unwrap(), 1);
879        let token = start_async(&REG, |_| {}, |_done| Ok(())).expect("started");
880        assert!(REG.is_pending(token), "the token names the live slot");
881    }
882
883    static STREAMS: Streams<u32> = Streams::new();
884
885    type Seen = Arc<Mutex<Vec<Item<u32>>>>;
886
887    fn collector() -> (Seen, impl FnMut(Item<u32>) + Send + 'static) {
888        let seen: Seen = Arc::new(Mutex::new(Vec::new()));
889        let s = seen.clone();
890        (seen, move |item| s.lock().unwrap().push(item))
891    }
892
893    #[test]
894    fn a_stream_delivers_in_order_then_ends_once() {
895        let (seen, cb) = collector();
896        let token = start_stream(&STREAMS, cb, |emit| {
897            let token = emit.into_token();
898            std::thread::spawn(move || {
899                for v in 0..100 {
900                    assert!(STREAMS.emit(token, v));
901                }
902                assert!(STREAMS.end(token));
903                assert!(!STREAMS.emit(token, 999), "nothing after the end");
904                assert!(!STREAMS.end(token), "the end is delivered once");
905            })
906            .join()
907            .unwrap();
908            Ok(())
909        })
910        .expect("started");
911        let seen = seen.lock().unwrap();
912        assert_eq!(seen.len(), 101);
913        assert!(
914            seen[..100]
915                .iter()
916                .enumerate()
917                .all(|(i, v)| *v == Item::Value(i as u32))
918        );
919        assert_eq!(seen[100], Item::End);
920        assert!(!STREAMS.is_open(token));
921    }
922
923    #[test]
924    fn pushes_from_many_threads_reach_the_consumer_serially() {
925        let busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
926        let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
927        let (b, c) = (busy.clone(), count.clone());
928        let emit = Emit::new(&STREAMS, move |_item| {
929            assert!(
930                !b.swap(true, std::sync::atomic::Ordering::SeqCst),
931                "two deliveries overlapped"
932            );
933            std::thread::yield_now();
934            c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
935            b.store(false, std::sync::atomic::Ordering::SeqCst);
936        });
937        let workers: Vec<_> = (0..8)
938            .map(|_| {
939                let e = emit.clone();
940                std::thread::spawn(move || {
941                    for v in 0..200 {
942                        e.emit(v);
943                    }
944                })
945            })
946            .collect();
947        for w in workers {
948            w.join().unwrap();
949        }
950        emit.end();
951        assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 8 * 200 + 1);
952    }
953
954    #[test]
955    fn the_consumer_may_stop_its_own_stream_from_inside_the_callback() {
956        let token_cell = Arc::new(Mutex::new(0u64));
957        let seen = Arc::new(Mutex::new(Vec::new()));
958        let (t, s) = (token_cell.clone(), seen.clone());
959        let emit = Emit::new(&STREAMS, move |item| {
960            s.lock().unwrap().push(item.clone());
961            if item == Item::Value(2) {
962                assert!(STREAMS.stop(*t.lock().unwrap()));
963            }
964        });
965        *token_cell.lock().unwrap() = emit.token();
966        for v in 0..5 {
967            emit.emit(v);
968        }
969        assert!(!emit.end(), "stopped streams refuse the end");
970        assert_eq!(
971            *seen.lock().unwrap(),
972            vec![Item::Value(0), Item::Value(1), Item::Value(2)]
973        );
974        assert!(!emit.is_open());
975    }
976
977    #[test]
978    fn a_stream_that_fails_to_start_delivers_that_failure_once() {
979        let (seen, cb) = collector();
980        let r = start_stream(&STREAMS, cb, |_emit| Err(Error::Foreign("no radio".into())));
981        assert_eq!(r, Err(Error::Foreign("no radio".into())));
982        assert_eq!(
983            *seen.lock().unwrap(),
984            vec![Item::Failed(Error::Foreign("no radio".into()))]
985        );
986    }
987
988    #[test]
989    fn deliver_maps_export_statuses() {
990        let (seen, cb) = collector();
991        let emit = Emit::new(&STREAMS, cb);
992        let token = emit.token();
993        assert!(STREAMS.deliver(token, 0, Ok(7)));
994        assert!(STREAMS.deliver(token, 0, Err(Error::Encoding)));
995        assert!(
996            !STREAMS.deliver(token, 2, Err(Error::Runtime)),
997            "already failed"
998        );
999        assert_eq!(
1000            *seen.lock().unwrap(),
1001            vec![Item::Value(7), Item::Failed(Error::Encoding)]
1002        );
1003    }
1004}