Skip to main content

byteflow/bytecode/
value.rs

1use std::fmt;
2use std::sync::Arc;
3
4use super::cap::CapId;
5
6/// Reserved Atomic Hop tag for monitor `DOWN` events (not an application tag).
7pub const TAG_SYS_DOWN: u16 = 0xFF01;
8/// Reserved Atomic Hop tag for linked-exit notices (`Ask` target death or
9/// `trap_exit` link signal).
10pub const TAG_SYS_EXIT: u16 = 0xFF02;
11
12/// Envelope carried in mailboxes and registers (**Atomic Hop**).
13///
14/// `payload` is a [`Value`] behind [`Arc`] so hops can carry `Int`, `Str`,
15/// `Bytes`, or nested messages. Mailbox byte budgets charge
16/// [`Value::memory_size`] of the whole hop, including the payload tree.
17///
18/// # Security
19///
20/// - **`sender`**: FlowId stamped by the scheduler on bytecode `Send` / `Ask`
21///   and host [`crate::Runtime::send`] (`0` = [`crate::FlowId::HOST`])
22///   (invariant **S1**). Not a capability.
23/// - **`reply_cap`**: stable SEND-only [`CapId`] per `(recipient, sender)`
24///   pair (holder = recipient, reused across hops). Correlation is
25///   [`Self::request_id`]. [`CapId::NONE`] means “no reply grant”.
26///
27/// See `docs/security.md`.
28#[derive(Clone, Debug, PartialEq)]
29pub struct Message {
30    /// Authenticated origin FlowId (`0` = trusted host / non-flow).
31    pub sender: u64,
32    /// Capability granting **SEND** back to [`Self::sender`], or [`CapId::NONE`].
33    pub reply_cap: CapId,
34    /// Client correlation token; echoed on replies (`Ask` / **S2**).
35    pub request_id: u64,
36    /// Protocol discriminator (opaque to the VM).
37    pub tag: u16,
38    /// Application body (shared so hop clones are cheap).
39    pub payload: Arc<Value>,
40}
41
42impl Message {
43    /// Build an envelope. `sender` / `reply_cap` are placeholders until a
44    /// bytecode hop is authenticated by the scheduler.
45    pub fn new(sender: u64, request_id: u64, tag: u16, payload: impl Into<Value>) -> Self {
46        Self {
47            sender,
48            reply_cap: CapId::NONE,
49            request_id,
50            tag,
51            payload: Arc::new(payload.into()),
52        }
53    }
54
55    /// Outgoing hop from host Rust (`sender` / `reply_cap` filled on delivery).
56    pub fn request(request_id: u64, tag: u16, payload: impl Into<Value>) -> Self {
57        Self::new(0, request_id, tag, payload)
58    }
59
60    /// Reply envelope echoing `request_id` from a received hop (host path).
61    pub fn reply_to(req: &Self, tag: u16, payload: impl Into<Value>) -> Self {
62        Self::new(0, req.request_id, tag, payload)
63    }
64
65    /// Runtime lifecycle hop: monitor `DOWN` (`tag == `[`TAG_SYS_DOWN`]).
66    pub fn down(monitor: u64, target_flow: u64, reason: u64) -> Self {
67        Self::new(
68            target_flow,
69            monitor,
70            TAG_SYS_DOWN,
71            Value::Int(reason as i64),
72        )
73    }
74
75    /// Runtime lifecycle hop: Ask target exited, or a linked peer exited
76    /// while this flow has `trap_exit` enabled (`tag == `[`TAG_SYS_EXIT`]).
77    pub fn linked_exit(target_flow: u64, reason: u64) -> Self {
78        Self::new(target_flow, 0, TAG_SYS_EXIT, Value::Int(reason as i64))
79    }
80
81    #[inline]
82    pub fn is_down(&self) -> bool {
83        self.tag == TAG_SYS_DOWN
84    }
85
86    #[inline]
87    pub fn is_exit(&self) -> bool {
88        self.tag == TAG_SYS_EXIT
89    }
90
91    /// Stamp origin FlowId and attach a reply capability (scheduler only).
92    #[inline]
93    pub(crate) fn authenticate(mut self, sender: u64, reply_cap: CapId) -> Self {
94        self.sender = sender;
95        self.reply_cap = reply_cap;
96        self
97    }
98
99    pub(crate) fn with_payload(mut self, payload: Value) -> Self {
100        self.payload = Arc::new(payload);
101        self
102    }
103}
104
105/// Most elements a [`Value::List`] may hold. Wider sequences are rejected
106/// by the decoder, `ListPack`, and [`Value::try_list`].
107pub const MAX_LIST_LEN: usize = 32;
108
109/// Shared stand-in so [`Drop`] can detach a payload without allocating.
110fn discarded_payload() -> Arc<Value> {
111    static EMPTY: std::sync::OnceLock<Arc<Value>> = std::sync::OnceLock::new();
112    Arc::clone(EMPTY.get_or_init(|| Arc::new(Value::Unit)))
113}
114
115impl Drop for Message {
116    fn drop(&mut self) {
117        // Leaf payloads fall through to the field drop. A nested `Message`
118        // is a chain: the default drop recurses one frame per hop and
119        // overflowed the stack on a long chain (the same failure `push`
120        // used to hit while sizing).
121        if !matches!(self.payload.as_ref(), Value::Message(_)) {
122            return;
123        }
124        let payload = std::mem::replace(&mut self.payload, discarded_payload());
125        let mut current = match Arc::into_inner(payload) {
126            Some(value) => value,
127            None => return,
128        };
129        while let Value::Message(mut message) = current {
130            let inner = std::mem::replace(&mut message.payload, discarded_payload());
131            current = match Arc::into_inner(inner) {
132                Some(value) => value,
133                None => return,
134            };
135        }
136    }
137}
138
139impl fmt::Display for Message {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        write!(
142            f,
143            "msg{{from=flow#{}, reply={}, id={}, tag={}, payload={}}}",
144            self.sender, self.reply_cap, self.request_id, self.tag, self.payload
145        )
146    }
147}
148
149/// A dynamically-tagged runtime value.
150///
151/// [`Value::Cap`] is an opaque [`CapId`] for `Send` / `Ask`. Authority lives
152/// in the runtime [`crate::CapTable`], keyed by holder — not in this tag.
153/// [`Value::Pid`] remains for **identity** inside authenticated messages.
154///
155/// [`Value::Str`] / [`Value::Bytes`] are heap payloads shared via [`Arc`].
156#[derive(Clone, Debug, PartialEq)]
157pub enum Value {
158    Unit,
159    Bool(bool),
160    Int(i64),
161    Float(f64),
162    /// Internal / message identity (FlowId as `u64`). **Not** a Send target.
163    Pid(u64),
164    /// Atomic Hop envelope. See [`Message`].
165    Message(Message),
166    /// Opaque capability token. Required for `Send` / `Ask`.
167    Cap(CapId),
168    /// UTF-8 text (constant pool, natives, host).
169    Str(Arc<str>),
170    /// Opaque byte buffer (constant pool, natives, host).
171    Bytes(Arc<[u8]>),
172    /// Bounded sequence (ABI v6 wire tag `9`). At most [`MAX_LIST_LEN`]
173    /// elements; nesting shares [`super::MAX_VALUE_DEPTH`] with `Message`.
174    List(Arc<[Value]>),
175}
176
177impl Value {
178    /// BFV0 wire tag for this value (`Unit=0` … `Bytes=8`, `List=9`).
179    ///
180    /// Used by [`crate::Opcode::ReceiveMatchKind`] selective receive.
181    #[inline]
182    pub fn wire_tag(&self) -> u8 {
183        match self {
184            Value::Unit => 0,
185            Value::Bool(_) => 1,
186            Value::Int(_) => 2,
187            Value::Float(_) => 3,
188            Value::Pid(_) => 4,
189            Value::Message(_) => 5,
190            Value::Cap(_) => 6,
191            Value::Str(_) => 7,
192            Value::Bytes(_) => 8,
193            Value::List(_) => 9,
194        }
195    }
196
197    /// Build a [`Value::List`]. Fails when `items` is longer than
198    /// [`MAX_LIST_LEN`] or the nested `Message` / `List` depth exceeds the
199    /// decoder ceiling.
200    pub fn try_list(items: Vec<Value>) -> Option<Self> {
201        if items.len() > MAX_LIST_LEN {
202            return None;
203        }
204        let value = Value::List(Arc::from(items));
205        if value.within_nesting_limit() {
206            Some(value)
207        } else {
208            None
209        }
210    }
211
212    /// Build a [`Value::Str`] from anything string-like.
213    #[inline]
214    pub fn str(s: impl AsRef<str>) -> Self {
215        Value::Str(Arc::from(s.as_ref()))
216    }
217
218    /// Build a [`Value::Bytes`] from a byte slice.
219    #[inline]
220    pub fn bytes(b: impl AsRef<[u8]>) -> Self {
221        Value::Bytes(Arc::from(b.as_ref()))
222    }
223
224    /// Same ceiling as the `.bf` decoder ([`super::MAX_VALUE_DEPTH`]).
225    ///
226    /// A deeper `Message` chain would recurse through cap reissue on a
227    /// worker stack. The walk stops at the limit instead of descending.
228    pub(crate) fn within_nesting_limit(&self) -> bool {
229        fn walk(value: &Value, depth: u32) -> bool {
230            if depth > super::MAX_VALUE_DEPTH {
231                return false;
232            }
233            match value {
234                Value::Message(message) => walk(message.payload.as_ref(), depth + 1),
235                Value::List(items) => items.iter().all(|item| walk(item, depth + 1)),
236                _ => true,
237            }
238        }
239        walk(self, 0)
240    }
241
242    /// Truthiness used by `Opcode::Branch`: falsy are `Unit`, `Bool(false)`,
243    /// `Int(0)`, empty [`Value::Str`], empty [`Value::Bytes`], and empty
244    /// [`Value::List`].
245    #[inline]
246    pub fn is_truthy(&self) -> bool {
247        match self {
248            Value::Unit | Value::Bool(false) | Value::Int(0) => false,
249            Value::Str(s) if s.is_empty() => false,
250            Value::Bytes(b) if b.is_empty() => false,
251            Value::List(items) if items.is_empty() => false,
252            _ => true,
253        }
254    }
255
256    /// `Int`, or `Bool` as `0` / `1`.
257    ///
258    /// This coercion is for host natives ([`crate::vm::expect_int`]). Opcode
259    /// operands that require an integer (`Sleep`, tags, `request_id`) do not
260    /// use it — a `Bool` there is a type error.
261    #[inline]
262    pub fn as_int(&self) -> Option<i64> {
263        match self {
264            Value::Int(i) => Some(*i),
265            Value::Bool(b) => Some(*b as i64),
266            _ => None,
267        }
268    }
269
270    #[inline]
271    pub fn as_pid(&self) -> Option<u64> {
272        match self {
273            Value::Pid(p) => Some(*p),
274            _ => None,
275        }
276    }
277
278    #[inline]
279    pub fn as_cap(&self) -> Option<CapId> {
280        match self {
281            Value::Cap(c) => Some(*c),
282            _ => None,
283        }
284    }
285
286    #[inline]
287    pub fn as_message(&self) -> Option<&Message> {
288        match self {
289            Value::Message(m) => Some(m),
290            _ => None,
291        }
292    }
293
294    #[inline]
295    pub fn as_str(&self) -> Option<&str> {
296        match self {
297            Value::Str(s) => Some(s.as_ref()),
298            _ => None,
299        }
300    }
301
302    #[inline]
303    pub fn as_bytes(&self) -> Option<&[u8]> {
304        match self {
305            Value::Bytes(b) => Some(b.as_ref()),
306            Value::Str(s) => Some(s.as_bytes()),
307            _ => None,
308        }
309    }
310
311    /// Bytes this value is **charged** for against a mailbox byte budget
312    /// (see [`crate::MailboxBytes`]).
313    ///
314    /// [`Value::Str`] / [`Value::Bytes`] / hop payloads are `Arc`-shared: the
315    /// same buffer cloned into N mailboxes exists once in memory, but each
316    /// mailbox is charged the full length. That over-counts on purpose.
317    ///
318    /// A `Message` chain deeper than [`super::MAX_VALUE_DEPTH`] does not
319    /// walk the tail. The returned size is [`usize::MAX`], which no mailbox
320    /// budget can admit.
321    #[inline]
322    pub fn memory_size(&self) -> usize {
323        match self.heap_size_limited() {
324            Some(heap) => std::mem::size_of::<Self>().saturating_add(heap),
325            None => usize::MAX,
326        }
327    }
328
329    /// Heap bytes owned (transitively) by this value, excluding the enum
330    /// itself.
331    ///
332    /// One `Arc` inside this value is counted once. A chain past the decoder
333    /// ceiling yields [`usize::MAX`] instead of recursing.
334    #[inline]
335    pub fn heap_size(&self) -> usize {
336        self.heap_size_limited().unwrap_or(usize::MAX)
337    }
338
339    /// `None` when the `Message` chain is deeper than the decoder ceiling or
340    /// the byte sum does not fit in `usize`.
341    ///
342    /// Iterative on purpose: `Mailbox::push` asks for this size, and a
343    /// recursive walk of a long chain overflowed the caller's stack.
344    fn heap_size_limited(&self) -> Option<usize> {
345        fn walk(value: &Value, depth: u32) -> Option<usize> {
346            let mut extra = 0usize;
347            let mut cursor = value;
348            let mut depth = depth;
349            loop {
350                match cursor {
351                    Value::Message(message) => {
352                        if depth >= super::MAX_VALUE_DEPTH {
353                            return None;
354                        }
355                        extra = extra.checked_add(std::mem::size_of::<Value>())?;
356                        cursor = message.payload.as_ref();
357                        depth += 1;
358                    }
359                    Value::List(items) => {
360                        if depth >= super::MAX_VALUE_DEPTH {
361                            return None;
362                        }
363                        let slots = items.len().checked_mul(std::mem::size_of::<Value>())?;
364                        extra = extra.checked_add(slots)?;
365                        for item in items.iter() {
366                            extra = extra.checked_add(walk(item, depth + 1)?)?;
367                        }
368                        return Some(extra);
369                    }
370                    Value::Str(s) => return extra.checked_add(s.len()),
371                    Value::Bytes(b) => return extra.checked_add(b.len()),
372                    Value::Unit
373                    | Value::Bool(_)
374                    | Value::Int(_)
375                    | Value::Float(_)
376                    | Value::Pid(_)
377                    | Value::Cap(_) => return Some(extra),
378                }
379            }
380        }
381        walk(self, 0)
382    }
383
384    pub fn type_name(&self) -> &'static str {
385        match self {
386            Value::Unit => "unit",
387            Value::Bool(_) => "bool",
388            Value::Int(_) => "int",
389            Value::Float(_) => "float",
390            Value::Pid(_) => "pid",
391            Value::Message(_) => "message",
392            Value::Cap(_) => "cap",
393            Value::Str(_) => "str",
394            Value::Bytes(_) => "bytes",
395            Value::List(_) => "list",
396        }
397    }
398}
399
400impl fmt::Display for Value {
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        match self {
403            Value::Unit => write!(f, "()"),
404            Value::Bool(b) => write!(f, "{b}"),
405            Value::Int(i) => write!(f, "{i}"),
406            Value::Float(x) => write!(f, "{x}"),
407            Value::Pid(p) => write!(f, "flow#{p}"),
408            Value::Message(m) => write!(f, "{m}"),
409            Value::Cap(c) => write!(f, "{c}"),
410            Value::Str(s) => write!(f, "{s}"),
411            Value::Bytes(b) => write!(f, "bytes[{}]", b.len()),
412            Value::List(items) => {
413                write!(f, "[")?;
414                for (index, item) in items.iter().enumerate() {
415                    if index > 0 {
416                        write!(f, ", ")?;
417                    }
418                    write!(f, "{item}")?;
419                }
420                write!(f, "]")
421            }
422        }
423    }
424}
425
426impl From<i64> for Value {
427    fn from(v: i64) -> Self {
428        Value::Int(v)
429    }
430}
431impl From<i32> for Value {
432    fn from(v: i32) -> Self {
433        Value::Int(i64::from(v))
434    }
435}
436impl From<u64> for Value {
437    /// Fits the `Int` domain. Values above `i64::MAX` saturate instead of
438    /// becoming negative.
439    fn from(v: u64) -> Self {
440        let n = match i64::try_from(v) {
441            Ok(n) => n,
442            Err(_) => i64::MAX,
443        };
444        Value::Int(n)
445    }
446}
447impl From<bool> for Value {
448    fn from(v: bool) -> Self {
449        Value::Bool(v)
450    }
451}
452impl From<f64> for Value {
453    fn from(v: f64) -> Self {
454        Value::Float(v)
455    }
456}
457impl From<Message> for Value {
458    fn from(m: Message) -> Self {
459        Value::Message(m)
460    }
461}
462impl From<CapId> for Value {
463    fn from(c: CapId) -> Self {
464        Value::Cap(c)
465    }
466}
467impl From<&str> for Value {
468    fn from(s: &str) -> Self {
469        Value::str(s)
470    }
471}
472impl From<String> for Value {
473    fn from(s: String) -> Self {
474        Value::Str(Arc::from(s))
475    }
476}
477impl From<&[u8]> for Value {
478    fn from(b: &[u8]) -> Self {
479        Value::bytes(b)
480    }
481}
482impl From<Vec<u8>> for Value {
483    fn from(b: Vec<u8>) -> Self {
484        Value::Bytes(Arc::from(b))
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    #[test]
493    fn nesting_stops_at_the_decoder_ceiling() {
494        let mut value = Value::Int(1);
495        for _ in 0..16 {
496            value = Value::Message(Message::new(0, 1, 1, value));
497        }
498        assert!(value.within_nesting_limit());
499        value = Value::Message(Message::new(0, 1, 1, value));
500        assert!(!value.within_nesting_limit());
501    }
502
503    #[test]
504    fn message_is_truthy_and_round_trips_helpers() {
505        let m = Message::new(7, 99, 10, 1u64);
506        let v = Value::Message(m.clone());
507        assert!(v.is_truthy());
508        assert_eq!(v.as_message(), Some(&m));
509        assert_eq!(v.type_name(), "message");
510        assert_eq!(m.payload.as_ref(), &Value::Int(1));
511    }
512
513    #[test]
514    fn authenticate_stamps_sender_and_reply_cap() {
515        let reply = CapId::from_raw(7);
516        let m = Message::new(999, 1, 2, 3u64).authenticate(42, reply);
517        assert_eq!(m.sender, 42);
518        assert_eq!(m.reply_cap, reply);
519        assert_eq!(m.request_id, 1);
520    }
521
522    #[test]
523    fn str_payload_is_charged_on_the_hop() {
524        let hop = Value::Message(Message::new(1, 1, 1, Value::str("hello")));
525        assert!(hop.heap_size() >= 5);
526    }
527
528    #[test]
529    fn nested_message_heap_counts_each_envelope_until_the_ceiling() {
530        let word = std::mem::size_of::<Value>();
531        let mut value = Value::str("hello");
532        for _ in 0..16 {
533            value = Value::Message(Message::new(0, 1, 1, value));
534        }
535        assert!(value.within_nesting_limit());
536        assert_eq!(value.heap_size(), 16 * word + 5);
537        assert_eq!(value.memory_size(), word + 16 * word + 5);
538        let blob = Value::Message(Message::new(0, 1, 1, Value::bytes(vec![0u8; 50_000])));
539        assert_eq!(blob.heap_size(), word + 50_000);
540        value = Value::Message(Message::new(0, 1, 1, value));
541        assert!(!value.within_nesting_limit());
542        assert_eq!(value.heap_size(), usize::MAX);
543        assert_eq!(value.memory_size(), usize::MAX);
544    }
545
546    #[test]
547    fn a_long_message_chain_sizes_without_recursing_off_the_stack() {
548        let mut value = Value::Int(1);
549        for _ in 0..10_000 {
550            value = Value::Message(Message::new(0, 1, 1, value));
551        }
552        assert!(!value.within_nesting_limit());
553        assert_eq!(value.heap_size(), usize::MAX);
554        assert_eq!(value.memory_size(), usize::MAX);
555    }
556
557    #[test]
558    fn cap_is_truthy() {
559        let cap = CapId::from_raw(3);
560        assert!(Value::Cap(cap).is_truthy());
561        assert_eq!(Value::Cap(cap).as_cap(), Some(cap));
562    }
563
564    #[test]
565    fn str_and_bytes_helpers() {
566        let s = Value::str("hi");
567        assert_eq!(s.as_str(), Some("hi"));
568        assert_eq!(s.type_name(), "str");
569        assert!(s.is_truthy());
570        assert!(!Value::str("").is_truthy());
571
572        let b = Value::bytes([1u8, 2, 3]);
573        assert_eq!(b.as_bytes(), Some(&[1, 2, 3][..]));
574        assert_eq!(b.type_name(), "bytes");
575        assert!(b.is_truthy());
576        assert!(!Value::bytes([]).is_truthy());
577
578        assert_eq!(s.as_bytes(), Some(b"hi".as_slice()));
579    }
580
581    #[test]
582    fn u64_above_i64_max_saturates() {
583        assert_eq!(Value::from(u64::MAX), Value::Int(i64::MAX));
584        assert_eq!(Value::from(4u64), Value::Int(4));
585    }
586
587    #[test]
588    fn str_eq_compares_content() {
589        assert_eq!(Value::str("a"), Value::from("a".to_owned()));
590        assert_ne!(Value::str("a"), Value::str("b"));
591        assert_eq!(Value::bytes([9]), Value::from(vec![9u8]));
592    }
593}