1use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
11use std::cell::Cell;
12use std::mem::size_of;
13use std::sync::OnceLock;
14
15pub const MAX_CTOR_TAG: u8 = 243;
17pub const TAG_CLOSURE: u8 = 245;
18pub const TAG_ARRAY: u8 = 246;
19pub const TAG_SARRAY: u8 = 248;
20pub const TAG_STRING: u8 = 249;
21pub const TAG_MPZ: u8 = 250;
22pub const TAG_MAP: u8 = 254;
24
25pub const CLOSURE_MAX_ARGS: usize = 16;
27
28#[repr(C)]
30pub struct Header {
31 rc: Cell<i32>,
34 size: u16,
36 other: u8,
38 tag: u8,
39}
40
41const WORD: usize = size_of::<usize>();
42const HEADER: usize = size_of::<Header>();
43
44#[derive(Clone, Copy, PartialEq, Eq, Debug)]
46#[repr(transparent)]
47pub struct Obj(*mut Header);
48
49#[inline(always)]
51pub fn box_(n: usize) -> Obj {
52 Obj(std::ptr::without_provenance_mut((n << 1) | 1))
53}
54
55#[inline(always)]
56pub fn unbox(o: Obj) -> usize {
57 o.0.addr() >> 1
58}
59
60#[inline(always)]
61pub fn is_scalar(o: Obj) -> bool {
62 o.0.addr() & 1 == 1
63}
64
65impl Obj {
66 #[inline(always)]
67 pub(crate) fn from_header(header: *mut Header) -> Obj {
68 Obj(header)
69 }
70
71 #[inline(always)]
72 pub(crate) fn header(self) -> *mut Header {
73 self.0
74 }
75}
76
77impl Header {
78 pub(crate) fn other(&self) -> u8 {
80 self.other
81 }
82}
83
84pub(crate) fn new_header(tag: u8, other: u8, size: u16) -> Header {
85 Header { rc: Cell::new(1), size, other, tag }
86}
87
88#[inline(always)]
89unsafe fn rc(o: Obj) -> &'static Cell<i32> {
90 &(*o.0).rc
91}
92
93#[inline(always)]
95pub unsafe fn ptr_tag(o: Obj) -> u8 {
96 (*o.0).tag
97}
98
99#[inline(always)]
101pub unsafe fn obj_tag(o: Obj) -> u32 {
102 if is_scalar(o) {
103 unbox(o) as u32
104 } else {
105 ptr_tag(o) as u32
106 }
107}
108
109#[inline(always)]
110pub unsafe fn inc_ref(o: Obj) {
111 let count = rc(o);
112 if count.get() > 0 {
113 count.set(count.get() + 1);
114 }
115}
116
117#[inline(always)]
118pub unsafe fn inc_ref_n(o: Obj, n: u32) {
119 let count = rc(o);
120 if count.get() > 0 {
121 count.set(count.get() + n as i32);
122 }
123}
124
125#[inline(always)]
126pub unsafe fn inc(o: Obj) {
127 if !is_scalar(o) {
128 inc_ref(o);
129 }
130}
131
132#[inline(always)]
133pub unsafe fn inc_n(o: Obj, n: u32) {
134 if !is_scalar(o) {
135 inc_ref_n(o, n);
136 }
137}
138
139#[inline(always)]
140pub unsafe fn dec_ref(o: Obj) {
141 let count = rc(o);
142 if count.get() > 1 {
143 count.set(count.get() - 1);
144 } else if count.get() == 1 {
145 free(o);
146 }
147}
148
149#[inline(always)]
150pub unsafe fn dec(o: Obj) {
151 if !is_scalar(o) {
152 dec_ref(o);
153 }
154}
155
156#[inline(always)]
158pub unsafe fn is_exclusive(o: Obj) -> bool {
159 !is_scalar(o) && rc(o).get() == 1
160}
161
162thread_local! {
163 static LIVE: Cell<isize> = const { Cell::new(0) };
164}
165
166#[inline(always)]
168pub(crate) fn count_object(change: isize) {
169 if cfg!(debug_assertions) {
170 LIVE.with(|live| live.set(live.get() + change));
171 }
172}
173
174pub fn live_objects() -> isize {
177 LIVE.with(Cell::get)
178}
179
180unsafe fn allocate(size: usize) -> *mut Header {
181 count_object(1);
182 let layout = Layout::from_size_align_unchecked(size, WORD.max(8));
183 let memory = alloc(layout);
184 if memory.is_null() {
185 handle_alloc_error(layout);
186 }
187 memory.cast()
188}
189
190unsafe fn deallocate(header: *mut Header, size: usize) {
191 count_object(-1);
192 dealloc(header.cast(), Layout::from_size_align_unchecked(size, WORD.max(8)));
193}
194
195unsafe fn children(o: Obj) -> [&'static [Obj]; 2] {
197 let one = |objects: &'static [Obj]| [objects, &[]];
198 match ptr_tag(o) {
199 tag if tag <= MAX_CTOR_TAG => one(std::slice::from_raw_parts(ctor_fields(o), (*o.0).other as usize)),
200 TAG_CLOSURE => {
201 let closure = o.0.cast::<Closure>();
202 one(std::slice::from_raw_parts(closure_args(o), (*closure).num_fixed as usize))
203 }
204 TAG_ARRAY => one(crate::array::elements(o)),
205 TAG_MAP => crate::map::children(o),
206 _ => one(&[]),
207 }
208}
209
210pub unsafe fn free_object(o: Obj) {
212 if is_scalar(o) {
213 return;
214 }
215 match ptr_tag(o) {
216 tag if tag <= MAX_CTOR_TAG => deallocate(o.0, (*o.0).size as usize),
217 TAG_CLOSURE => {
218 let closure = o.0.cast::<Closure>();
219 deallocate(o.0, closure_size((*closure).num_fixed as usize));
220 }
221 TAG_ARRAY => crate::array::free(o),
222 TAG_SARRAY => crate::sarray::free(o),
223 TAG_STRING => crate::string::free(o),
224 TAG_MPZ => crate::nat::free_big(o),
225 TAG_MAP => crate::map::free(o),
226 tag => unreachable!("inlean: object of unknown kind {tag}"),
227 }
228}
229
230unsafe fn free(o: Obj) {
233 let mut pending: Vec<Obj> = Vec::new();
234 let mut current = o;
235 loop {
236 for &child in children(current).into_iter().flatten() {
237 if is_scalar(child) {
238 continue;
239 }
240 let count = rc(child);
241 if count.get() > 1 {
242 count.set(count.get() - 1);
243 } else if count.get() == 1 {
244 pending.push(child);
245 }
246 }
247 free_object(current);
248 match pending.pop() {
249 Some(next) => current = next,
250 None => return,
251 }
252 }
253}
254
255pub unsafe fn mark_persistent(o: Obj) {
258 let mut pending = vec![o];
259 while let Some(current) = pending.pop() {
260 if is_scalar(current) || rc(current).get() == 0 {
261 continue;
262 }
263 rc(current).set(0);
264 for run in children(current) {
265 pending.extend_from_slice(run);
266 }
267 }
268}
269
270#[inline(always)]
273unsafe fn ctor_fields(o: Obj) -> *mut Obj {
274 o.0.cast::<u8>().add(HEADER).cast()
275}
276
277pub unsafe fn alloc_ctor(tag: u32, num_objs: u32, num_usize: u32, scalar_size: u32) -> Obj {
280 let size = HEADER + (num_objs + num_usize) as usize * WORD + scalar_size as usize;
281 let size = size.next_multiple_of(WORD.max(8));
282 let header = allocate(size);
283 header.write(new_header(tag as u8, num_objs as u8, size as u16));
284 Obj(header)
285}
286
287#[inline(always)]
288pub unsafe fn ctor_get(o: Obj, i: u32) -> Obj {
289 *ctor_fields(o).add(i as usize)
290}
291
292#[inline(always)]
293pub unsafe fn ctor_set(o: Obj, i: u32, value: Obj) {
294 *ctor_fields(o).add(i as usize) = value;
295}
296
297#[inline(always)]
298pub unsafe fn ctor_set_tag(o: Obj, tag: u32) {
299 (*o.0).tag = tag as u8;
300}
301
302#[inline(always)]
304pub unsafe fn ctor_release(o: Obj, i: u32) {
305 let field = ctor_fields(o).add(i as usize);
306 dec(*field);
307 *field = box_(0);
309}
310
311pub unsafe fn reset(o: Obj, num_objs: u32) -> Obj {
315 if is_exclusive(o) {
316 for i in 0..num_objs {
317 ctor_release(o, i);
318 }
319 o
320 } else {
321 dec_ref(o);
322 box_(0)
323 }
324}
325
326pub unsafe fn reuse(memory: Obj, tag: u32, num_objs: u32, num_usize: u32, scalar_size: u32, update_tag: bool) -> Obj {
329 if is_scalar(memory) {
330 alloc_ctor(tag, num_objs, num_usize, scalar_size)
331 } else {
332 if update_tag {
333 ctor_set_tag(memory, tag);
334 }
335 memory
336 }
337}
338
339#[inline(always)]
340pub unsafe fn ctor_get_usize(o: Obj, slot: u32) -> usize {
341 ctor_fields(o).add(slot as usize).cast::<usize>().read()
342}
343
344#[inline(always)]
345pub unsafe fn ctor_set_usize(o: Obj, slot: u32, value: usize) {
346 ctor_fields(o).add(slot as usize).cast::<usize>().write(value);
347}
348
349macro_rules! ctor_scalars {
350 ($($get:ident $set:ident $ty:ty),*) => {$(
351 #[inline(always)]
353 pub unsafe fn $get(o: Obj, slots: u32, offset: u32) -> $ty {
354 ctor_fields(o).cast::<u8>().add(slots as usize * WORD + offset as usize).cast::<$ty>().read_unaligned()
355 }
356
357 #[inline(always)]
359 pub unsafe fn $set(o: Obj, slots: u32, offset: u32, value: $ty) {
360 ctor_fields(o).cast::<u8>().add(slots as usize * WORD + offset as usize).cast::<$ty>().write_unaligned(value);
361 }
362 )*};
363}
364
365ctor_scalars!(
366 ctor_get_uint8 ctor_set_uint8 u8,
367 ctor_get_uint16 ctor_set_uint16 u16,
368 ctor_get_uint32 ctor_set_uint32 u32,
369 ctor_get_uint64 ctor_set_uint64 u64,
370 ctor_get_float ctor_set_float f64,
371 ctor_get_float32 ctor_set_float32 f32
372);
373
374#[inline(always)]
378pub unsafe fn box_uint32(value: u32) -> Obj {
379 if WORD == 4 {
380 let o = alloc_ctor(0, 0, 0, 4);
381 ctor_set_uint32(o, 0, 0, value);
382 o
383 } else {
384 box_(value as usize)
385 }
386}
387
388#[inline(always)]
389pub unsafe fn unbox_uint32(o: Obj) -> u32 {
390 if WORD == 4 {
391 ctor_get_uint32(o, 0, 0)
392 } else {
393 unbox(o) as u32
394 }
395}
396
397pub unsafe fn box_uint64(value: u64) -> Obj {
398 let o = alloc_ctor(0, 0, 0, 8);
399 ctor_set_uint64(o, 0, 0, value);
400 o
401}
402
403#[inline(always)]
404pub unsafe fn unbox_uint64(o: Obj) -> u64 {
405 ctor_get_uint64(o, 0, 0)
406}
407
408pub unsafe fn box_usize(value: usize) -> Obj {
409 let o = alloc_ctor(0, 0, 1, 0);
410 ctor_set_usize(o, 0, value);
411 o
412}
413
414#[inline(always)]
415pub unsafe fn unbox_usize(o: Obj) -> usize {
416 ctor_get_usize(o, 0)
417}
418
419pub unsafe fn box_float(value: f64) -> Obj {
420 let o = alloc_ctor(0, 0, 0, 8);
421 ctor_set_float(o, 0, 0, value);
422 o
423}
424
425#[inline(always)]
426pub unsafe fn unbox_float(o: Obj) -> f64 {
427 ctor_get_float(o, 0, 0)
428}
429
430pub unsafe fn box_float32(value: f32) -> Obj {
431 let o = alloc_ctor(0, 0, 0, 4);
432 ctor_set_float32(o, 0, 0, value);
433 o
434}
435
436#[inline(always)]
437pub unsafe fn unbox_float32(o: Obj) -> f32 {
438 ctor_get_float32(o, 0, 0)
439}
440
441#[repr(C)]
444struct Closure {
445 header: Header,
446 function: *const (),
448 arity: u16,
449 num_fixed: u16,
450}
451
452fn closure_size(num_fixed: usize) -> usize {
453 size_of::<Closure>() + num_fixed * WORD
454}
455
456#[inline(always)]
457unsafe fn closure_args(o: Obj) -> *mut Obj {
458 o.0.cast::<u8>().add(size_of::<Closure>()).cast()
459}
460
461pub unsafe fn alloc_closure(function: *const (), arity: u32, num_fixed: u32) -> Obj {
464 let closure = allocate(closure_size(num_fixed as usize)).cast::<Closure>();
465 closure.write(Closure {
466 header: new_header(TAG_CLOSURE, 0, 0),
467 function,
468 arity: arity as u16,
469 num_fixed: num_fixed as u16,
470 });
471 Obj(closure.cast())
472}
473
474#[inline(always)]
475pub unsafe fn closure_set(o: Obj, i: u32, value: Obj) {
476 *closure_args(o).add(i as usize) = value;
477}
478
479unsafe fn call(function: *const (), args: &[Obj]) -> Obj {
480 use std::mem::transmute as cast;
481 type O = Obj;
482 let a = args;
483 match a.len() {
484 1 => cast::<_, unsafe fn(O) -> O>(function)(a[0]),
485 2 => cast::<_, unsafe fn(O, O) -> O>(function)(a[0], a[1]),
486 3 => cast::<_, unsafe fn(O, O, O) -> O>(function)(a[0], a[1], a[2]),
487 4 => cast::<_, unsafe fn(O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3]),
488 5 => cast::<_, unsafe fn(O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4]),
489 6 => cast::<_, unsafe fn(O, O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4], a[5]),
490 7 => cast::<_, unsafe fn(O, O, O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4], a[5], a[6]),
491 8 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]),
492 9 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O) -> O>(function)(
493 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8],
494 ),
495 10 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O) -> O>(function)(
496 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9],
497 ),
498 11 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
499 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10],
500 ),
501 12 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
502 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11],
503 ),
504 13 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
505 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12],
506 ),
507 14 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
508 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13],
509 ),
510 15 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
511 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14],
512 ),
513 16 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
514 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15],
515 ),
516 n => panic!("inlean: a function of {n} arguments cannot be called through a closure"),
517 }
518}
519
520pub unsafe fn apply(f: Obj, args: &[Obj]) -> Obj {
525 let closure = f.0.cast::<Closure>();
526 let (function, arity, fixed) = ((*closure).function, (*closure).arity as usize, (*closure).num_fixed as usize);
527 let stored = std::slice::from_raw_parts(closure_args(f), fixed);
528 if fixed + args.len() < arity {
529 let extended = alloc_closure(function, arity as u32, (fixed + args.len()) as u32);
530 for (i, &arg) in stored.iter().chain(args).enumerate() {
531 closure_set(extended, i as u32, arg);
532 }
533 take_stored(f, stored);
534 return extended;
535 }
536 let (now, later) = args.split_at(arity - fixed);
537 let mut all = [box_(0); CLOSURE_MAX_ARGS];
538 assert!(arity <= CLOSURE_MAX_ARGS, "inlean: a function of {arity} arguments cannot be called through a closure");
539 all[..fixed].copy_from_slice(stored);
540 all[fixed..arity].copy_from_slice(now);
541 take_stored(f, stored);
542 let result = call(function, &all[..arity]);
543 if later.is_empty() {
544 result
545 } else {
546 apply(result, later)
547 }
548}
549
550unsafe fn take_stored(f: Obj, stored: &[Obj]) {
553 if is_exclusive(f) {
554 free_object(f);
555 } else {
556 for &arg in stored {
557 inc(arg);
558 }
559 dec_ref(f);
560 }
561}
562
563pub struct Constant(OnceLock<Shared>);
565
566struct Shared(Obj);
567
568unsafe impl Send for Shared {}
570unsafe impl Sync for Shared {}
571
572impl Constant {
573 #[allow(clippy::new_without_default)]
574 pub const fn new() -> Constant {
575 Constant(OnceLock::new())
576 }
577
578 pub unsafe fn get(&self, init: unsafe fn() -> Obj) -> Obj {
581 self.0
582 .get_or_init(|| {
583 let value = init();
584 mark_persistent(value);
585 Shared(value)
586 })
587 .0
588 }
589}