Expand description
§Overview
A thread-safe library to manipulate first-order terms. A first-order term is defined by the following grammar:
t := c | f(t1, ..., tn) | u64where f is a function symbol with arity n > 0 and a name, c is a function
symbol with arity zero and u64 is a numerical term. As such f(a, g(b)) is an
example of a term with constants a and b. However, in practice we can also
represent expressions such as 5 + 7 * 3 > 2 as terms or even computations such
as sort([3, 1, 2]), using appropriate function symbols for list concatenation
and the integers. These expressions are then typically manipulated by a term rewrite
engine, such as the one provided in merc_sabre.
Terms are stored maximally shared in the global aterm pool, meaning that two terms are structurally equivalent if and only if they have the same memory address. This allows for very efficient equality checking and compact memory usage.
Terms are immutable, but can be accessed concurrently in different threads. They are periodically garbage collected when they are no longer reachable. This is ensured by thread-local protection sets that keep track of reachable terms. Note that the name stands for Annotated terms, but this is only a leftover from the history, as of today terms can no longer be annotated with additional information.
§Usage
The main trait of the library is the Term trait, which is implemented by every
struct that behaves as a first-order term, and can be used to generically deal
with terms. The Symb trait does the same for function symbols.
The main implementations of this trait are the ATerm and ATermRef structs,
which represent owned and borrowed terms respectively. The ATermRef struct
carries a lifetime to ensure that borrowed terms are not used after they are no
longer protected, and as such avoid use-after-free errors.
In general terms can simply be created by using their constructors:
use merc_aterm::{ATerm, Term, Symbol, Symb};
let a = ATerm::constant(&Symbol::new("a", 0));
let f = ATerm::with_args(&Symbol::new("f", 2), &[a.clone(), a]); // Creates f(a, a)
let g = ATerm::from_string("f(a, g(b))").unwrap(); // Parses the term from a string
assert!(g.arg(0).get_head_symbol().name() == "a"); // Access first argument of g§Details
The crate is heavily optimised for performance, avoiding unnecessary allocations
for looking up terms that already exist, and avoiding protections when possible,
by using the ATermRef struct and the Return struct to cheaply return terms
without taking ownership. Furthermore, the Protected struct can be used to
cheaply store many terms in a single protection, for example by using
Protected<Vec<ATermRef<'static>>> to store a vector of terms.
The crate also provides serialization of terms to the same binary format that is
used in the mCRL2 toolset (implemented in the aterm_binary_stream module),
allowing compact storage of terms.
§Macros
The merc_derive_terms proc macro can be used to generate the necessary boilerplate
code for structs to behave as aterms with additional structure. This is
heavily used in the merc_data crate, but also in the term library to define
lists and integers. The macro must be added to a module that contains the
definitions for the underlying data types for which the boilerplate code should
be generated, as shown in the example below:
use merc_macros::merc_derive_terms;
use merc_aterm::ATerm;
use merc_aterm::Term;
use merc_aterm::Symbol;
#[merc_derive_terms]
mod inner {
// Normally this can be `use super::*`, but that does not seem to work in doctests.
use merc_aterm::ATerm;
use merc_aterm::Term;
use merc_macros::merc_term;
use merc_macros::merc_ignore;
use delegate::delegate;
// These imports are used by the macro, but we cannot use the $crate trick since the macro is used
// within the crate that defines these types.
use merc_aterm::ATermRef;
use merc_aterm::ATermArgs;
use merc_aterm::ATermIndex;
use merc_aterm::TermIterator;
use merc_aterm::Symbol;
use merc_aterm::SymbolRef;
use merc_aterm::Markable;
use merc_aterm::storage::Marker;
use merc_aterm::Transmutable;
// Uses the Term trait to specify a predicate for terms that are data expressions
#[merc_ignore]
fn is_data_expression<'a, 'b, T: Term<'a, 'b>>(term: &'b T) -> bool {
true
}
#[merc_term(is_data_expression)]
pub struct DataExpression {
term: ATerm, // Must contain exactly one ATerm field
}
impl DataExpression {
#[merc_ignore] // Ignore this method for code generation
pub fn with_sort(expr: ATerm, sort: ATerm) -> Self {
Self {
term: ATerm::with_args(&Symbol::new("DataExpr", 2), &[expr, sort.into()]).protect(),
}
}
// Custom methods can be added here
}
}
use inner::DataExpression;
use inner::DataExpressionRef;
// Here we can now use the generated code:
let expr = DataExpression::with_sort(ATerm::constant(&Symbol::new("42", 0)), ATerm::constant(&Symbol::new("42", 0)));
let expr_ref: DataExpressionRef = expr.copy();§Safety
This crate does use unsafe for some of the more intricate parts of the
library, but every module that only uses safe Rust is marked with
#![forbid(unsafe_code)]. This crate is a full reimplementation of the ATerm
library used in the mCRL2 toolset.
Misuse of GcMutex, used by the Protected struct, can lead to undefined
behaviour in safe code. Ensure that the guards returned from GcMutex are not
used after the THREAD_TERM_POOL is dropped, which happens when the thread
terminates. The same applies to the Return<T> struct, which also holds a
reference to the thread local term pool. Alternatively, we could have required
access to THREAD_TERM_POOL to only be called through the closures, but this
would have made the API more cumbersome to use.
Furthermore, the protect and protect_symbol methods of Protected must be
used in a way that the resulting term or symbol is inserted into the container,
otherwise undefined behaviour may occur after garbage collection. This is
checked in debug mode, but the checks are far too expensive to be performed in
release mode.
Reading the value() of an ATermInt that is not actually a valid integer term
leads to undefined behaviour. This is also only checked in debug mode.
§Changelog
§2.0.0
Removed the ahash, arbitrary, arbtest, and rayon dependencies since
their use was only minimal. Fixed a bug where garbage collection of terms was
not triggered properly.
Reduced the size of terms by introducing fixed-size storages for small terms,
and moving annotations to only the ATermInt type. Furthermore, use a block
allocator to avoid the overhead of many small allocations for terms. Garbage
collection is now triggered properly and no longer leads to subtle bugs, and
some unsound implementation of Return<T> has been removed.
§Related work
Further details on the implementation are explained in the following paper:
Jan Friso Groote, Kevin H.J. Jilissen, Maurice Laveaux, Flip van Spaendonck. Using the Parallel ATerm Library for Parallel Model Checking and State Space Generation. A Journey from Process Algebra via Timed Automata to Model Learning. DOI.
The initial ATerm library was presented by the following article:
M.G.J. van den Brand, H.A. de Jong, P. Klint, P.A. Olivier. Efficient annotated terms. Software: Practice and Experience. DOI.
§Authors
This crate was heavily inspired by the original ATerm library, and many ideas from the original authors.
§Minimum Supported Rust Version
We do not maintain an official minimum supported rust version (MSRV), and it may be upgraded at any time when necessary.
§License
All MERC crates are licensed under the BSL-1.0 license. See the LICENSE file in the repository root for more information.
Modules§
- storage
- Implementation of the
crate::ATermrelated data structure.
Structs§
- ATerm
- The protected version of ATermRef, mostly derived from it.
- ATerm
Args - An iterator over the arguments of a term.
- ATerm
Int - This is a wrapper around the ATerm type that stores a single
u64using an annotation. - ATerm
IntRef - ATerm
List - Represents a list of ATerms of type T.
- ATerm
List Iter - The iterator over the elements of an ATermList.
- ATerm
Read Iter - A read iterator for ATerms from a binary aterm input stream.
- ATerm
Ref - This represents a lifetime bound reference to an existing ATerm.
- ATerm
Send - A sendable variant of an
ATerm. - ATerm
String - ATerm
String Ref - ArgStack
- This struct defines a local argument stack on the global stack.
- BinaryA
Term Reader - The reader counterpart of BinaryATermWriter, which reads ATerms from a binary aterm input stream.
- BinaryA
Term Writer - Writes terms in a streamable binary aterm format to an output stream.
- Protected
- A container of objects, typically either terms or objects containing terms,
that implement Markable. These store ATermRef
<'static>values that are protected during garbage collection by being in the container itself. - Protected
Read Guard - Protected
Write Guard - Return
- This is a wrapper around a term that indicates it is being returned from a function.
- Symbol
- A protected function symbol, with the same interface as SymbolRef.
- Symbol
Ref - A reference to a function symbol in the symbol pool.
- Term
Builder - This can be used to construct an ATerm from a given input of (inductive) type I without using recursion, as such avoiding system stack overflows. See TermBuilder::evaluate for more details.
- Term
Iterator - An iterator over all subterms of the given ATerm in preorder traversal, i.e., for f(g(a), b) we visit f(g(a), b), g(a), a, b.
- Term
Parser
Enums§
Traits§
- ATerm
Read - Trait for reading ATerms from a stream.
- ATerm
Streamable - Trait for objects that can be written to and read from an ATerm stream.
- ATerm
Write - Trait for writing ATerms to a stream.
- Markable
- This trait should be used on all objects and containers related to storing unprotected terms, or unprotected symbols.
- Symb
- The public interface for a function symbol. Can be used to write generic functions that accept both Symbol and SymbolRef.
- Term
- The ATerm trait represents a first-order term in the ATerm library. It provides methods to manipulate and access the term’s properties.
- Transmutable
Functions§
- apply
- Applies the given function to every subterm of the given term using the TermBuilder. function(subterm) returns: None , in which case subterm is kept and it is recursed into its arguments. Some(x), in which case subterm is replaced by x.
- is_
empty_ list_ term - Returns true iff the term is an empty ATermList.
- is_
int_ symbol - Returns true if the given symbol is the special integer symbol used by ATermInt.
- is_
int_ term - Returns true if the term is an ATermInt term.
- is_
list_ term - Returns true iff the term is a ATermList list term.
- random_
term - Create a random term consisting of the given symbol and constants. Performs iterations number of constructions, and uses chance_duplicates to choose the amount of subterms that are duplicated.
Type Aliases§
- ATerm
Index - Type alias for ATerm indices, representing a stable pointer to a SharedTerm in the term pool.
- Symbol
Index - An alias for the type that is used to reference into the SharedSymbol set.