| @@ -0,0 +1,415 @@ |
| 1 | +//! `std/array`: immutable arrays, updated in place when unique (ADR 0014). |
| 2 | +//! |
| 3 | +//! An array is a `TAG_ARRAY` block with `scan_fsize` [`SCAN_LARGE`]. In |
| 4 | +//! words after the header: |
| 5 | +//! |
| 6 | +//! ```text |
| 7 | +//! [ tl_int(n) | x1 ... xn | spare | spare unused slots ] |
| 8 | +//! ``` |
| 9 | +//! |
| 10 | +//! The first `1 + n` words are the layout the ABI reserved for large |
| 11 | +//! blocks, so drop and `send` walk arrays like any block. The raw area is |
| 12 | +//! the spare capacity: a plain `i64` count, then that many zeroed slots. |
| 13 | +//! A block of capacity `cap` is always `2 + cap` words long. |
| 14 | +//! |
| 15 | +//! `set` and `push` are `owned` externs: they consume the array, so a |
| 16 | +//! count of 1 means nobody else can see it, and they update it in place. |
| 17 | +//! A shared array (count > 1, or negative: sent to other actors) is |
| 18 | +//! copied first. The other functions borrow their arguments, like every |
| 19 | +//! `@extern` function. All of them must behave like the interpreter's |
| 20 | +//! (`tilc_core::interp`). |
| 21 | + |
| 22 | +use crate::abi::{Block, Ctx, Header, SCAN_LARGE, TAG_ARRAY, UNIT, Value, int, int_get}; |
| 23 | +use crate::heap::{alloc_bytes, drop_value, dup_value, realloc_block}; |
| 24 | +use crate::prims::panic_with; |
| 25 | +use crate::values::{cell, list, list_items}; |
| 26 | + |
| 27 | +const WORD: usize = size_of::<Value>(); |
| 28 | +const HEADER: usize = size_of::<Header>(); |
| 29 | +/// The smallest capacity an array grows to. |
| 30 | +const MIN_GROW: usize = 4; |
| 31 | +/// `with_capacity` hints above this are capped (pushes still grow). |
| 32 | +const MAX_HINT: i64 = 1 << 24; |
| 33 | + |
| 34 | +/// A fresh array of `len` units with capacity `cap >= len`. |
| 35 | +fn alloc(ctx: *mut Ctx, len: usize, cap: usize) -> *mut Block { |
| 36 | + debug_assert!(len <= cap); |
| 37 | + let b = alloc_bytes(ctx, HEADER + WORD * (2 + cap)); |
| 38 | + // SAFETY: a fresh block of `2 + cap` words after the header. |
| 39 | + unsafe { |
| 40 | + b.cast::<Header>().write(Header { |
| 41 | + rc: 1, |
| 42 | + tag: TAG_ARRAY, |
| 43 | + scan_fsize: SCAN_LARGE, |
| 44 | + flags: 0, |
| 45 | + }); |
| 46 | + let words = Block::fields_ptr(b); |
| 47 | + for i in 0..len { |
| 48 | + words.add(1 + i).write(UNIT); |
| 49 | + } |
| 50 | + // Zeroed spare slots: a copy (`send`) never reads uninitialised |
| 51 | + // memory. |
| 52 | + std::ptr::write_bytes(words.add(1 + len), 0, cap - len + 1); |
| 53 | + set_len(b, len, cap - len); |
| 54 | + } |
| 55 | + b |
| 56 | +} |
| 57 | + |
| 58 | +/// Record `len` elements and `spare` unused slots after them. |
| 59 | +/// |
| 60 | +/// # Safety |
| 61 | +/// `b` must be an array block of capacity `len + spare`. |
| 62 | +unsafe fn set_len(b: *mut Block, len: usize, spare: usize) { |
| 63 | + // SAFETY: forwarded caller guarantee: word `1 + len` is the spare count. |
| 64 | + unsafe { |
| 65 | + let words = Block::fields_ptr(b); |
| 66 | + words.write(int(len as i64)); |
| 67 | + words.add(1 + len).cast::<i64>().write(spare as i64); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +/// The number of elements. |
| 72 | +/// |
| 73 | +/// # Safety |
| 74 | +/// `a` must be a live array. |
| 75 | +unsafe fn len(a: Value) -> usize { |
| 76 | + // SAFETY: an array's first word is its count. |
| 77 | + int_get(unsafe { *Block::fields_ptr(a as *mut Block) }) as usize |
| 78 | +} |
| 79 | + |
| 80 | +/// The unused slots after the elements. |
| 81 | +/// |
| 82 | +/// # Safety |
| 83 | +/// `a` must be a live array. |
| 84 | +unsafe fn spare(a: Value) -> usize { |
| 85 | + // SAFETY: the word after the elements is the spare count. |
| 86 | + unsafe { elems(a).add(len(a)).cast::<i64>().read() as usize } |
| 87 | +} |
| 88 | + |
| 89 | +/// The first element's slot. |
| 90 | +fn elems(a: Value) -> *mut Value { |
| 91 | + Block::fields_ptr(a as *mut Block).wrapping_add(1) |
| 92 | +} |
| 93 | + |
| 94 | +/// The elements (borrowed). |
| 95 | +/// |
| 96 | +/// # Safety |
| 97 | +/// `a` must be a live array, not changed while the slice is used. |
| 98 | +unsafe fn items<'a>(a: Value) -> &'a [Value] { |
| 99 | + // SAFETY: forwarded caller guarantee. |
| 100 | + unsafe { std::slice::from_raw_parts(elems(a), len(a)) } |
| 101 | +} |
| 102 | + |
| 103 | +/// A new array holding `items` (borrowed: each is dup'd), with capacity |
| 104 | +/// `cap`. |
| 105 | +fn from_items(ctx: *mut Ctx, items: &[Value], cap: usize) -> Value { |
| 106 | + let b = alloc(ctx, items.len(), cap.max(items.len())); |
| 107 | + let a = b as Value; |
| 108 | + for (i, x) in items.iter().enumerate() { |
| 109 | + // SAFETY: `x` is live (borrowed from the caller); slot `i` exists. |
| 110 | + unsafe { |
| 111 | + dup_value(*x); |
| 112 | + elems(a).add(i).write(*x); |
| 113 | + } |
| 114 | + } |
| 115 | + a |
| 116 | +} |
| 117 | + |
| 118 | +/// `i` as an index of `a`, if it is one. |
| 119 | +/// |
| 120 | +/// # Safety |
| 121 | +/// `a` must be a live array. |
| 122 | +unsafe fn index(a: Value, i: Value) -> Option<usize> { |
| 123 | + // SAFETY: forwarded caller guarantee. |
| 124 | + let n = unsafe { len(a) }; |
| 125 | + usize::try_from(int_get(i)).ok().filter(|i| *i < n) |
| 126 | +} |
| 127 | + |
| 128 | +/// An empty array with room for `n` elements before it grows. |
| 129 | +#[unsafe(no_mangle)] |
| 130 | +pub extern "C" fn tl_array_with_capacity(ctx: *mut Ctx, n: Value) -> Value { |
| 131 | + alloc(ctx, 0, int_get(n).clamp(0, MAX_HINT) as usize) as Value |
| 132 | +} |
| 133 | + |
| 134 | +/// # Safety |
| 135 | +/// `a` must be a live array. |
| 136 | +#[unsafe(no_mangle)] |
| 137 | +pub unsafe extern "C" fn tl_array_length(_ctx: *mut Ctx, a: Value) -> Value { |
| 138 | + // SAFETY: caller guarantees a live array. |
| 139 | + int(unsafe { len(a) } as i64) |
| 140 | +} |
| 141 | + |
| 142 | +/// An array of the elements of a `List`. |
| 143 | +/// |
| 144 | +/// # Safety |
| 145 | +/// `list` must be a live list. |
| 146 | +#[unsafe(no_mangle)] |
| 147 | +pub unsafe extern "C" fn tl_array_from_list(ctx: *mut Ctx, list: Value) -> Value { |
| 148 | + // SAFETY: caller guarantees a live list. |
| 149 | + let items: Vec<Value> = unsafe { list_items(list) }.collect(); |
| 150 | + from_items(ctx, &items, items.len()) |
| 151 | +} |
| 152 | + |
| 153 | +/// The elements as a `List`. |
| 154 | +/// |
| 155 | +/// # Safety |
| 156 | +/// `a` must be a live array. |
| 157 | +#[unsafe(no_mangle)] |
| 158 | +pub unsafe extern "C" fn tl_array_to_list(ctx: *mut Ctx, a: Value) -> Value { |
| 159 | + // SAFETY: caller guarantees a live array; its elements are live. |
| 160 | + let items = unsafe { items(a) }; |
| 161 | + list( |
| 162 | + ctx, |
| 163 | + items.iter().map(|x| { |
| 164 | + // SAFETY: as above. |
| 165 | + unsafe { dup_value(*x) }; |
| 166 | + *x |
| 167 | + }), |
| 168 | + ) |
| 169 | +} |
| 170 | + |
| 171 | +/// `Some(element)` at `i`, or `None` out of range. |
| 172 | +/// |
| 173 | +/// # Safety |
| 174 | +/// `a` must be a live array. |
| 175 | +#[unsafe(no_mangle)] |
| 176 | +pub unsafe extern "C" fn tl_array_get(ctx: *mut Ctx, a: Value, i: Value) -> Value { |
| 177 | + // SAFETY: caller guarantees a live array. |
| 178 | + match unsafe { index(a, i) } { |
| 179 | + // SAFETY: `i` is in range; the element is live. |
| 180 | + Some(i) => unsafe { |
| 181 | + let x = *elems(a).add(i); |
| 182 | + dup_value(x); |
| 183 | + cell(ctx, 1, &[x]) |
| 184 | + }, |
| 185 | + None => int(0), |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +/// The element at `i`, which `std/array` keeps in range (`fold`, `map`); |
| 190 | +/// panics otherwise. |
| 191 | +/// |
| 192 | +/// # Safety |
| 193 | +/// `ctx` must be the running actor's context; `a` a live array. |
| 194 | +#[unsafe(no_mangle)] |
| 195 | +pub unsafe extern "C" fn tl_array_at(ctx: *mut Ctx, a: Value, i: Value) -> Value { |
| 196 | + // SAFETY: caller guarantees a live array. |
| 197 | + match unsafe { index(a, i) } { |
| 198 | + // SAFETY: `i` is in range; the element is live. |
| 199 | + Some(i) => unsafe { |
| 200 | + let x = *elems(a).add(i); |
| 201 | + dup_value(x); |
| 202 | + x |
| 203 | + }, |
| 204 | + None => panic_with(ctx, &out_of_range("array.at", a, i)), |
| 205 | + } |
| 206 | +} |
| 207 | + |
| 208 | +/// The message of an index out of range. |
| 209 | +fn out_of_range(op: &str, a: Value, i: Value) -> String { |
| 210 | + // SAFETY: called with a live array. |
| 211 | + let n = unsafe { len(a) }; |
| 212 | + format!("{op}: index {} out of range for length {n}", int_get(i)) |
| 213 | +} |
| 214 | + |
| 215 | +/// `a` with `x` at index `i`: in place if `a` is unique, else in a copy. |
| 216 | +/// Panics if `i` is out of range. Consumes `a` and `x` (an `owned` |
| 217 | +/// extern). |
| 218 | +/// |
| 219 | +/// # Safety |
| 220 | +/// `ctx` must be the running actor's context; `a` an owned array, `x` an |
| 221 | +/// owned value. |
| 222 | +#[unsafe(no_mangle)] |
| 223 | +pub unsafe extern "C" fn tl_array_set(ctx: *mut Ctx, a: Value, i: Value, x: Value) -> Value { |
| 224 | + // SAFETY: caller guarantees an owned array and value. |
| 225 | + unsafe { |
| 226 | + let Some(i) = index(a, i) else { |
| 227 | + let message = out_of_range("array.set", a, i); |
| 228 | + drop_value(ctx, a); |
| 229 | + drop_value(ctx, x); |
| 230 | + return panic_with(ctx, &message); |
| 231 | + }; |
| 232 | + let a = unique(ctx, a, 0); |
| 233 | + let slot = elems(a).add(i); |
| 234 | + let old = slot.read(); |
| 235 | + slot.write(x); |
| 236 | + drop_value(ctx, old); |
| 237 | + a |
| 238 | + } |
| 239 | +} |
| 240 | + |
| 241 | +/// `a` with `x` appended: in place if `a` is unique and has a spare slot; |
| 242 | +/// a unique array without one grows (doubling). Consumes `a` and `x` (an |
| 243 | +/// `owned` extern). |
| 244 | +/// |
| 245 | +/// # Safety |
| 246 | +/// `ctx` must be the running actor's context; `a` an owned array, `x` an |
| 247 | +/// owned value. |
| 248 | +#[unsafe(no_mangle)] |
| 249 | +pub unsafe extern "C" fn tl_array_push(ctx: *mut Ctx, a: Value, x: Value) -> Value { |
| 250 | + // SAFETY: caller guarantees an owned array and value. |
| 251 | + unsafe { |
| 252 | + let a = unique(ctx, a, 1); |
| 253 | + let (n, s) = (len(a), spare(a)); |
| 254 | + let a = if s > 0 { |
| 255 | + a |
| 256 | + } else { |
| 257 | + let cap = (2 * n).max(MIN_GROW); |
| 258 | + let b = realloc_block(a as *mut Block, HEADER + WORD * (2 + cap)); |
| 259 | + std::ptr::write_bytes(Block::fields_ptr(b).add(1 + n), 0, cap - n + 1); |
| 260 | + set_len(b, n, cap - n); |
| 261 | + b as Value |
| 262 | + }; |
| 263 | + let s = spare(a); |
| 264 | + elems(a).add(n).write(x); |
| 265 | + set_len(a as *mut Block, n + 1, s - 1); |
| 266 | + a |
| 267 | + } |
| 268 | +} |
| 269 | + |
| 270 | +/// `a` itself if it is unique, else a copy (giving up one reference to |
| 271 | +/// `a`), with at least `extra` spare slots. A copy for one more element |
| 272 | +/// gets room to grow, so pushes on it are in place afterwards. |
| 273 | +/// |
| 274 | +/// # Safety |
| 275 | +/// `ctx` must be the running actor's context; `a` an owned array. |
| 276 | +unsafe fn unique(ctx: *mut Ctx, a: Value, extra: usize) -> Value { |
| 277 | + // SAFETY: caller guarantees an owned (live) array. |
| 278 | + unsafe { |
| 279 | + if (*(a as *mut Block)).header.rc == 1 { |
| 280 | + return a; |
| 281 | + } |
| 282 | + let n = len(a); |
| 283 | + let cap = if extra == 0 { |
| 284 | + n |
| 285 | + } else { |
| 286 | + (2 * n).max(n + extra).max(MIN_GROW) |
| 287 | + }; |
| 288 | + let copy = from_items(ctx, items(a), cap); |
| 289 | + drop_value(ctx, a); |
| 290 | + copy |
| 291 | + } |
| 292 | +} |
| 293 | + |
| 294 | +/// The elements from `start` up to `end` (excluded), both clamped to |
| 295 | +/// `0..length`; empty when `end <= start`. |
| 296 | +/// |
| 297 | +/// # Safety |
| 298 | +/// `a` must be a live array. |
| 299 | +#[unsafe(no_mangle)] |
| 300 | +pub unsafe extern "C" fn tl_array_slice( |
| 301 | + ctx: *mut Ctx, |
| 302 | + a: Value, |
| 303 | + start: Value, |
| 304 | + end: Value, |
| 305 | +) -> Value { |
| 306 | + // SAFETY: caller guarantees a live array. |
| 307 | + let items = unsafe { items(a) }; |
| 308 | + let clamp = |v: Value| int_get(v).clamp(0, items.len() as i64) as usize; |
| 309 | + let (start, end) = (clamp(start), clamp(end)); |
| 310 | + let part = &items[start..end.max(start)]; |
| 311 | + from_items(ctx, part, part.len()) |
| 312 | +} |
| 313 | + |
| 314 | +#[cfg(test)] |
| 315 | +mod tests { |
| 316 | + use super::*; |
| 317 | + |
| 318 | + fn ints(a: Value) -> Vec<i64> { |
| 319 | + // SAFETY: tests pass live arrays of ints. |
| 320 | + unsafe { items(a) }.iter().map(|v| int_get(*v)).collect() |
| 321 | + } |
| 322 | + |
| 323 | + fn rc(v: Value) -> i32 { |
| 324 | + // SAFETY: tests pass live blocks. |
| 325 | + unsafe { (*(v as *mut Block)).header.rc } |
| 326 | + } |
| 327 | + |
| 328 | + /// Pushes stay in the block while there is room, then grow it. |
| 329 | + unsafe fn push_in_place_and_grow(ctx: *mut Ctx) { |
| 330 | + // SAFETY: every array is owned by this test. |
| 331 | + unsafe { |
| 332 | + let mut a = tl_array_with_capacity(ctx, int(2)); |
| 333 | + let first = a; |
| 334 | + for i in 0..2 { |
| 335 | + a = tl_array_push(ctx, a, int(i)); |
| 336 | + } |
| 337 | + assert_eq!((a, spare(a)), (first, 0)); |
| 338 | + for i in 2..100 { |
| 339 | + a = tl_array_push(ctx, a, int(i)); |
| 340 | + } |
| 341 | + assert_eq!(ints(a), (0..100).collect::<Vec<_>>()); |
| 342 | + assert_eq!(spare(a) + 100, 128); |
| 343 | + drop_value(ctx, a); |
| 344 | + } |
| 345 | + } |
| 346 | + |
| 347 | + /// Updates copy an array someone else holds, and change a unique one. |
| 348 | + unsafe fn shared_arrays_are_copied(ctx: *mut Ctx) { |
| 349 | + // SAFETY: every value is owned by this test. |
| 350 | + unsafe { |
| 351 | + let list = list(ctx, (1..=3).map(int)); |
| 352 | + let a = tl_array_from_list(ctx, list); |
| 353 | + drop_value(ctx, list); |
| 354 | + dup_value(a); |
| 355 | + let b = tl_array_set(ctx, a, int(0), int(9)); |
| 356 | + assert_ne!(a, b); |
| 357 | + assert_eq!((ints(a), ints(b)), (vec![1, 2, 3], vec![9, 2, 3])); |
| 358 | + assert_eq!((rc(a), rc(b)), (1, 1)); |
| 359 | + dup_value(a); |
| 360 | + let c = tl_array_push(ctx, a, int(4)); |
| 361 | + assert_eq!((ints(a), ints(c)), (vec![1, 2, 3], vec![1, 2, 3, 4])); |
| 362 | + // The copy has room: the next push is in place. |
| 363 | + let d = tl_array_push(ctx, c, int(5)); |
| 364 | + assert_eq!(c, d); |
| 365 | + let e = tl_array_set(ctx, a, int(2), int(7)); |
| 366 | + assert_eq!((e, ints(e)), (a, vec![1, 2, 7])); |
| 367 | + for v in [b, d, e] { |
| 368 | + drop_value(ctx, v); |
| 369 | + } |
| 370 | + } |
| 371 | + } |
| 372 | + |
| 373 | + /// Elements are counted: read, sliced, replaced and dropped. |
| 374 | + unsafe fn elements_are_counted(ctx: *mut Ctx) { |
| 375 | + // SAFETY: every value is owned by this test. |
| 376 | + unsafe { |
| 377 | + let s = crate::values::tl_string_from(ctx, c"x".as_ptr(), 1); |
| 378 | + dup_value(s); // the list's reference |
| 379 | + let list = list(ctx, [s].into_iter()); |
| 380 | + let a = tl_array_from_list(ctx, list); |
| 381 | + drop_value(ctx, list); |
| 382 | + assert_eq!(rc(s), 2); |
| 383 | + let part = tl_array_slice(ctx, a, int(-5), int(9)); |
| 384 | + assert_eq!(rc(s), 3); |
| 385 | + let got = tl_array_get(ctx, part, int(0)); |
| 386 | + assert_eq!(rc(s), 4); |
| 387 | + let a = tl_array_set(ctx, a, int(0), int(1)); |
| 388 | + assert_eq!(rc(s), 3); |
| 389 | + assert_eq!(tl_array_get(ctx, a, int(1)), int(0)); |
| 390 | + for v in [a, part, got] { |
| 391 | + drop_value(ctx, v); |
| 392 | + } |
| 393 | + assert_eq!(rc(s), 1); |
| 394 | + drop_value(ctx, s); |
| 395 | + } |
| 396 | + } |
| 397 | + |
| 398 | + /// The scenarios run as one root actor, so drops have a context. |
| 399 | + unsafe extern "C" fn scenarios(ctx: *mut Ctx) -> Value { |
| 400 | + // SAFETY: `ctx` is the root actor's. |
| 401 | + unsafe { |
| 402 | + push_in_place_and_grow(ctx); |
| 403 | + shared_arrays_are_copied(ctx); |
| 404 | + elements_are_counted(ctx); |
| 405 | + } |
| 406 | + assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); |
| 407 | + UNIT |
| 408 | + } |
| 409 | + |
| 410 | + #[test] |
| 411 | + fn updates_in_place_and_copies() { |
| 412 | + // SAFETY: `scenarios` follows the generated-code convention. |
| 413 | + assert_eq!(unsafe { crate::sched::run_test_actor(scenarios) }, 0); |
| 414 | + } |
| 415 | +} |