use std::alloc::Layout;
use std::alloc::LayoutError;
use std::fmt;
use std::hash::Hash;
use std::mem::offset_of;
use std::ptr::NonNull;
use std::ptr::slice_from_raw_parts_mut;
use equivalent::Equivalent;
use merc_unsafety::Erasable;
use merc_unsafety::ErasedPtr;
use merc_unsafety::SliceDst;
use merc_unsafety::StablePointer;
use merc_unsafety::repr_c;
use merc_utilities::AtomicTaggedPtr;
use crate::ATermRef;
use crate::Symb;
use crate::SymbolRef;
use crate::Term;
use crate::Transmutable;
use crate::storage::SymbolHeader;
#[repr(C)]
pub struct SharedTerm {
symbol: TermSymbol,
arguments: [ATermRef<'static>],
}
#[repr(C)]
pub(crate) struct TermSymbol {
ptr: AtomicTaggedPtr<SymbolHeader>,
#[cfg(debug_assertions)]
reference: SymbolRef<'static>,
}
impl TermSymbol {
pub(crate) fn new(symbol: &SymbolRef<'_>) -> Self {
Self {
ptr: AtomicTaggedPtr::new(symbol.shared().erased().cast()),
#[cfg(debug_assertions)]
reference: unsafe { SymbolRef::from_index(symbol.shared()) },
}
}
pub(crate) fn get(&self) -> SymbolRef<'_> {
let ptr: ErasedPtr = unsafe { NonNull::new_unchecked(self.ptr.load()) }.cast();
#[cfg(debug_assertions)]
let index = unsafe { StablePointer::from_related_erased(ptr, self.reference.shared()) };
#[cfg(not(debug_assertions))]
let index = unsafe { StablePointer::from_erased(ptr) };
unsafe { SymbolRef::from_index(&index) }
}
pub(crate) fn mark(&self) -> bool {
!self.ptr.set_tag()
}
pub(crate) fn is_marked(&self) -> bool {
self.ptr.is_tagged()
}
pub(crate) fn unmark(&self) {
self.ptr.clear_tag()
}
}
impl PartialEq for TermSymbol {
fn eq(&self, other: &Self) -> bool {
self.ptr.load() == other.ptr.load()
}
}
impl Eq for TermSymbol {}
impl Hash for TermSymbol {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.get().hash(state);
}
}
impl fmt::Debug for TermSymbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.get())
}
}
impl PartialEq for SharedTerm {
fn eq(&self, other: &Self) -> bool {
self.symbol == other.symbol && self.arguments == other.arguments
}
}
impl Eq for SharedTerm {}
unsafe impl SliceDst for SharedTerm {
fn layout_for(len: usize) -> Result<Layout, LayoutError> {
let header_layout = Layout::new::<TermSymbol>();
let slice_layout = Layout::array::<ATermRef<'static>>(len)?;
repr_c(&[header_layout, slice_layout])
}
fn retype(ptr: std::ptr::NonNull<[()]>) -> NonNull<Self> {
unsafe { NonNull::new_unchecked(ptr.as_ptr() as *mut _) }
}
fn length(&self) -> usize {
self.symbol().arity()
}
}
unsafe impl Erasable for SharedTerm {
fn erase(this: NonNull<Self>) -> ErasedPtr {
this.cast()
}
unsafe fn unerase(this: ErasedPtr) -> NonNull<Self> {
unsafe {
let len = (*this.as_ptr().cast::<TermSymbol>()).get().arity();
let raw = NonNull::new_unchecked(slice_from_raw_parts_mut(this.as_ptr().cast(), len));
Self::retype(raw)
}
}
}
impl fmt::Debug for SharedTerm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"SharedTerm {{ symbol: {:?}, arguments: {:?} }}",
self.symbol,
self.arguments()
)
}
}
const ARGUMENTS_OFFSET: usize = size_of::<TermSymbol>().next_multiple_of(align_of::<ATermRef<'static>>());
impl SharedTerm {
pub(crate) unsafe fn symbol_of<'a>(ptr: ErasedPtr) -> SymbolRef<'a> {
unsafe { ptr.cast::<TermSymbol>().as_ref() }.get()
}
pub(crate) unsafe fn argument_of<'a>(ptr: ErasedPtr, index: usize) -> &'a ATermRef<'static> {
unsafe {
ptr.byte_add(ARGUMENTS_OFFSET)
.cast::<ATermRef<'static>>()
.add(index)
.as_ref()
}
}
pub fn symbol(&self) -> SymbolRef<'_> {
self.symbol.get()
}
pub(crate) fn mark(&self) -> bool {
self.symbol.mark()
}
pub(crate) fn is_marked(&self) -> bool {
self.symbol.is_marked()
}
pub(crate) fn unmark(&self) {
self.symbol.unmark()
}
pub fn arguments(&self) -> &[ATermRef<'_>] {
unsafe { self.arguments.transmute_lifetime() }
}
pub fn index(&self) -> usize {
self as *const Self as *const u8 as usize
}
pub(crate) fn length_for(object: &SharedTermLookup) -> usize {
object.arguments.len()
}
pub(crate) unsafe fn construct(ptr: *mut SharedTerm, object: &SharedTermLookup) {
unsafe {
ptr.cast::<TermSymbol>().write(TermSymbol::new(&object.symbol));
for (index, argument) in object.arguments.iter().enumerate() {
ptr.byte_add(ARGUMENTS_OFFSET)
.cast::<ATermRef<'static>>()
.add(index)
.write(ATermRef::from_index(argument.shared()));
}
}
}
}
impl Hash for SharedTerm {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.symbol.hash(state);
self.arguments.hash(state);
}
}
pub(crate) struct SharedTermLookup<'a> {
pub(crate) symbol: SymbolRef<'a>,
pub(crate) arguments: &'a [ATermRef<'a>],
}
impl Equivalent<SharedTerm> for SharedTermLookup<'_> {
fn equivalent(&self, other: &SharedTerm) -> bool {
self.symbol == other.symbol() && self.arguments == &other.arguments
}
}
impl Hash for SharedTermLookup<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.symbol.hash(state);
self.arguments.hash(state);
}
}
const _: () = assert!(offset_of!(SharedTerm, symbol) == 0);
#[cfg(test)]
mod tests {
use allocator_api2::alloc::Global;
use merc_unsafety::AllocatorDst;
#[cfg(not(debug_assertions))]
use merc_unsafety::SliceDst;
use crate::ATerm;
use crate::Symbol;
use crate::Term;
use crate::storage::SharedTerm;
use crate::storage::SharedTermLookup;
#[test]
#[cfg(not(debug_assertions))]
fn test_shared_symbol_size() {
assert_eq!(
SharedTerm::layout_for(0)
.expect("The layout should not overflow")
.size(),
1 * std::mem::size_of::<usize>(),
"A SharedTerm without arguments should be the same size as the Symbol"
);
assert_eq!(
SharedTerm::layout_for(2)
.expect("The layout should not overflow")
.size(),
3 * std::mem::size_of::<usize>(),
"A SharedTerm with arity two should be the same size as the Symbol and two ATermRef arguments"
);
}
#[test]
fn test_shared_term_lookup() {
let symbol = Symbol::new("a", 2);
let term = ATerm::constant(&Symbol::new("b", 0));
let lookup = SharedTermLookup {
symbol: symbol.copy(),
arguments: &[term.copy(), term.copy()],
};
let ptr = Global.allocate_slice_dst(2).expect("Could not allocate slice dst");
unsafe {
SharedTerm::construct(ptr.as_ptr(), &lookup);
assert_eq!(
ptr.as_ref().symbol(),
symbol.copy(),
"The symbol should match the lookup symbol"
);
assert_eq!(
ptr.as_ref().arguments()[0],
term.copy(),
"The arguments should match the lookup arguments"
);
assert_eq!(
ptr.as_ref().arguments()[1],
term.copy(),
"The arguments should match the lookup arguments"
);
}
Global.deallocate_slice_dst(ptr, 2);
}
#[test]
fn test_shared_term_header_access() {
let a = ATerm::constant(&Symbol::new("a", 0));
let b = ATerm::constant(&Symbol::new("b", 0));
let term = ATerm::with_args(&Symbol::new("f", 2), &[a.copy(), b.copy()]).protect();
let ptr = term.shared().erased();
let shared = unsafe { term.shared().deref() };
unsafe {
assert_eq!(SharedTerm::symbol_of(ptr), shared.symbol());
for (index, argument) in shared.arguments().iter().enumerate() {
assert!(
std::ptr::eq(SharedTerm::argument_of(ptr, index), argument),
"The argument offset should match the layout of the term"
);
}
}
}
}