use std::cmp::Ordering;
use std::collections::VecDeque;
use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::sync::Arc;
use std::sync::Mutex;
use delegate::delegate;
use merc_sharedmutex::RecursiveLockReadGuard;
use merc_unsafety::ProtectionIndex;
use merc_unsafety::ProtectionSet;
use merc_unsafety::StablePointer;
use merc_utilities::MercError;
use merc_utilities::PhantomUnsend;
use crate::ATermIntRef;
use crate::ATermList;
use crate::Markable;
use crate::Symb;
use crate::SymbolRef;
use crate::Transmutable;
use crate::is_empty_list_term;
use crate::is_int_term;
use crate::is_list_term;
use crate::storage::GlobalTermPool;
use crate::storage::Marker;
use crate::storage::SharedTerm;
use crate::storage::THREAD_TERM_POOL;
pub trait Term<'a, 'b> {
fn protect(&self) -> ATerm;
fn arg(&'b self, index: usize) -> ATermRef<'a>;
fn arguments(&'b self) -> ATermArgs<'a>;
fn copy(&'b self) -> ATermRef<'a>;
fn borrow(&self) -> ATermRef<'_>;
fn get_head_symbol(&'b self) -> SymbolRef<'a>;
fn iter(&'b self) -> TermIterator<'a>;
fn index(&self) -> usize;
fn shared(&self) -> &ATermIndex;
}
pub type ATermIndex = StablePointer<SharedTerm>;
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ATermRef<'a> {
shared: ATermIndex,
marker: PhantomData<&'a ()>,
}
#[cfg(not(debug_assertions))]
const _: () = assert!(std::mem::size_of::<ATermRef>() == std::mem::size_of::<usize>());
#[cfg(not(debug_assertions))]
const _: () = assert!(std::mem::size_of::<Option<ATermRef>>() == std::mem::size_of::<usize>());
unsafe impl Send for ATermRef<'_> {}
unsafe impl Sync for ATermRef<'_> {}
impl ATermRef<'_> {
pub unsafe fn from_index(shared: &ATermIndex) -> Self {
ATermRef {
shared: unsafe { shared.copy() },
marker: PhantomData,
}
}
}
impl<'a, 'b> Term<'a, 'b> for ATermRef<'a> {
fn protect(&self) -> ATerm {
THREAD_TERM_POOL.with(|tp| tp.protect(&self.copy()))
}
fn arg(&self, index: usize) -> ATermRef<'a> {
assert!(
index < self.get_head_symbol().arity(),
"arg({index}) is not defined for term {self:?}"
);
unsafe { ATermRef::from_index(SharedTerm::argument_of(self.shared.erased(), index).shared()) }
}
fn arguments(&self) -> ATermArgs<'a> {
ATermArgs::new(self.copy())
}
fn copy(&self) -> ATermRef<'a> {
unsafe { ATermRef::from_index(self.shared()) }
}
fn borrow(&self) -> ATermRef<'_> {
self.copy()
}
fn get_head_symbol(&'b self) -> SymbolRef<'a> {
unsafe { SharedTerm::symbol_of(self.shared.erased()) }
}
fn iter(&self) -> TermIterator<'a> {
TermIterator::new(self.copy())
}
fn index(&self) -> usize {
self.shared.erased().as_ptr() as usize
}
fn shared(&self) -> &ATermIndex {
&self.shared
}
}
impl Markable for ATermRef<'_> {
fn mark(&self, marker: &mut Marker) {
marker.mark(self);
}
fn contains_term(&self, term: &ATermRef<'_>) -> bool {
term == self
}
fn contains_symbol(&self, symbol: &SymbolRef<'_>) -> bool {
self.get_head_symbol() == *symbol
}
fn len(&self) -> usize {
1
}
}
impl fmt::Display for ATermRef<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
enum FormatFrame<'a> {
Term(ATermRef<'a>),
Str(&'static str),
}
impl fmt::Debug for ATermRef<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut stack = vec![FormatFrame::Term(self.copy())];
while let Some(frame) = stack.pop() {
match frame {
FormatFrame::Str(s) => write!(f, "{s}")?,
FormatFrame::Term(t) => {
if is_int_term(&t) {
write!(f, "{}", Into::<ATermIntRef>::into(t.copy()))?;
} else if is_list_term(&t) || is_empty_list_term(&t) {
write!(f, "{}", Into::<ATermList<ATerm>>::into(t.copy()))?;
} else if t.arguments().is_empty() {
write!(f, "{}", t.get_head_symbol().name())?;
} else {
write!(f, "{:?}(", t.get_head_symbol())?;
let args = t.arguments().rev();
let num_args = args.len();
stack.push(FormatFrame::Str(")"));
for (i, arg) in args.enumerate() {
stack.push(FormatFrame::Term(arg));
if i + 1 < num_args {
stack.push(FormatFrame::Str(", "));
}
}
}
}
}
}
Ok(())
}
}
pub struct ATerm {
term: ATermRef<'static>,
root: ProtectionIndex,
_marker: PhantomUnsend,
}
impl ATerm {
pub fn with_args<'a, 'b, S: Symb<'a, 'b>, T: Term<'a, 'b>>(
symbol: &'b S,
args: &'b [T],
) -> Return<ATermRef<'static>> {
THREAD_TERM_POOL.with(|tp| tp.create_term(symbol, args))
}
pub fn with_iter<'a, 'b, 'c, 'd, S, I, T>(symbol: &'b S, iter: I) -> ATerm
where
S: Symb<'a, 'b>,
I: IntoIterator<Item = T>,
T: Term<'c, 'd>,
{
THREAD_TERM_POOL.with(|tp| tp.create_term_iter(symbol, iter))
}
pub fn try_with_iter<'a, 'b, 'c, 'd, S, I, T>(symbol: &'b S, iter: I) -> Result<ATerm, MercError>
where
S: Symb<'a, 'b>,
I: IntoIterator<Item = Result<T, MercError>>,
T: Term<'c, 'd>,
{
THREAD_TERM_POOL.with(|tp| tp.try_create_term_iter(symbol, iter))
}
pub fn with_iter_head<'a, 'b, 'c, 'd, 'e, 'f, I, S, T, H>(symbol: &'b S, head: &'d H, iter: I) -> ATerm
where
S: Symb<'a, 'b>,
H: Term<'c, 'd>,
I: IntoIterator<Item = T>,
T: Term<'e, 'f>,
{
THREAD_TERM_POOL.with(|tp| tp.create_term_iter_head(symbol, head, iter))
}
pub fn constant<'a, 'b, S: Symb<'a, 'b>>(symbol: &'b S) -> ATerm {
THREAD_TERM_POOL.with(|tp| tp.create_constant(symbol))
}
pub fn from_string(text: &str) -> Result<ATerm, MercError> {
THREAD_TERM_POOL.with(|tp| tp.from_string(text))
}
pub fn get(&self) -> ATermRef<'_> {
self.term.copy()
}
pub fn root(&self) -> ProtectionIndex {
self.root
}
pub fn replace<'a, 'b, T>(&mut self, value: Return<T>)
where
T: Term<'a, 'b>,
'b: 'a,
{
let index = unsafe { value.shared().copy() };
let mut value = ManuallyDrop::new(value);
let guard = unsafe { ManuallyDrop::take(&mut value.guard) };
THREAD_TERM_POOL.with(|tp| tp.replace(guard, self.root, unsafe { index.copy() }));
self.term = unsafe { ATermRef::from_index(&index) };
}
pub(crate) fn from_index(term: &ATermIndex, root: ProtectionIndex) -> ATerm {
unsafe {
ATerm {
term: ATermRef::from_index(term),
root,
_marker: PhantomData,
}
}
}
}
impl<'a, 'b> Term<'a, 'b> for ATerm
where
'b: 'a,
{
delegate! {
to self.term {
fn protect(&self) -> ATerm;
fn arg(&self, index: usize) -> ATermRef<'a>;
fn arguments(&self) -> ATermArgs<'a>;
fn copy(&self) -> ATermRef<'a>;
fn borrow(&self) -> ATermRef<'_>;
fn get_head_symbol(&self) -> SymbolRef<'a>;
fn iter(&self) -> TermIterator<'a>;
fn index(&self) -> usize;
fn shared(&self) -> &ATermIndex;
}
}
}
impl Markable for ATerm {
fn mark(&self, marker: &mut Marker) {
marker.mark(&self.term);
}
fn contains_term(&self, term: &ATermRef<'_>) -> bool {
*term == self.term
}
fn contains_symbol(&self, symbol: &SymbolRef<'_>) -> bool {
self.get_head_symbol() == *symbol
}
fn len(&self) -> usize {
1
}
}
impl Drop for ATerm {
fn drop(&mut self) {
THREAD_TERM_POOL.with(|tp| tp.drop(self))
}
}
impl Clone for ATerm {
fn clone(&self) -> Self {
self.copy().protect()
}
}
impl fmt::Display for ATerm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.copy())
}
}
impl fmt::Debug for ATerm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.copy())
}
}
impl Hash for ATerm {
fn hash<H: Hasher>(&self, state: &mut H) {
self.term.hash(state)
}
}
impl PartialEq for ATerm {
fn eq(&self, other: &Self) -> bool {
self.term.eq(&other.term)
}
}
impl PartialOrd for ATerm {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ATerm {
fn cmp(&self, other: &Self) -> Ordering {
self.term.cmp(&other.term)
}
}
impl Eq for ATerm {}
pub struct ATermSend {
term: ATermRef<'static>,
root: ProtectionIndex,
protection_set: Arc<Mutex<ProtectionSet<ATermIndex>>>,
}
unsafe impl Send for ATermSend {}
unsafe impl Sync for ATermSend {}
impl ATermSend {
pub fn from(term: ATerm) -> Self {
let protection_set = THREAD_TERM_POOL.with(|tp| tp.send_term_protection_set().clone());
let term_ref: ATermRef<'static> = unsafe { ATermRef::from_index(&term.term.shared) };
let root = protection_set
.lock()
.expect("Lock poisoned!")
.protect(unsafe { term.shared().copy() });
Self {
term: term_ref,
root,
protection_set,
}
}
}
impl Drop for ATermSend {
fn drop(&mut self) {
let mut guard = match self.protection_set.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
unsafe {
guard.unprotect(self.root);
}
}
}
impl Hash for ATermSend {
fn hash<H: Hasher>(&self, state: &mut H) {
self.term.hash(state)
}
}
impl PartialEq for ATermSend {
fn eq(&self, other: &Self) -> bool {
self.term.eq(&other.term)
}
}
impl Eq for ATermSend {}
impl PartialOrd for ATermSend {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ATermSend {
fn cmp(&self, other: &Self) -> Ordering {
self.term.cmp(&other.term)
}
}
impl<'a, 'b> Term<'a, 'b> for ATermSend
where
'b: 'a,
{
delegate! {
to self.term {
fn protect(&self) -> ATerm;
fn arg(&self, index: usize) -> ATermRef<'a>;
fn arguments(&self) -> ATermArgs<'a>;
fn copy(&self) -> ATermRef<'a>;
fn borrow(&self) -> ATermRef<'_>;
fn get_head_symbol(&self) -> SymbolRef<'a>;
fn iter(&self) -> TermIterator<'a>;
fn index(&self) -> usize;
fn shared(&self) -> &ATermIndex;
}
}
}
pub struct Return<T> {
term: T,
guard: ManuallyDrop<RecursiveLockReadGuard<'static, GlobalTermPool>>,
}
impl<T> Return<T> {
pub(crate) fn new(guard: RecursiveLockReadGuard<'static, GlobalTermPool>, term: T) -> Self {
Return {
term,
guard: ManuallyDrop::new(guard),
}
}
pub fn cast<U>(self) -> Return<U>
where
T: Into<U>,
{
let mut this = ManuallyDrop::new(self);
let guard = unsafe { ManuallyDrop::take(&mut this.guard) };
let term = unsafe { std::ptr::read(&this.term) };
Return {
term: term.into(),
guard: ManuallyDrop::new(guard),
}
}
}
impl<T> Drop for Return<T> {
fn drop(&mut self) {
THREAD_TERM_POOL.with(|_| {
unsafe { ManuallyDrop::drop(&mut self.guard) };
});
}
}
impl<T: Transmutable> Return<T> {
pub fn inner(&self) -> &T::Target<'_> {
unsafe { self.term.transmute_lifetime() }
}
}
impl<'a, 'b, T: Term<'a, 'b>> Term<'a, 'b> for Return<T>
where
'b: 'a,
{
delegate! {
to self.term {
fn protect(&self) -> ATerm;
fn arg(&'b self, index: usize) -> ATermRef<'a>;
fn arguments(&'b self) -> ATermArgs<'a>;
fn copy(&'b self) -> ATermRef<'a>;
fn borrow(&self) -> ATermRef<'_>;
fn get_head_symbol(&'b self) -> SymbolRef<'a>;
fn iter(&'b self) -> TermIterator<'a>;
fn index(&self) -> usize;
fn shared(&self) -> &ATermIndex;
}
}
}
pub struct ATermArgs<'a> {
term: Option<ATermRef<'a>>,
arity: usize,
index: usize,
}
impl<'a> ATermArgs<'a> {
pub fn empty() -> ATermArgs<'static> {
ATermArgs {
term: None,
arity: 0,
index: 0,
}
}
fn new(term: ATermRef<'a>) -> ATermArgs<'a> {
let arity = term.get_head_symbol().arity();
ATermArgs {
term: Some(term),
arity,
index: 0,
}
}
pub fn is_empty(&self) -> bool {
self.arity == 0
}
}
impl<'a> Iterator for ATermArgs<'a> {
type Item = ATermRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.arity {
let res = Some(self.term.as_ref().unwrap().arg(self.index));
self.index += 1;
res
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.arity - self.index;
(remaining, Some(remaining))
}
}
impl DoubleEndedIterator for ATermArgs<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.index < self.arity {
let res = Some(self.term.as_ref().unwrap().arg(self.arity - 1));
self.arity -= 1;
res
} else {
None
}
}
}
impl ExactSizeIterator for ATermArgs<'_> {
fn len(&self) -> usize {
self.arity - self.index
}
}
pub struct TermIterator<'a> {
queue: VecDeque<ATermRef<'a>>,
}
impl TermIterator<'_> {
pub fn new(t: ATermRef) -> TermIterator {
TermIterator {
queue: VecDeque::from([t]),
}
}
}
impl<'a> Iterator for TermIterator<'a> {
type Item = ATermRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
match self.queue.pop_back() {
Some(term) => {
for argument in term.arguments().rev() {
self.queue.push_back(argument);
}
Some(term)
}
None => None,
}
}
}
impl<'a, 'b, T: Term<'a, 'b>> Term<'a, 'b> for &'b T {
fn protect(&self) -> ATerm {
(*self).protect()
}
fn arg(&self, index: usize) -> ATermRef<'a> {
(*self).arg(index)
}
fn arguments(&self) -> ATermArgs<'a> {
(*self).arguments()
}
fn copy(&self) -> ATermRef<'a> {
(*self).copy()
}
fn borrow(&self) -> ATermRef<'_> {
(*self).borrow()
}
fn get_head_symbol(&self) -> SymbolRef<'a> {
(*self).get_head_symbol()
}
fn iter(&self) -> TermIterator<'a> {
(*self).iter()
}
fn index(&self) -> usize {
(*self).index()
}
fn shared(&self) -> &ATermIndex {
(*self).shared()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use parking_lot::Mutex;
use crate::ATerm;
use crate::ATermSend;
use crate::Symbol;
use crate::Term;
use crate::storage::THREAD_TERM_POOL;
#[test]
#[should_panic(expected = "arg(1) is not defined")]
fn test_arg_out_of_bounds_panics() {
let f = Symbol::new("f_arg_oob_test", 1);
let a = ATerm::constant(&Symbol::new("a_arg_oob_test", 0));
let t = ATerm::with_args(&f, &[a.copy()]).protect();
let _ = t.arg(1);
}
#[test]
fn test_debug_multi_arg_term_argument_order() {
let f = Symbol::new("f_debug_order_test", 3);
let g = Symbol::new("g_debug_order_test", 1);
let a = ATerm::constant(&Symbol::new("a_debug_order_test", 0));
let b = ATerm::constant(&Symbol::new("b_debug_order_test", 0));
let c = ATerm::with_args(&g, &[b.copy()]).protect();
let t = ATerm::with_args(&f, &[a.copy(), b.copy(), c.copy()]).protect();
assert_eq!(
format!("{t:?}"),
"f_debug_order_test(a_debug_order_test, b_debug_order_test, g_debug_order_test(b_debug_order_test))"
);
}
#[test]
#[cfg_attr(miri, ignore)] fn test_debug_deeply_nested_term() {
let f = Symbol::new("f", 1);
let mut t = ATerm::constant(&Symbol::new("a", 0));
for _ in 0..300_000 {
t = ATerm::with_args(&f, &[t]).protect();
}
let text = format!("{t:?}");
assert!(text.starts_with("f(f("));
assert!(text.ends_with("))"));
}
#[test]
fn test_send_term_outlives_creating_thread() {
let symbol = Symbol::new("send_outlives", 0);
let term = std::thread::spawn(|| ATermSend::from(ATerm::constant(&Symbol::new("send_outlives", 0))))
.join()
.unwrap();
THREAD_TERM_POOL.with(|tp| {
tp.force_collect_garbage();
tp.force_collect_garbage();
});
assert_eq!(term.get_head_symbol(), symbol.copy());
}
#[test]
#[cfg_attr(miri, ignore)] fn test_send_terms() {
let symbol = Symbol::new("a", 0);
let term = Arc::new(Mutex::new(ATermSend::from(ATerm::constant(&symbol))));
let thread_a = {
let term = term.clone();
std::thread::spawn(move || {
let symbol = Symbol::new("a", 0);
for _ in 0..100000 {
*term.lock() = ATermSend::from(ATerm::constant(&symbol));
}
})
};
for _ in 0..100000 {
*term.lock() = ATermSend::from(ATerm::constant(&symbol));
}
thread_a.join().unwrap();
}
}