use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
use std::cell::Cell;
use std::mem::size_of;
use std::sync::OnceLock;
pub const MAX_CTOR_TAG: u8 = 243;
pub const TAG_CLOSURE: u8 = 245;
pub const TAG_ARRAY: u8 = 246;
pub const TAG_SARRAY: u8 = 248;
pub const TAG_STRING: u8 = 249;
pub const TAG_MPZ: u8 = 250;
pub const TAG_MAP: u8 = 254;
pub const CLOSURE_MAX_ARGS: usize = 16;
#[repr(C)]
pub struct Header {
rc: Cell<i32>,
size: u16,
other: u8,
tag: u8,
}
const WORD: usize = size_of::<usize>();
const HEADER: usize = size_of::<Header>();
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(transparent)]
pub struct Obj(*mut Header);
#[inline(always)]
pub fn box_(n: usize) -> Obj {
Obj(std::ptr::without_provenance_mut((n << 1) | 1))
}
#[inline(always)]
pub fn unbox(o: Obj) -> usize {
o.0.addr() >> 1
}
#[inline(always)]
pub fn is_scalar(o: Obj) -> bool {
o.0.addr() & 1 == 1
}
impl Obj {
#[inline(always)]
pub(crate) fn from_header(header: *mut Header) -> Obj {
Obj(header)
}
#[inline(always)]
pub(crate) fn header(self) -> *mut Header {
self.0
}
}
impl Header {
pub(crate) fn other(&self) -> u8 {
self.other
}
}
pub(crate) fn new_header(tag: u8, other: u8, size: u16) -> Header {
Header { rc: Cell::new(1), size, other, tag }
}
#[inline(always)]
unsafe fn rc(o: Obj) -> &'static Cell<i32> {
&(*o.0).rc
}
#[inline(always)]
pub unsafe fn ptr_tag(o: Obj) -> u8 {
(*o.0).tag
}
#[inline(always)]
pub unsafe fn obj_tag(o: Obj) -> u32 {
if is_scalar(o) {
unbox(o) as u32
} else {
ptr_tag(o) as u32
}
}
#[inline(always)]
pub unsafe fn inc_ref(o: Obj) {
let count = rc(o);
if count.get() > 0 {
count.set(count.get() + 1);
}
}
#[inline(always)]
pub unsafe fn inc_ref_n(o: Obj, n: u32) {
let count = rc(o);
if count.get() > 0 {
count.set(count.get() + n as i32);
}
}
#[inline(always)]
pub unsafe fn inc(o: Obj) {
if !is_scalar(o) {
inc_ref(o);
}
}
#[inline(always)]
pub unsafe fn inc_n(o: Obj, n: u32) {
if !is_scalar(o) {
inc_ref_n(o, n);
}
}
#[inline(always)]
pub unsafe fn dec_ref(o: Obj) {
let count = rc(o);
if count.get() > 1 {
count.set(count.get() - 1);
} else if count.get() == 1 {
free(o);
}
}
#[inline(always)]
pub unsafe fn dec(o: Obj) {
if !is_scalar(o) {
dec_ref(o);
}
}
#[inline(always)]
pub unsafe fn is_exclusive(o: Obj) -> bool {
!is_scalar(o) && rc(o).get() == 1
}
thread_local! {
static LIVE: Cell<isize> = const { Cell::new(0) };
}
#[inline(always)]
pub(crate) fn count_object(change: isize) {
if cfg!(debug_assertions) {
LIVE.with(|live| live.set(live.get() + change));
}
}
pub fn live_objects() -> isize {
LIVE.with(Cell::get)
}
unsafe fn allocate(size: usize) -> *mut Header {
count_object(1);
let layout = Layout::from_size_align_unchecked(size, WORD.max(8));
let memory = alloc(layout);
if memory.is_null() {
handle_alloc_error(layout);
}
memory.cast()
}
unsafe fn deallocate(header: *mut Header, size: usize) {
count_object(-1);
dealloc(header.cast(), Layout::from_size_align_unchecked(size, WORD.max(8)));
}
unsafe fn children(o: Obj) -> [&'static [Obj]; 2] {
let one = |objects: &'static [Obj]| [objects, &[]];
match ptr_tag(o) {
tag if tag <= MAX_CTOR_TAG => one(std::slice::from_raw_parts(ctor_fields(o), (*o.0).other as usize)),
TAG_CLOSURE => {
let closure = o.0.cast::<Closure>();
one(std::slice::from_raw_parts(closure_args(o), (*closure).num_fixed as usize))
}
TAG_ARRAY => one(crate::array::elements(o)),
TAG_MAP => crate::map::children(o),
_ => one(&[]),
}
}
pub unsafe fn free_object(o: Obj) {
if is_scalar(o) {
return;
}
match ptr_tag(o) {
tag if tag <= MAX_CTOR_TAG => deallocate(o.0, (*o.0).size as usize),
TAG_CLOSURE => {
let closure = o.0.cast::<Closure>();
deallocate(o.0, closure_size((*closure).num_fixed as usize));
}
TAG_ARRAY => crate::array::free(o),
TAG_SARRAY => crate::sarray::free(o),
TAG_STRING => crate::string::free(o),
TAG_MPZ => crate::nat::free_big(o),
TAG_MAP => crate::map::free(o),
tag => unreachable!("inlean: object of unknown kind {tag}"),
}
}
unsafe fn free(o: Obj) {
let mut pending: Vec<Obj> = Vec::new();
let mut current = o;
loop {
for &child in children(current).into_iter().flatten() {
if is_scalar(child) {
continue;
}
let count = rc(child);
if count.get() > 1 {
count.set(count.get() - 1);
} else if count.get() == 1 {
pending.push(child);
}
}
free_object(current);
match pending.pop() {
Some(next) => current = next,
None => return,
}
}
}
pub unsafe fn mark_persistent(o: Obj) {
let mut pending = vec![o];
while let Some(current) = pending.pop() {
if is_scalar(current) || rc(current).get() == 0 {
continue;
}
rc(current).set(0);
for run in children(current) {
pending.extend_from_slice(run);
}
}
}
#[inline(always)]
unsafe fn ctor_fields(o: Obj) -> *mut Obj {
o.0.cast::<u8>().add(HEADER).cast()
}
pub unsafe fn alloc_ctor(tag: u32, num_objs: u32, num_usize: u32, scalar_size: u32) -> Obj {
let size = HEADER + (num_objs + num_usize) as usize * WORD + scalar_size as usize;
let size = size.next_multiple_of(WORD.max(8));
let header = allocate(size);
header.write(new_header(tag as u8, num_objs as u8, size as u16));
Obj(header)
}
#[inline(always)]
pub unsafe fn ctor_get(o: Obj, i: u32) -> Obj {
*ctor_fields(o).add(i as usize)
}
#[inline(always)]
pub unsafe fn ctor_set(o: Obj, i: u32, value: Obj) {
*ctor_fields(o).add(i as usize) = value;
}
#[inline(always)]
pub unsafe fn ctor_set_tag(o: Obj, tag: u32) {
(*o.0).tag = tag as u8;
}
#[inline(always)]
pub unsafe fn ctor_release(o: Obj, i: u32) {
let field = ctor_fields(o).add(i as usize);
dec(*field);
*field = box_(0);
}
pub unsafe fn reset(o: Obj, num_objs: u32) -> Obj {
if is_exclusive(o) {
for i in 0..num_objs {
ctor_release(o, i);
}
o
} else {
dec_ref(o);
box_(0)
}
}
pub unsafe fn reuse(memory: Obj, tag: u32, num_objs: u32, num_usize: u32, scalar_size: u32, update_tag: bool) -> Obj {
if is_scalar(memory) {
alloc_ctor(tag, num_objs, num_usize, scalar_size)
} else {
if update_tag {
ctor_set_tag(memory, tag);
}
memory
}
}
#[inline(always)]
pub unsafe fn ctor_get_usize(o: Obj, slot: u32) -> usize {
ctor_fields(o).add(slot as usize).cast::<usize>().read()
}
#[inline(always)]
pub unsafe fn ctor_set_usize(o: Obj, slot: u32, value: usize) {
ctor_fields(o).add(slot as usize).cast::<usize>().write(value);
}
macro_rules! ctor_scalars {
($($get:ident $set:ident $ty:ty),*) => {$(
#[inline(always)]
pub unsafe fn $get(o: Obj, slots: u32, offset: u32) -> $ty {
ctor_fields(o).cast::<u8>().add(slots as usize * WORD + offset as usize).cast::<$ty>().read_unaligned()
}
#[inline(always)]
pub unsafe fn $set(o: Obj, slots: u32, offset: u32, value: $ty) {
ctor_fields(o).cast::<u8>().add(slots as usize * WORD + offset as usize).cast::<$ty>().write_unaligned(value);
}
)*};
}
ctor_scalars!(
ctor_get_uint8 ctor_set_uint8 u8,
ctor_get_uint16 ctor_set_uint16 u16,
ctor_get_uint32 ctor_set_uint32 u32,
ctor_get_uint64 ctor_set_uint64 u64,
ctor_get_float ctor_set_float f64,
ctor_get_float32 ctor_set_float32 f32
);
#[inline(always)]
pub unsafe fn box_uint32(value: u32) -> Obj {
if WORD == 4 {
let o = alloc_ctor(0, 0, 0, 4);
ctor_set_uint32(o, 0, 0, value);
o
} else {
box_(value as usize)
}
}
#[inline(always)]
pub unsafe fn unbox_uint32(o: Obj) -> u32 {
if WORD == 4 {
ctor_get_uint32(o, 0, 0)
} else {
unbox(o) as u32
}
}
pub unsafe fn box_uint64(value: u64) -> Obj {
let o = alloc_ctor(0, 0, 0, 8);
ctor_set_uint64(o, 0, 0, value);
o
}
#[inline(always)]
pub unsafe fn unbox_uint64(o: Obj) -> u64 {
ctor_get_uint64(o, 0, 0)
}
pub unsafe fn box_usize(value: usize) -> Obj {
let o = alloc_ctor(0, 0, 1, 0);
ctor_set_usize(o, 0, value);
o
}
#[inline(always)]
pub unsafe fn unbox_usize(o: Obj) -> usize {
ctor_get_usize(o, 0)
}
pub unsafe fn box_float(value: f64) -> Obj {
let o = alloc_ctor(0, 0, 0, 8);
ctor_set_float(o, 0, 0, value);
o
}
#[inline(always)]
pub unsafe fn unbox_float(o: Obj) -> f64 {
ctor_get_float(o, 0, 0)
}
pub unsafe fn box_float32(value: f32) -> Obj {
let o = alloc_ctor(0, 0, 0, 4);
ctor_set_float32(o, 0, 0, value);
o
}
#[inline(always)]
pub unsafe fn unbox_float32(o: Obj) -> f32 {
ctor_get_float32(o, 0, 0)
}
#[repr(C)]
struct Closure {
header: Header,
function: *const (),
arity: u16,
num_fixed: u16,
}
fn closure_size(num_fixed: usize) -> usize {
size_of::<Closure>() + num_fixed * WORD
}
#[inline(always)]
unsafe fn closure_args(o: Obj) -> *mut Obj {
o.0.cast::<u8>().add(size_of::<Closure>()).cast()
}
pub unsafe fn alloc_closure(function: *const (), arity: u32, num_fixed: u32) -> Obj {
let closure = allocate(closure_size(num_fixed as usize)).cast::<Closure>();
closure.write(Closure {
header: new_header(TAG_CLOSURE, 0, 0),
function,
arity: arity as u16,
num_fixed: num_fixed as u16,
});
Obj(closure.cast())
}
#[inline(always)]
pub unsafe fn closure_set(o: Obj, i: u32, value: Obj) {
*closure_args(o).add(i as usize) = value;
}
unsafe fn call(function: *const (), args: &[Obj]) -> Obj {
use std::mem::transmute as cast;
type O = Obj;
let a = args;
match a.len() {
1 => cast::<_, unsafe fn(O) -> O>(function)(a[0]),
2 => cast::<_, unsafe fn(O, O) -> O>(function)(a[0], a[1]),
3 => cast::<_, unsafe fn(O, O, O) -> O>(function)(a[0], a[1], a[2]),
4 => cast::<_, unsafe fn(O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3]),
5 => cast::<_, unsafe fn(O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4]),
6 => cast::<_, unsafe fn(O, O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4], a[5]),
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]),
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]),
9 => cast::<_, unsafe fn(O, 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], a[8],
),
10 => cast::<_, unsafe fn(O, O, 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], a[8], a[9],
),
11 => cast::<_, unsafe fn(O, O, O, 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], a[8], a[9], a[10],
),
12 => cast::<_, unsafe fn(O, O, O, O, 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], a[8], a[9], a[10], a[11],
),
13 => cast::<_, unsafe fn(O, O, O, O, O, 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], a[8], a[9], a[10], a[11], a[12],
),
14 => cast::<_, unsafe fn(O, O, O, O, O, O, 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], a[8], a[9], a[10], a[11], a[12], a[13],
),
15 => cast::<_, unsafe fn(O, O, O, O, O, O, O, 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], a[8], a[9], a[10], a[11], a[12], a[13], a[14],
),
16 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, 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], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15],
),
n => panic!("inlean: a function of {n} arguments cannot be called through a closure"),
}
}
pub unsafe fn apply(f: Obj, args: &[Obj]) -> Obj {
let closure = f.0.cast::<Closure>();
let (function, arity, fixed) = ((*closure).function, (*closure).arity as usize, (*closure).num_fixed as usize);
let stored = std::slice::from_raw_parts(closure_args(f), fixed);
if fixed + args.len() < arity {
let extended = alloc_closure(function, arity as u32, (fixed + args.len()) as u32);
for (i, &arg) in stored.iter().chain(args).enumerate() {
closure_set(extended, i as u32, arg);
}
take_stored(f, stored);
return extended;
}
let (now, later) = args.split_at(arity - fixed);
let mut all = [box_(0); CLOSURE_MAX_ARGS];
assert!(arity <= CLOSURE_MAX_ARGS, "inlean: a function of {arity} arguments cannot be called through a closure");
all[..fixed].copy_from_slice(stored);
all[fixed..arity].copy_from_slice(now);
take_stored(f, stored);
let result = call(function, &all[..arity]);
if later.is_empty() {
result
} else {
apply(result, later)
}
}
unsafe fn take_stored(f: Obj, stored: &[Obj]) {
if is_exclusive(f) {
free_object(f);
} else {
for &arg in stored {
inc(arg);
}
dec_ref(f);
}
}
pub struct Constant(OnceLock<Shared>);
struct Shared(Obj);
unsafe impl Send for Shared {}
unsafe impl Sync for Shared {}
impl Constant {
#[allow(clippy::new_without_default)]
pub const fn new() -> Constant {
Constant(OnceLock::new())
}
pub unsafe fn get(&self, init: unsafe fn() -> Obj) -> Obj {
self.0
.get_or_init(|| {
let value = init();
mark_persistent(value);
Shared(value)
})
.0
}
}