tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

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