pub struct Arena { /* private fields */ }Expand description
The arena interns atoms, variables, strings, binaries, and compound terms.
An Arena owns all memory for interned data. Terms store only indices into
this arena and remain valid as long as the epoch they belong to is alive.
§Epochs
The arena is divided into epochs. Conceptually, epochs form a stack.
Allocation begins in epoch 0, which starts at offset 0 in all
underlying storages. At any time, the user can call begin_epoch().
This operation:
- Freezes the current epoch (recording its byte and term offsets).
- Starts a new active epoch for subsequent allocations.
At any point, there are K alive epochs, where:
K - 1are frozen (no new data is added),- The last one is active (all new allocations go there),
- and
K <= MAX_LIVE_EPOCHS(typically very small number, currently 8).
Terms remain valid only while the epoch they were created in is alive.
§Truncation
The arena can be truncated back to a given epoch m, where
0 <= m < MAX_LIVE_EPOCHS:
- Epoch
mand all epochs more recent thanmare erased in O(1). - Terms from those epochs become invalid.
truncate(0)erases all data (synonym:clear()).truncate(current_epoch())erases only the latest epoch
(synonym:truncate_current()).
Conceptually, epochs form a stack: you can push with begin_epoch()
and pop with truncate_current(). This makes it efficient to manage
temporary, scoped allocations. For example:
let mut arena = Arena::with_capacity(4096, 1024);
let epoch = arena.begin_epoch().unwrap();
// … build temporary terms here …
arena.truncate(epoch).unwrap(); // frees them all at onceThis is especially useful during iteration: each loop can create short-lived terms, then discard them cleanly all at once at the end.
Implementations§
Source§impl Arena
impl Arena
Sourcepub const UNIT: Term = Term::UNIT
pub const UNIT: Term = Term::UNIT
Constant representing the zero‑arity tuple (unit). Internally
this is the atom "unit" encoded as a small atom. It may
be copied freely and does not depend on any arena.
Sourcepub const NIL: Term = Term::NIL
pub const NIL: Term = Term::NIL
Constant representing the empty list (nil). Internally this is
the atom "nil" encoded as a small atom. It may be copied
freely and does not depend on any arena.
Sourcepub fn with_capacity(bytes_capacity: usize, terms_capacity: usize) -> Self
pub fn with_capacity(bytes_capacity: usize, terms_capacity: usize) -> Self
Create a new, empty arena with given capacities.
Sourcepub fn try_with_default_opers() -> Result<Self, TermError>
pub fn try_with_default_opers() -> Result<Self, TermError>
Create a new, empty arena with default operator definitions and default capacities.
Sourcepub fn stats(&self) -> ArenaStats
pub fn stats(&self) -> ArenaStats
Returns stats.
Sourcepub fn current_epoch(&self) -> EpochID
pub fn current_epoch(&self) -> EpochID
Returns current epoch.
Sourcepub fn begin_epoch(&mut self) -> Result<EpochID, TermError>
pub fn begin_epoch(&mut self) -> Result<EpochID, TermError>
Freezes current epoch and begins a new one.
Sourcepub fn clear(&mut self) -> Result<(), TermError>
pub fn clear(&mut self) -> Result<(), TermError>
Erases arena in O(1). Does not shrink the allocated capacity.
Sourcepub fn truncate_current(&mut self) -> Result<(), TermError>
pub fn truncate_current(&mut self) -> Result<(), TermError>
Epoch m and all epochs more recent than m are erased in O(1)
Does not shrink the allocated capacity.
Sourcepub fn truncate(&mut self, epoch_id: EpochID) -> Result<(), TermError>
pub fn truncate(&mut self, epoch_id: EpochID) -> Result<(), TermError>
Epoch m and all epochs more recent than m are erased in O(1)
Does not shrink the allocated capacity.
Sourcepub fn int(&mut self, i: impl Into<i64>) -> Term
pub fn int(&mut self, i: impl Into<i64>) -> Term
Construct a new integer term. The full 64 bit two’s complement
representation of i is stored in the payload. No truncation
occurs.
Sourcepub fn real(&mut self, r: impl Into<f64>) -> Term
pub fn real(&mut self, r: impl Into<f64>) -> Term
Construct a new floating point term. The full 64 bit IEEE‑754 bit pattern is stored in the payload without truncation.
Sourcepub fn date(&mut self, ms: impl Into<i64>) -> Term
pub fn date(&mut self, ms: impl Into<i64>) -> Term
Construct a new date term representing a Unix epoch in milliseconds.
Sourcepub fn atom(&mut self, name: impl AsRef<str>) -> Term
pub fn atom(&mut self, name: impl AsRef<str>) -> Term
Construct or intern an atom into the arena and produce a term referencing it. Small atom names (≤14 bytes of UTF‑8) are inlined directly into the handle; longer names are interned into the arena and referenced by index and length.
Sourcepub fn var(&mut self, name: impl AsRef<str>) -> Term
pub fn var(&mut self, name: impl AsRef<str>) -> Term
Construct or intern a variable into the arena and produce a term referencing it. Small variable names (≤14 bytes) are inlined directly into the handle; longer names are interned in the arena and referenced by index.
Sourcepub fn str(&mut self, s: impl AsRef<str>) -> Term
pub fn str(&mut self, s: impl AsRef<str>) -> Term
Construct or intern a UTF‑8 string into the arena and produce a term referencing it. Strings longer than 14 bytes are interned in the arena; shorter strings are inlined. Invalid UTF‑8 will result in an error.
Sourcepub fn bin(&mut self, bytes: impl AsRef<[u8]>) -> Term
pub fn bin(&mut self, bytes: impl AsRef<[u8]>) -> Term
Construct or intern a binary blob into the arena and produce a term referencing it. Blobs longer than 14 bytes are interned in the arena; shorter blobs are inlined.
Sourcepub fn func(
&mut self,
functor: impl AsRef<str>,
args: impl IntoIterator<Item = impl IntoTerm>,
) -> Term
pub fn func( &mut self, functor: impl AsRef<str>, args: impl IntoIterator<Item = impl IntoTerm>, ) -> Term
Construct a new compound term by interning the functor and arguments in the arena. The returned term references a slice in the arena’s term storage consisting of the functor atom as the first entry followed by the argument handles. A functor of arity zero results in an atom.
Sourcepub fn funcv(
&mut self,
terms: impl IntoIterator<Item = impl IntoTerm>,
) -> Result<Term, TermError>
pub fn funcv( &mut self, terms: impl IntoIterator<Item = impl IntoTerm>, ) -> Result<Term, TermError>
Construct a new compound term by interning the functor and its arguments into the arena as a sequence of terms (functor first, then arguments). A functor with no arguments yields the atom itself. Errors if no functor is provided or if the first term is not an atom.
Sourcepub fn list(&mut self, terms: impl IntoIterator<Item = impl IntoTerm>) -> Term
pub fn list(&mut self, terms: impl IntoIterator<Item = impl IntoTerm>) -> Term
Constructs a new list. A list is represented internally as an
array of terms. If terms is empty, returns nil.
Sourcepub fn listc(
&mut self,
terms: impl IntoIterator<Item = impl IntoTerm>,
tail: impl IntoTerm,
) -> Term
pub fn listc( &mut self, terms: impl IntoIterator<Item = impl IntoTerm>, tail: impl IntoTerm, ) -> Term
Constructs a new improper list. An improper list is represented as
a list and additional argument. If terms is empty, returns nil.
Sourcepub fn tuple(&mut self, terms: impl IntoIterator<Item = impl IntoTerm>) -> Term
pub fn tuple(&mut self, terms: impl IntoIterator<Item = impl IntoTerm>) -> Term
Constructs a new tuple. A tuple is represented internally as an array of terms.
Sourcepub fn name<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
pub fn name<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
Returns the name of a compound term, atom, or variable.
Use [unpack_atom], [unpack_func], or [unpack_var]
to ensure the term is of a specific kind.
Sourcepub fn atom_name<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
pub fn atom_name<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
Returns the name of an atom,
Sourcepub fn var_name<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
pub fn var_name<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
Returns the name of a variable.
Sourcepub fn func_name<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
pub fn func_name<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
Returns the name of a compund term.
Sourcepub fn unpack_int(&self, term: &Term) -> Result<i64, TermError>
pub fn unpack_int(&self, term: &Term) -> Result<i64, TermError>
Returns the value if term is an integer, otherwise an error.
Sourcepub fn unpack_real(&self, term: &Term) -> Result<f64, TermError>
pub fn unpack_real(&self, term: &Term) -> Result<f64, TermError>
Returns the value if term is a real, otherwise an error.
Sourcepub fn unpack_date(&self, term: &Term) -> Result<i64, TermError>
pub fn unpack_date(&self, term: &Term) -> Result<i64, TermError>
Returns the value if term is a date, otherwise an error.
Sourcepub fn unpack_str<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
pub fn unpack_str<'a>(&'a self, term: &'a Term) -> Result<&'a str, TermError>
Returns the string slice if term is a string, otherwise an error.
Sourcepub fn unpack_bin<'a>(&'a self, term: &'a Term) -> Result<&'a [u8], TermError>
pub fn unpack_bin<'a>(&'a self, term: &'a Term) -> Result<&'a [u8], TermError>
Returns the slice if term is a binary blob, otherwise an error.
Sourcepub fn unpack_atom<'a>(
&'a self,
term: &'a Term,
allowed_names: &[&str],
) -> Result<&'a str, TermError>
pub fn unpack_atom<'a>( &'a self, term: &'a Term, allowed_names: &[&str], ) -> Result<&'a str, TermError>
Returns the name if term is an atom, otherwise an error.
Sourcepub fn unpack_var<'a>(
&'a self,
term: &'a Term,
allowed_names: &[&str],
) -> Result<&'a str, TermError>
pub fn unpack_var<'a>( &'a self, term: &'a Term, allowed_names: &[&str], ) -> Result<&'a str, TermError>
Returns the name if term is a variable, otherwise an error.
Sourcepub fn unpack_func_any<'a>(
&'a self,
term: &'a Term,
allowed_names: &[&str],
) -> Result<(&'a Term, &'a [Term]), TermError>
pub fn unpack_func_any<'a>( &'a self, term: &'a Term, allowed_names: &[&str], ) -> Result<(&'a Term, &'a [Term]), TermError>
Returns the name and arguments if term is a compound term of any arity
or an atom and its name is in allowed_names (or if allowed_names is empty),
otherwise returns an error.
Sourcepub fn unpack_func<'a, const ARITY: usize>(
&'a self,
term: &'a Term,
allowed_names: &[&str],
) -> Result<(&'a Term, [Term; ARITY]), TermError>
pub fn unpack_func<'a, const ARITY: usize>( &'a self, term: &'a Term, allowed_names: &[&str], ) -> Result<(&'a Term, [Term; ARITY]), TermError>
Returns the name and arguments if term is a compound term of arity ARITY
(or an atom if ARITY == 0) and its name is in allowed_names (or if allowed_names is empty),
otherwise returns an error.
Sourcepub fn unpack_list<'a>(
&'a self,
term: &'a Term,
) -> Result<(&'a [Term], &'a Term), TermError>
pub fn unpack_list<'a>( &'a self, term: &'a Term, ) -> Result<(&'a [Term], &'a Term), TermError>
Returns the slice with list elements and the tail if term is a list,
otherwise returns an error.
Source§impl Arena
impl Arena
Sourcepub fn lookup_oper(&self, name: &str) -> Option<usize>
pub fn lookup_oper(&self, name: &str) -> Option<usize>
Sourcepub fn get_oper(&self, index: Option<usize>) -> &OperDefTab
pub fn get_oper(&self, index: Option<usize>) -> &OperDefTab
Retrieves an operator definition table by index.
Returns a reference to the corresponding OperDefTab,
or [EMPTY_OPER_DEF_TAB] if the index is None or out of bounds.
Sourcepub fn opers_len(&self) -> usize
pub fn opers_len(&self) -> usize
Returns the total number of operator entries in this registry.
Sourcepub fn define_oper(&mut self, op: Term) -> Result<(), TermError>
pub fn define_oper(&mut self, op: Term) -> Result<(), TermError>
Defines a single operator entry from a parsed [arena_terms::Term] structure.
This function ingests a Prolog-style operator definition term of the form:
op(
oper: atom | func(arg: atom | '='(name: atom, default: term)), ...,
type: 'fun' | 'prefix' | 'infix' | 'postfix',
prec: 0..1200, % must be 0 for fixity = 'fun'
assoc: 'none' | 'left' | 'right',
rename_to: 'none' | some(new_name: atom),
embed_type: 'false' | 'true'
).Each op/1 term specifies one operator, including its name, fixity, precedence,
associativity, optional renaming target, and embedding behavior.
§Parameters
arena: TheArenaproviding term access and allocation.op: TheTermdescribing the operator declaration.
§Returns
Ok(())if the operator was successfully parsed and registered.
§Errors
Returns an error if the operator definition is invalid, malformed, or violates fixity/precedence/associativity constraints.
Sourcepub fn define_opers(&mut self, term: Term) -> Result<(), TermError>
pub fn define_opers(&mut self, term: Term) -> Result<(), TermError>
Defines one or more operators from [arena_terms::Term].
This method accepts either:
- A list of operator terms (each of which is passed to [
define_oper]), or - A single operator term (
op(...)) to be defined directly.
Each term is ingested and registered according to its fixity, precedence, associativity, and optional metadata.
§Parameters
arena: TheArenaproviding term access and allocation.term: Either a list of operator definitions or a single operator term.
§Returns
Ok(())if all operator definitions were successfully processed.
§Errors
Returns an error if any individual operator definition is invalid, malformed, or violates fixity/precedence/associativity constraints.
Sourcepub fn clear_opers(&mut self)
pub fn clear_opers(&mut self)
Clears all operator definitions and compound term metadata.
Sourcepub fn normalize_term(
&mut self,
term: Term,
fixity: Fixity,
op_tab_index: Option<usize>,
) -> Result<Term, TermError>
pub fn normalize_term( &mut self, term: Term, fixity: Fixity, op_tab_index: Option<usize>, ) -> Result<Term, TermError>
Normalizes a parsed term using its operator definition.
This process transforms terms according to their declared fixity, applying named default arguments and other attributes specified in the corresponding operator definition.
§Parameters
arena: Arena used to store normalized term structures.term: The parsed term to normalize.fixity: Operator fixity (fun,prefix,infix, orpostfix).op_tab_index: Optional index into the operator definition table, if the term corresponds to a defined operator.
§Returns
A normalized Term allocated in the given arena, ready for evaluation or
further semantic analysis.
§Errors
Returns an error if normalization fails due to invalid fixity, mismatched arity, or inconsistent operator metadata.
Sourcepub fn define_default_opers(&mut self) -> Result<(), TermError>
pub fn define_default_opers(&mut self) -> Result<(), TermError>
Constructs the default operator definitions used by the TermParser.
This function populates an OperDefs table in the given Arena,
defining built-in operators such as - (prefix), ++ (infix), and = (infix),
along with their precedence and associativity rules.
[ op(-(x), prefix, 800, right, none, false),
op(++(x, y), infix, 500, left, none, false),
op(=(x, y), infix, 100, right, none, false),
op(op(f,
=(type, fun),
=(prec, 0),
=(assoc, none),
=(rename_to, none),
=(embed_type, false)),
fun, 0, none, none, false)
]The resulting definitions form the standard operator environment available to the parser when no user-defined operator table is provided.
§Parameters
arena: TheArenaused for allocating operator term structures.
§Returns
An initialized OperDefs instance containing the default operator set.