use std::cell::UnsafeCell;
use std::fmt;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Instant;
use log::debug;
use rustc_hash::FxHashMap;
use rustc_hash::FxHashSet;
use merc_io::LargeFormatter;
use merc_sharedmutex::GlobalBfSharedMutex;
use merc_sharedmutex::RecursiveLockReadGuard;
use merc_unsafety::ProtectionSet;
use merc_unsafety::StablePointer;
use merc_utilities::debug_trace;
use crate::ATermIndex;
use crate::ATermRef;
use crate::Markable;
use crate::Symb;
use crate::Symbol;
use crate::SymbolIndex;
use crate::SymbolRef;
use crate::Term;
use crate::storage::ATermStorage;
use crate::storage::SharedTerm;
use crate::storage::SymbolPool;
pub(crate) static GLOBAL_TERM_POOL: LazyLock<GlobalBfSharedMutex<GlobalTermPool>> =
LazyLock::new(|| GlobalBfSharedMutex::new(GlobalTermPool::new()));
pub(crate) const AGGRESSIVE_GC: bool = false;
pub(crate) const GC_BUDGET_CHUNK: usize = 4096;
pub(crate) type GlobalTermPoolGuard<'a> = RecursiveLockReadGuard<'a, GlobalTermPool>;
pub(crate) type SendContainerProtectionSet = Arc<Mutex<ProtectionSet<Arc<dyn Markable + Sync + Send>>>>;
pub(crate) struct GlobalTermPool {
terms: ATermStorage,
symbol_pool: SymbolPool,
thread_pools: ThreadPoolList,
send_term_protection_sets: Vec<Option<Arc<Mutex<ProtectionSet<ATermIndex>>>>>,
send_container_protection_sets: Vec<Option<SendContainerProtectionSet>>,
orphan_term_protection_set: FxHashSet<ATermIndex>,
orphan_symbol_protection_set: FxHashSet<SymbolIndex>,
orphan_container_protection_set: FxHashMap<usize, Arc<dyn Markable + Sync + Send>>,
stack: Vec<ATermIndex>,
garbage_collection: bool,
gc_budget: AtomicUsize,
int_symbol: SymbolRef<'static>,
empty_list_symbol: SymbolRef<'static>,
list_symbol: SymbolRef<'static>,
}
impl GlobalTermPool {
fn new() -> GlobalTermPool {
let mut symbol_pool = SymbolPool::new();
let int_symbol = unsafe { SymbolRef::from_index(&symbol_pool.create_reserved("<aterm_int>", 0)) };
let list_symbol = unsafe { SymbolRef::from_index(&symbol_pool.create("<list_constructor>", 2)) };
let empty_list_symbol = unsafe { SymbolRef::from_index(&symbol_pool.create("<empty_list>", 0)) };
let pool = GlobalTermPool {
terms: ATermStorage::new(),
symbol_pool,
thread_pools: ThreadPoolList(Vec::new()),
send_term_protection_sets: Vec::new(),
send_container_protection_sets: Vec::new(),
orphan_term_protection_set: FxHashSet::default(),
orphan_symbol_protection_set: FxHashSet::default(),
orphan_container_protection_set: FxHashMap::default(),
stack: Vec::new(),
garbage_collection: true,
gc_budget: AtomicUsize::new(0),
int_symbol,
list_symbol,
empty_list_symbol,
};
pool.reset_gc_budget();
pool
}
pub fn len(&self) -> usize {
self.terms.len()
}
#[allow(dead_code)]
pub(crate) fn is_empty(&self) -> bool {
self.len() == 0
}
pub(crate) fn create_int(&self, value: usize) -> (StablePointer<SharedTerm>, bool) {
let (index, inserted) = unsafe {
self.terms
.insert_int_term(SymbolRef::from_index(self.int_symbol.shared()), value)
};
(index, inserted)
}
pub(crate) fn create_term_array<'a, 'b, 'c, S: Symb<'a, 'b>>(
&'c self,
symbol: &'b S,
args: &'c [ATermRef<'c>],
) -> (StablePointer<SharedTerm>, bool) {
self.terms.insert(symbol, args)
}
pub(crate) fn create_term_fixed<'a, 'b, 'c, 'd, S, T>(
&self,
symbol: &'b S,
args: &[T],
) -> (StablePointer<SharedTerm>, bool)
where
S: Symb<'a, 'b>,
T: Term<'c, 'd>,
{
self.terms.insert_fixed(symbol, args)
}
pub(crate) fn create_term_fixed_iter<'a, 'b, S, I>(
&self,
symbol: &'b S,
args: I,
) -> (StablePointer<SharedTerm>, bool)
where
S: Symb<'a, 'b>,
I: Iterator<Item = ATermIndex>,
{
self.terms.insert_fixed_iter(symbol, args)
}
pub(crate) fn create_symbol<P>(&self, name: &str, arity: usize, protect: P) -> Symbol
where
P: FnOnce(SymbolIndex) -> Symbol,
{
protect(self.symbol_pool.create(name, arity))
}
pub(crate) fn create_unused_symbol<P>(&self, name: &str, arity: usize, protect: P) -> Option<Symbol>
where
P: FnOnce(SymbolIndex) -> Symbol,
{
self.symbol_pool.create_unused(name, arity).map(protect)
}
#[allow(clippy::arc_with_non_send_sync)]
#[allow(clippy::type_complexity)]
pub(crate) fn register_thread_term_pool(
&mut self,
) -> (
Arc<UnsafeCell<SharedTermProtection>>,
Arc<Mutex<ProtectionSet<ATermIndex>>>,
SendContainerProtectionSet,
) {
let protection = Arc::new(UnsafeCell::new(SharedTermProtection {
term_protection_set: ProtectionSet::new(),
symbol_protection_set: ProtectionSet::new(),
container_protection_set: ProtectionSet::new(),
index: self.thread_pools.len(),
}));
debug!("Registered thread_local protection set(s) {}", self.thread_pools.len());
self.thread_pools.push(Some(protection.clone()));
let send_term_protection_set = Arc::new(Mutex::new(ProtectionSet::new()));
self.send_term_protection_sets
.push(Some(send_term_protection_set.clone()));
let send_container_protection_set = Arc::new(Mutex::new(ProtectionSet::new()));
self.send_container_protection_sets
.push(Some(send_container_protection_set.clone()));
(protection, send_term_protection_set, send_container_protection_set)
}
pub(crate) fn deregister_thread_pool(&mut self, index: usize) {
debug!("Removed thread_local protection set(s) {index}");
if let Some(entry) = self.thread_pools.get_mut(index) {
*entry = None;
}
}
pub(crate) fn protect_orphan_roots(&mut self, protection: &SharedTermProtection) {
for (_root, term) in protection.term_protection_set.iter() {
self.orphan_term_protection_set.insert(unsafe { term.copy() });
}
for (_root, symbol) in protection.symbol_protection_set.iter() {
self.orphan_symbol_protection_set.insert(unsafe { symbol.copy() });
}
for (_root, container) in protection.container_protection_set.iter() {
let key = Arc::as_ptr(container) as *const () as usize;
self.orphan_container_protection_set
.entry(key)
.or_insert_with(|| container.clone());
}
}
pub(crate) fn trigger_garbage_collection(&mut self) {
if self.garbage_collection {
self.collect_garbage();
}
self.reset_gc_budget();
}
pub(crate) fn reset_gc_budget(&self) {
let budget = if AGGRESSIVE_GC {
1
} else {
self.terms.capacity().saturating_sub(self.len()).max(1)
};
self.gc_budget.store(budget, Ordering::Relaxed);
}
pub(crate) fn consume_gc_budget(&self, amount: usize) -> usize {
#[allow(deprecated)] self.gc_budget
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
Some(current.saturating_sub(amount))
})
.expect("the update closure always returns Some")
}
pub fn automatic_garbage_collection(&mut self, enabled: bool) {
self.garbage_collection = enabled;
}
pub fn collect_garbage(&mut self) {
let mark_time = Instant::now();
self.mark_roots();
let mark_time_elapsed = mark_time.elapsed();
let collect_time = Instant::now();
let (removed_terms, removed_symbols) = self.sweep_terms_and_symbols();
debug!(
"Garbage collection: marking took {}ms, collection took {}ms, {} terms and {} symbols removed",
mark_time_elapsed.as_millis(),
collect_time.elapsed().as_millis(),
removed_terms,
removed_symbols
);
debug!("{}", self.metrics());
for pool in self.thread_pools.iter().flatten() {
let pool = unsafe { &mut *pool.get() };
debug!("{}", pool.metrics());
}
self.stack.clear();
}
fn mark_roots(&mut self) {
let mut marker = Marker { stack: &mut self.stack };
marker.mark_symbol(&self.int_symbol);
marker.mark_symbol(&self.list_symbol);
marker.mark_symbol(&self.empty_list_symbol);
for pool in self.thread_pools.iter().flatten() {
let pool = unsafe { &mut *pool.get() };
for (_root, symbol) in pool.symbol_protection_set.iter() {
debug_trace!("Marking root {_root} symbol {symbol:?}");
unsafe { symbol.deref() }.mark();
}
for (_root, term) in pool.term_protection_set.iter() {
debug_trace!("Marking root {_root} term {term:?}");
unsafe {
ATermRef::from_index(term).mark(&mut marker);
}
}
for (_, container) in pool.container_protection_set.iter() {
container.mark(&mut marker);
}
}
for pool in self.send_term_protection_sets.iter().flatten() {
let pool = pool.lock().expect("Lock poisoned!");
for (_root, term) in pool.iter() {
debug_trace!("Marking sendable term {term:?}");
unsafe {
ATermRef::from_index(term).mark(&mut marker);
}
}
}
for pool in self.send_container_protection_sets.iter().flatten() {
let pool = pool.lock().expect("Lock poisoned!");
for (_, container) in pool.iter() {
debug_trace!("Marking sendable container");
container.mark(&mut marker);
}
}
for term in &self.orphan_term_protection_set {
debug_trace!("Marking orphaned term {term:?}");
unsafe {
ATermRef::from_index(term).mark(&mut marker);
}
}
for symbol in &self.orphan_symbol_protection_set {
debug_trace!("Marking orphaned symbol {symbol:?}");
unsafe { symbol.deref() }.mark();
}
for container in self.orphan_container_protection_set.values() {
debug_trace!("Marking orphaned container");
container.mark(&mut marker);
}
for slot in self.send_term_protection_sets.iter_mut() {
if slot.as_ref().is_some_and(|set| Arc::strong_count(set) == 1) {
*slot = None;
}
}
for slot in self.send_container_protection_sets.iter_mut() {
if slot.as_ref().is_some_and(|set| Arc::strong_count(set) == 1) {
*slot = None;
}
}
}
fn sweep_terms_and_symbols(&mut self) -> (usize, usize) {
let num_of_terms = self.len();
let num_of_symbols = self.symbol_pool.len();
unsafe {
self.terms.retain(|term| {
let shared = term.deref();
if !shared.is_marked() {
debug_trace!("Dropping term: {:?}", term);
return false;
}
shared.unmark();
true
});
}
unsafe {
self.symbol_pool.retain(|symbol| {
let shared = symbol.deref();
if !shared.is_marked() {
debug_trace!("Dropping symbol: {:?}", symbol);
return false;
}
shared.unmark();
true
});
}
(num_of_terms - self.len(), num_of_symbols - self.symbol_pool.len())
}
pub fn metrics(&self) -> TermPoolMetrics<'_> {
TermPoolMetrics(self)
}
pub(crate) fn get_int_symbol(&self) -> &SymbolRef<'static> {
&self.int_symbol
}
pub(crate) fn get_list_symbol(&self) -> &SymbolRef<'static> {
&self.list_symbol
}
pub(crate) fn get_empty_list_symbol(&self) -> &SymbolRef<'static> {
&self.empty_list_symbol
}
}
pub(crate) struct TermPoolMetrics<'a>(&'a GlobalTermPool);
impl fmt::Display for TermPoolMetrics<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"There are {} terms, and {} symbols",
self.0.terms.len(),
self.0.symbol_pool.len()
)
}
}
struct ThreadPoolList(Vec<Option<Arc<UnsafeCell<SharedTermProtection>>>>);
unsafe impl Sync for ThreadPoolList {}
unsafe impl Send for ThreadPoolList {}
impl std::ops::Deref for ThreadPoolList {
type Target = Vec<Option<Arc<UnsafeCell<SharedTermProtection>>>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for ThreadPoolList {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub(crate) struct SharedTermProtection {
pub term_protection_set: ProtectionSet<ATermIndex>,
pub symbol_protection_set: ProtectionSet<SymbolIndex>,
pub container_protection_set: ProtectionSet<Arc<dyn Markable + Sync + Send>>,
pub index: usize,
}
impl SharedTermProtection {
pub fn metrics(&self) -> ProtectionMetrics<'_> {
ProtectionMetrics(self)
}
}
pub(crate) struct ProtectionMetrics<'a>(&'a SharedTermProtection);
impl fmt::Display for ProtectionMetrics<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(
f,
"Protection set {} has {} roots, max {} and {} insertions",
self.0.index,
LargeFormatter(self.0.term_protection_set.len()),
LargeFormatter(self.0.term_protection_set.maximum_size()),
LargeFormatter(self.0.term_protection_set.number_of_insertions())
)?;
writeln!(
f,
"Containers: {} roots, max {} and {} insertions",
LargeFormatter(self.0.container_protection_set.len()),
LargeFormatter(self.0.container_protection_set.maximum_size()),
LargeFormatter(self.0.container_protection_set.number_of_insertions()),
)?;
write!(
f,
"Symbols: {} roots, max {} and {} insertions",
LargeFormatter(self.0.symbol_protection_set.len()),
LargeFormatter(self.0.symbol_protection_set.maximum_size()),
LargeFormatter(self.0.symbol_protection_set.number_of_insertions()),
)
}
}
pub struct Marker<'a> {
stack: &'a mut Vec<ATermIndex>,
}
impl Marker<'_> {
pub fn mark(&mut self, term: &ATermRef<'_>) {
unsafe {
if term.shared().deref().mark() {
self.stack.push(term.shared().copy());
while let Some(term) = self.stack.pop() {
let shared = term.deref();
shared.symbol().shared().deref().mark();
for arg in shared.arguments().iter() {
if arg.shared().deref().mark() {
self.stack.push(arg.shared().copy());
}
}
}
}
}
}
pub fn mark_symbol(&mut self, symbol: &SymbolRef<'_>) {
unsafe { symbol.shared().deref() }.mark();
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use merc_utilities::random_test;
use crate::ATerm;
use crate::Symb;
use crate::Symbol;
use crate::Term;
use crate::random_term;
use crate::storage::THREAD_TERM_POOL;
#[test]
#[cfg_attr(miri, ignore)]
fn test_maximal_sharing() {
random_test(100, |rng| {
let mut terms = HashMap::new();
for _ in 0..1000 {
let term = random_term(rng, &[("f".into(), 2), ("g".into(), 1)], &["a".to_string()], 10);
let representation = format!("{}", term);
if let Some(entry) = terms.get(&representation) {
assert_eq!(term, *entry, "There is another term with the same representation");
} else {
terms.insert(representation, term);
}
}
});
}
#[test]
fn test_symbol_reachable_through_term_survives_collection() {
let term = {
let f = Symbol::new("only_reachable_through_term", 1);
ATerm::with_args(&f, &[ATerm::constant(&Symbol::new("a", 0))]).protect()
};
THREAD_TERM_POOL.with(|tp| tp.force_collect_garbage());
THREAD_TERM_POOL.with(|tp| tp.force_collect_garbage());
let head = term.get_head_symbol();
assert_eq!(head.name(), "only_reachable_through_term");
assert_eq!(head.arity(), 1, "the mark must not leak into the arity");
assert_eq!(head, Symbol::new("only_reachable_through_term", 1).copy());
}
#[test]
#[should_panic]
fn test_term_out_of_bound_arity() {
let c = ATerm::constant(&Symbol::new("a", 0));
let t = ATerm::with_args(&Symbol::new("f", 1), &[c.copy(), c.copy()]);
let _ = t.arg(1);
}
}