//! Runtime-kind blocks: strings, byte strings and closures, and the //! constructor cells runtime functions return (lists, `Result`s). use std::ffi::c_char; use crate::abi::{ Block, Ctx, Header, TAG_BYTES, TAG_CLOSURE, TAG_STRING, UNIT, Value, int, is_ptr, }; use crate::heap::tl_alloc; const WORD: usize = size_of::(); /// Strings have no scanned fields, so the raw area follows the header. fn string_raw(s: Value) -> *mut u8 { Block::fields_ptr(s as *mut Block).cast::() } /// A fresh string of `len` bytes, its length and NUL written, and where its /// bytes go: the caller writes them (UTF-8) before the string is used. For /// building a string in place, with one allocation and one copy (issue /// #129). pub fn string_uninit(ctx: *mut Ctx, len: usize) -> (Value, *mut u8) { let s = tl_alloc(ctx, TAG_STRING, 0, WORD + len + 1) as Value; let raw = string_raw(s); // SAFETY: the raw area holds an i64 length, `len` bytes, and a NUL. unsafe { raw.cast::().write(len as i64); raw.add(WORD + len).write(0); (s, raw.add(WORD)) } } /// A fresh `Bytes` of `len` bytes, its length written, and where its bytes /// go (see [`string_uninit`]). pub fn bytes_uninit(ctx: *mut Ctx, len: usize) -> (Value, *mut u8) { let b = tl_alloc(ctx, TAG_BYTES, 0, WORD + len); let raw = Block::fields_ptr(b).cast::(); // SAFETY: the raw area holds an i64 length and `len` bytes. unsafe { raw.cast::().write(len as i64); (b as Value, raw.add(WORD)) } } /// Shrink the unique string `s`, allocated for `alloced` bytes, to `len` /// bytes (`len <= alloced`): the block is resized and its length and NUL /// rewritten. Returns the (possibly moved) string. For writing a string's /// bytes before its exact length is known (the block's size is derived /// from the length word when it is freed, so it must not stay over-long). /// /// # Safety /// `s` must be a unique string whose block was allocated for `alloced` /// bytes (as by [`string_uninit`]), with its first `len` bytes written. pub unsafe fn string_shrink(s: Value, alloced: usize, len: usize) -> Value { debug_assert!(len <= alloced); if len == alloced { return s; } let header = size_of::(); // SAFETY: forwarded caller guarantee: `s` is unique and its block was // allocated with HEADER + WORD + alloced + 1 bytes. let b = unsafe { crate::heap::realloc_block( s as *mut Block, header + WORD + alloced + 1, header + WORD + len + 1, ) }; // SAFETY: the raw area holds the length, `len` bytes and a NUL. unsafe { let raw = string_raw(b as Value); raw.cast::().write(len as i64); raw.add(WORD + len).write(0); } b as Value } /// The total length of `parts`, `sep` between each two: what building /// their concatenation in one block needs. pub fn joined_len<'a>(parts: impl Iterator, sep: usize) -> usize { let (count, len) = parts.fold((0usize, 0usize), |(n, len), p| { ( n + 1, len.checked_add(p.len()).expect("louise: string too large"), ) }); sep.checked_mul(count.saturating_sub(1)) .and_then(|s| len.checked_add(s)) .expect("louise: string too large") } /// Write `parts` to `out`, `sep` between each two; `out` must have room for /// [`joined_len`] bytes. /// /// # Safety /// `out` must be valid for writes of the joined length. pub unsafe fn write_joined<'a>(out: *mut u8, parts: impl Iterator, sep: &[u8]) { let mut at = 0; for (i, p) in parts.enumerate() { // SAFETY: the caller sized `out` with `joined_len` over the same // parts and separator. unsafe { if i > 0 { std::ptr::copy_nonoverlapping(sep.as_ptr(), out.add(at), sep.len()); at += sep.len(); } std::ptr::copy_nonoverlapping(p.as_ptr(), out.add(at), p.len()); } at += p.len(); } } /// Copy `len` bytes (expected UTF-8) into a fresh, NUL-terminated string. /// /// # Safety /// `bytes` must be valid for reads of `len` bytes. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_string_from(ctx: *mut Ctx, bytes: *const c_char, len: usize) -> Value { let b = tl_alloc(ctx, TAG_STRING, 0, WORD + len + 1); let s = b as Value; // SAFETY: the raw area holds an i64 length, `len` bytes, and a NUL. unsafe { let raw = string_raw(s); raw.cast::().write(len as i64); std::ptr::copy_nonoverlapping(bytes.cast::(), raw.add(WORD), len); raw.add(WORD + len).write(0); } s } /// # Safety /// `s` must be a live string (borrowed). #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_string_len(s: Value) -> usize { // SAFETY: caller guarantees `s` is a live string. unsafe { string_raw(s).cast::().read() as usize } } /// # Safety /// `s` must be a live string (borrowed); the pointer is valid while it lives. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_string_ptr(s: Value) -> *const c_char { // SAFETY: caller guarantees `s` is a live string. unsafe { string_raw(s).add(WORD).cast() } } /// # Safety /// `s` must be a live string (borrowed). pub unsafe fn string_bytes<'a>(s: Value) -> &'a [u8] { // SAFETY: caller guarantees `s` is a live string. unsafe { std::slice::from_raw_parts(tl_string_ptr(s).cast(), tl_string_len(s)) } } /// The text of a string (borrowed). /// /// # Safety /// `s` must be a live string (borrowed). pub(crate) unsafe fn text<'a>(s: Value) -> &'a str { // SAFETY: strings hold UTF-8 (they are made from Rust strings, source // literals or checked bytes). unsafe { std::str::from_utf8_unchecked(string_bytes(s)) } } /// A fresh string holding `s`. pub(crate) fn string(ctx: *mut Ctx, s: &str) -> Value { // SAFETY: `s` is valid for its length. unsafe { tl_string_from(ctx, s.as_ptr().cast(), s.len()) } } /// An immortal string (rc 0) holding `s`, leaked: never freed and never /// counted by the leak oracle — it lives outside the counted heap, /// reachable from a static, like the clock capabilities (`clock.rs`). /// For the handful of strings a hot path repeats forever (common HTTP /// header names, `http.rs`). pub(crate) fn immortal_string(s: &'static str) -> Value { let words = (WORD + WORD + s.len() + 1).div_ceil(WORD); let mut block = vec![0 as Value; words].into_boxed_slice(); let b = block.as_mut_ptr().cast::(); // SAFETY: `block` is `Value`-aligned with room for the header and // the raw area (an i64 length, the bytes, a NUL). unsafe { b.cast::
().write(Header { rc: 0, tag: TAG_STRING, scan_fsize: 0, flags: 0, }); let raw = string_raw(b as Value); raw.cast::().write(s.len() as i64); std::ptr::copy_nonoverlapping(s.as_ptr(), raw.add(WORD), s.len()); } Box::leak(block); b as Value } /// Copy `bytes` into fresh `Bytes`. Unlike a string, the raw area has no /// NUL: an i64 length, then the bytes. pub fn bytes_from(ctx: *mut Ctx, bytes: &[u8]) -> Value { let b = tl_alloc(ctx, TAG_BYTES, 0, WORD + bytes.len()); // SAFETY: the raw area holds an i64 length and `bytes.len()` bytes. unsafe { let raw = Block::fields_ptr(b).cast::(); raw.cast::().write(bytes.len() as i64); std::ptr::copy_nonoverlapping(bytes.as_ptr(), raw.add(WORD), bytes.len()); } b as Value } /// The contents of a `String` or `Bytes` (both start their raw area with /// an i64 length). /// /// # Safety /// `b` must be a live string or byte string (borrowed). pub unsafe fn bytes_of<'a>(b: Value) -> &'a [u8] { // SAFETY: forwarded caller guarantee; the layouts agree up to the NUL. unsafe { string_bytes(b) } } /// A constructor cell with tag `tag` and `fields` (owned). pub(crate) fn cell(ctx: *mut Ctx, tag: u16, fields: &[Value]) -> Value { let b = tl_alloc(ctx, tag, fields.len() as u8, 0); // SAFETY: a fresh block with `fields.len()` scanned fields. unsafe { let f = Block::fields_ptr(b); for (i, v) in fields.iter().enumerate() { f.add(i).write(*v); } } b as Value } /// `Ok(v)` (`Result` constructor 0). pub(crate) fn ok(ctx: *mut Ctx, v: Value) -> Value { cell(ctx, 0, &[v]) } /// `Error(message)` (`Result` constructor 1). pub(crate) fn error(ctx: *mut Ctx, message: &str) -> Value { // SAFETY: `message` is valid for its length. let text = unsafe { tl_string_from(ctx, message.as_ptr().cast(), message.len()) }; cell(ctx, 1, &[text]) } /// A `List` (`Nil` is the small int 0, `Cons` constructor 1) of `items` /// (owned). pub(crate) fn list(ctx: *mut Ctx, items: impl DoubleEndedIterator) -> Value { items .rev() .fold(int(0), |tail, head| cell(ctx, 1, &[head, tail])) } /// The elements of a `List` (borrowed). /// /// # Safety /// `list` must be a live list. pub(crate) unsafe fn list_items(mut list: Value) -> impl Iterator { std::iter::from_fn(move || { if !is_ptr(list) { return None; } // SAFETY: a `Cons` cell has the head, then the tail. unsafe { let f = Block::fields_ptr(list as *mut Block); list = f.add(1).read(); Some(f.read()) } }) } /// Print `s` and a newline to stdout, through the console (ADR 0022): /// the actor parks, rather than its thread blocks, while the console is /// behind. Borrows `s` (like every function the standard library /// declares `@extern`). /// /// # Safety /// `ctx` must be the running actor's context (or null); `s` a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_println(ctx: *mut Ctx, s: Value) -> Value { // SAFETY: caller passes its context and a live string. unsafe { crate::console::write(ctx, crate::console::Stream::Out, &[string_bytes(s), b"\n"]); } crate::abi::UNIT } pub type ClosureFn = unsafe extern "C" fn(); /// Allocate a closure with `env_count` captured values (initialised to /// unit; the caller stores the environment into fields 0..env_count). /// `code` is the owned entry, `borrowed` the borrowed-contract one /// (ADR 0068): called with the closure and the arguments borrowed, it /// neither drops nor consumes them. #[unsafe(no_mangle)] pub extern "C" fn tl_closure_alloc( ctx: *mut Ctx, code: ClosureFn, borrowed: ClosureFn, env_count: u8, ) -> Value { let b = tl_alloc(ctx, TAG_CLOSURE, env_count, 2 * WORD); // SAFETY: the code pointers live in the raw area after the env fields. unsafe { let raw = Block::fields_ptr(b) .add(env_count as usize) .cast::(); raw.write(code); raw.add(1).write(borrowed); } b as Value } /// # Safety /// `clo` must be a live closure (borrowed). pub unsafe fn closure_code(clo: Value) -> ClosureFn { // SAFETY: caller guarantees `clo` is a live closure. unsafe { closure_slot(clo, 0) } } /// The borrowed-contract entry (ADR 0068). /// /// # Safety /// `clo` must be a live closure (borrowed). pub unsafe fn closure_code_borrowed(clo: Value) -> ClosureFn { // SAFETY: caller guarantees `clo` is a live closure. unsafe { closure_slot(clo, 1) } } /// Entry `slot` of `clo` (0 owned, 1 borrowed). /// /// # Safety /// `clo` must be a live closure (borrowed). unsafe fn closure_slot(clo: Value, slot: usize) -> ClosureFn { let b = clo as *mut Block; // SAFETY: caller guarantees `clo` is a live closure; the raw area // holds two code pointers after the env fields. unsafe { let n = (*b).header.scan_fsize as usize; Block::fields_ptr(b) .add(n + slot) .cast::() .read() } } /// The owned-entry signature every closure entry has. type Entry = unsafe extern "C" fn(*mut Ctx, Value, Value, Value, Value, Value, Value) -> Value; /// The borrowed entry (ADR 0068) of a runtime-made closure called with no /// arguments: the caller keeps its references, so dup `this` for the /// owned entry, which consumes the duplicate. /// /// # Safety /// `ctx` must be the running actor's context; `this` a live closure whose /// owned entry takes no arguments. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_borrowed0( ctx: *mut Ctx, this: Value, _: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: forwarded caller guarantees; the owned entry consumes the // duplicates. unsafe { crate::heap::dup_value(this); let code: Entry = std::mem::transmute(closure_code(this)); code(ctx, this, UNIT, UNIT, UNIT, UNIT, UNIT) } } /// [`tl_borrowed0`] for a closure called with one argument. /// /// # Safety /// `ctx` must be the running actor's context; `this` a live closure whose /// owned entry takes one argument. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_borrowed1( ctx: *mut Ctx, this: Value, a: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as `tl_borrowed0`. unsafe { crate::heap::dup_value(this); crate::heap::dup_value(a); let code: Entry = std::mem::transmute(closure_code(this)); code(ctx, this, a, UNIT, UNIT, UNIT, UNIT) } } /// [`tl_borrowed0`] for a closure called with two arguments. /// /// # Safety /// `ctx` must be the running actor's context; `this` a live closure whose /// owned entry takes two arguments. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_borrowed2( ctx: *mut Ctx, this: Value, a: Value, b: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as `tl_borrowed0`. unsafe { crate::heap::dup_value(this); crate::heap::dup_value(a); crate::heap::dup_value(b); let code: Entry = std::mem::transmute(closure_code(this)); code(ctx, this, a, b, UNIT, UNIT, UNIT) } }