Skip to main content

Value

Enum Value 

Source
pub enum Value {
    Bool(bool),
    Int(i64),
    BigInt(Arc<BigInt>),
    Str(Atom),
    Model(Atom),
    Set(Set),
    Fcn(Fcn),
}
Expand description

A TLA+ value.

Integers built through Value::int are canonical: Value::Int for every value in i64 range and Value::BigInt only outside it. Equality, ordering, hashing and fingerprints are numeric even for a hand-built BigInt that fits in an i64. Functions are canonical by domain (see Fcn). Sets may be enumerated or lazy (see Set); equality and hashing look through the representation.

Variants§

§

Bool(bool)

TRUE or FALSE.

§

Int(i64)

An integer in i64 range.

§

BigInt(Arc<BigInt>)

An integer outside i64 range (big-integer mode only).

§

Str(Atom)

A string.

§

Model(Atom)

A model value: untyped, or typed when named x_name (TLC’s rule).

§

Set(Set)

A set.

§

Fcn(Fcn)

A function, including tuples, sequences and records.

Implementations§

Source§

impl Value

Source

pub fn flat_cache_heap_bytes( &self, names: &Interner, proceed: &mut dyn FnMut() -> bool, ) -> Option<usize>

Requested heap payload retained by a narrow immutable conversion cache.

Admits only booleans, inline integers and flat tuples/records containing those values. The caller separately charges its table capacity, including inline Value/Atom owners. Record name payload is shared only when its Arc is already pinned by names; foreign owners and all other shapes decline. Includes private function headers (and fixed fingerprint cache) and boxed element/field storage. Opaque Arc headers and allocator overhead are not measured; this is not a whole-process memory allowance. proceed checks work before each component; false declines caching.

use dive_value::{Ctx, Interner, Value};
let names = Interner::new();
let record = Value::record(vec![(names.intern("x"), Value::Int(1))], Ctx::dive())?;
assert!(record.flat_cache_heap_bytes(&names, &mut || true).is_some());
assert_eq!(record.flat_cache_heap_bytes(&names, &mut || false), None);
Source

pub fn closed_function_cache_heap_bytes( &self, names: &Interner, proceed: &mut dyn FnMut() -> bool, ) -> Option<usize>

Conservative requested payload for a closed function-tree read cache.

Admits Bool/Int, strings pinned by this exact names interner, and recursively closed tuples, records and functions. General function keys must be Bool/Int or run-owned strings. All sets (including normalized sets), model values, big integers and other shapes decline without evaluation or normalization. Function literal classes remain unchanged.

Counts each occurrence, conservatively overcharging shared children. Includes function headers, boxed arrays, general-domain headers and the maximum future scalar-domain TLC-order array. Scalar keys cannot create the allocating product-domain index. Fingerprint and scalar lookup caches are fixed header fields and have no normalization-history side effects. The caller separately charges its table and row array. Opaque Arc headers and allocator overhead remain excluded; this is not a process memory cap. Inspection checks proceed at each step and declines after 4,096 values or 64 function levels. Declining only bypasses caching.

use dive_value::{Ctx, Interner, Value};
let names = Interner::new();
let nested = Value::fcn(vec![(Value::Int(0),
    Value::tuple(vec![Value::string(&names, "tok")]))], Ctx::tlc())?;
assert!(nested.closed_function_cache_heap_bytes(&names, &mut || true).is_some());
Source

pub fn closed_cache_heap_bytes( &self, names: &Interner, proceed: &mut dyn FnMut() -> bool, ) -> Option<usize>

Requested payload for immutable closed function/set conversion reuse.

Extends Self::closed_function_cache_heap_bytes to already materialized enumerated sets, recursively retaining the same leaf/key restrictions, name ownership, 4,096-value and 64-level bounds. No set is normalized or enumerated: raw and symbolic representations decline even if they have cached elements. Set headers and complete element arrays are charged, including repeated shared children. Fixed set hash/fingerprint fields cannot introduce further retained arrays. Declining bypasses reuse only; the caller’s conversion and control requirements are unchanged.

use dive_value::{Ctx, Interner, Value};
let names = Interner::new();
let set = Value::set(vec![Value::tuple(vec![Value::Int(1)])], Ctx::dive())?;
assert!(set.closed_cache_heap_bytes(&names, &mut || true).is_some());
assert_eq!(Value::nat(Ctx::dive()).closed_cache_heap_bytes(&names, &mut || true), None);
Source§

impl Value

Source

pub fn validate_names(&self, names: &Interner) -> Result<(), NameError>

Checks every stored string, model value and record-field name against names, including symbolic set components. Text and token must both match. This iterative walk does not intern names, normalize or enumerate sets, or invoke callbacks; it accepts any stored nesting depth.

use dive_value::{Interner, NameError, Value};
let names = Interner::new();
let owned = Value::string(&names, "a");
assert_eq!(owned.validate_names(&names), Ok(()));
let foreign = Interner::new();
foreign.intern("padding");
let wrong_token = Value::string(&foreign, "a");
assert_eq!(wrong_token.validate_names(&names), Err(NameError::ForeignAtom));
§Errors

A foreign name token or an opaque deferred set. Even a deferred set with cached elements is refused because its source may contain names the cache does not expose.

Source

pub fn validate_names_in( &self, names: &Interner, order: ValueOrder, ) -> Result<(), NameError>

Self::validate_names, and also checks that every stored set, record and non-tuple function is sorted in order: a value built under another run’s order would be read in the wrong order by operations that rely on normalization (CHOOSE, enumeration, merging).

use dive_value::{Ctx, Interner, NameError, Value};
let names = Interner::new();
let set = Value::set(vec![Value::string(&names, "a")], Ctx::dive()).expect("set");
assert_eq!(set.validate_names_in(&names, Ctx::dive().order), Ok(()));
assert_eq!(
    set.validate_names_in(&names, Ctx::tlc().order),
    Err(NameError::ForeignOrder)
);
§Errors

As Self::validate_names, or a value sorted in another order.

Source§

impl Value

Source

pub fn cmp_with(&self, other: &Self, order: ValueOrder) -> Ordering

A total order on all values, under the name order order.

It extends TLC’s partial order (Value.compareTo in tlc2.value.impl): wherever TLC compares two values without error the two agree, and where TLC raises an error this order falls back to a fixed ranking of kinds:

  1. model values (by name),
  2. booleans (FALSE < TRUE),
  3. integers (numerically),
  4. strings (by name),
  5. finite sets (by cardinality, then element by element in normalized order),
  6. functions, including tuples and records (by domain size, then domain element by element, then values element by element),
  7. infinite, unenumerable or very large sets (Nat < Int < STRING < Seq(S), then by definition).

Names (rules 1 and 4, and record fields) are ordered by ValueOrder. Consistent with ==: a.cmp_with(b, o) == Equal iff a == b.

Source§

impl Value

Source

pub fn cmp_distinct_set( elems: &[&Value], other: &Value, order: ValueOrder, ) -> Option<Ordering>

The order Value::cmp_with gives the set of elems, built raw, against other, computed without building or sorting that set: its elements are selected in order only up to the first difference. None when other is not a finite enumerated set, so that the caller must build the set and compare it in full.

The caller must guarantee that elems are pairwise distinct and mutually comparable (Value::elements_comparable), as the image of a normalized set under an injective map that preserves comparability is.

use dive_value::{Ctx, Value};
let ctx = Ctx::default();
let (one, two, three) = (Value::Int(1), Value::Int(2), Value::Int(3));
let other = Value::set_raw(vec![one.clone(), three.clone()], ctx);
let full = Value::set_raw(vec![two.clone(), one.clone()], ctx).cmp_with(&other, ctx.order);
assert_eq!(Value::cmp_distinct_set(&[&two, &one], &other, ctx.order), Some(full));
Source

pub fn elements_comparable(elems: &[Value]) -> bool

Whether every pair of elems compares in TLC without error, so that a set of them normalizes by the total order alone.

use dive_value::Value;
assert!(Value::elements_comparable(&[Value::Int(1), Value::Int(2)]));
assert!(!Value::elements_comparable(&[Value::Int(1), Value::Bool(true)]));
Source§

impl Value

Source

pub const TRUE: Self

TRUE.

Source

pub const FALSE: Self

FALSE.

Source

pub fn int(i: Int) -> Self

An integer value from an Int, in canonical form.

Source

pub fn as_int(&self) -> Option<Int>

The integer, if this is one, in canonical form.

Source

pub const fn as_bool(&self) -> Option<bool>

The boolean, if this is one.

Source

pub const fn as_set(&self) -> Option<&Set>

The set, if this is one.

Source

pub const fn as_fcn(&self) -> Option<&Fcn>

The function, if this is one.

Source

pub fn hash64(&self) -> u64

The hash used by Hash: order-independent for sets and functions, so equal values hash equally whatever their representation (an interval and the enumerated set it equals, for example). Never changes how TLC’s operations behave: hashing an unnormalized set does not normalize it.

Source

pub fn kind_name(&self) -> &'static str

A short name of the value’s kind, for diagnostics.

Source§

impl Value

Source

pub fn string(names: &Interner, text: &str) -> Self

A string, interned in names.

Source

pub fn model(names: &Interner, name: &str) -> Self

A model value, interned in names.

Source

pub fn set(elems: Vec<Self>, ctx: Ctx) -> Result<Self>

A normalized set of elems.

Normalization applies TLC’s comparability rules: {1, "a"} is an error, with the message TLC gives (Attempted to compare string "a" with non-string:\n1). Whether an error occurs is decided exactly as TLC decides it, by TLC’s insertion sort in TLC’s name order, in both ValueOrders (with names interned in TLC’s order); the result is then sorted in ctx.order.

When elements are equal but differently represented (1..3 and {1, 2, 3}), the first one is kept, as in TLC.

§Errors

ErrorKind::Incomparable and friends, as in TLC.

Source

pub fn set_canonical(elems: Vec<Self>, ctx: Ctx) -> Result<Self>

Constructs a mathematical finite set in canonical value order.

Unlike Self::set, construction accepts mixed value shapes without reproducing TLC’s partial sorting comparisons. This does not change the semantics of direct scalar comparisons.

use dive_value::{Ctx, Value};
let ctx = Ctx::dive();
let a = Value::set_canonical(vec![Value::Int(1), Value::TRUE], ctx)?;
let b = Value::set_canonical(vec![Value::TRUE, Value::Int(1), Value::TRUE], ctx)?;
assert_eq!(a, b);
§Errors

A symbolic child whose mathematical identity is not established, including inside a singleton, nested set, function key or function value, or allocation failure.

Source

pub fn require_materialized(&self, ctx: Ctx) -> Result<()>

Requires a complete explicit finite value tree, including raw set storage.

Stored name order need not match ctx; this inspection does not sort or normalize values and never invokes a symbolic provider.

Symbolic definitions are not mathematical inequality certificates. This checks singleton/nested sets and all function keys and values without enumerating a symbolic domain.

use dive_value::{Ctx, Value};
Value::Int(1).require_materialized(Ctx::dive())?;
§Errors

An unsupported symbolic child, or temporary allocation failure.

Source

pub fn materialized_for_equality(&self, ctx: Ctx) -> Result<Self>

Produces a materialized operand for quiet extensional equality.

Explicit and deferred results are checked recursively. Symbolic operator definitions are refused rather than compared structurally. As with value equality and hashing, provider evaluation here does not invoke host control.

§Errors

Provider evaluation errors, unsupported identity, or allocation failure.

Source

pub fn materialized_identity(&self, ctx: Ctx) -> Result<Self>

Materializes explicit/deferred children for an identity-demanding operation.

Provider evaluation retains its normal controls. Symbolic operator definitions whose identity is unproved remain unsupported.

§Errors

Provider evaluation errors, unsupported identity, or allocation failure.

Source

pub fn set_controlled( elems: Vec<Self>, ctx: Ctx, proceed: &mut dyn FnMut() -> bool, ) -> Result<Self, ConstructionError>

Constructs an explicit set with cooperative normalization checkpoints.

proceed returns false to interrupt. Closed materialized values use checked comparison, sorting and fallible temporary storage. Symbolic children keep the uncontrolled constructor, whose enumeration is not yet cooperative. Final shared-value allocations retain Rust’s allocation behavior; this is not an allocation-time memory ceiling.

§Errors

The original value error, interruption, or temporary allocation failure.

use dive_value::{ConstructionError, Ctx, Value};
let result = Value::set_controlled(vec![Value::Int(1)], Ctx::tlc(), &mut || false);
assert!(matches!(result, Err(ConstructionError::Interrupted)));
Source

pub fn set_raw(elems: Vec<Self>, ctx: Ctx) -> Self

A set exactly as TLC builds a set enumeration {e1, ..., en}: unnormalized until TLC would normalize it. Membership tests scan the elements with TLC’s equality, so 1 \in {1, "a"} is TRUE while {1, "a"} = {} is an error, as in TLC.

Source

pub fn empty_set(ctx: Ctx) -> Self

The empty set.

Source

pub fn interval(lo: Int, hi: Int, ctx: Ctx) -> Self

The interval lo..hi (empty when hi < lo).

Source

pub fn subset(base: Self, ctx: Ctx) -> Self

SUBSET base.

Source

pub fn fcn_set(domain: Self, range: Self, ctx: Ctx) -> Self

[domain -> range].

Source

pub fn record_set(fields: Vec<(Atom, Self)>, ctx: Ctx) -> Result<Self>

[f1 : S1, ..., fn : Sn].

§Errors

ErrorKind::Duplicate when a field repeats.

Source

pub fn product(factors: Vec<Self>, ctx: Ctx) -> Self

S1 \X ... \X Sn (n >= 2 in TLA+ syntax; any n is accepted).

Source

pub fn nat(ctx: Ctx) -> Self

Nat.

Source

pub fn int_set(ctx: Ctx) -> Self

Int.

Source

pub fn string_set(ctx: Ctx) -> Self

STRING.

Source

pub fn seq_set(range: Self, ctx: Ctx) -> Self

Seq(range).

Source

pub fn boolean_set(ctx: Ctx) -> Self

BOOLEAN, which TLC represents as the enumerated set {FALSE, TRUE}.

Source

pub fn deferred(source: Arc<dyn DeferredSet>, ctx: Ctx) -> Self

An evaluator-driven lazy set ({x \in S : P} or {e : x \in S}).

Source

pub fn tuple(elems: Vec<Self>) -> Self

The tuple (sequence) <<e1, ..., en>> (TLC TupleValue).

Source

pub fn tuple_fcn(elems: Vec<Self>) -> Self

The function with domain 1..n mapping i to elems[i - 1], as TLC builds it from [i \in 1..n |-> e] (a FcnRcdValue, not a TupleValue; see Fcn). Equal to Value::tuple of the same elements.

Source

pub fn record(fields: Vec<(Atom, Self)>, ctx: Ctx) -> Result<Self>

The record literal [f1 |-> v1, ..., fn |-> vn] (TLC RecordValue). With no fields this is the empty function <<>>.

§Errors

ErrorKind::Duplicate when a field repeats (TLC: Field name f occurs multiple times in record.).

Source

pub fn fcn(pairs: Vec<(Self, Self)>, ctx: Ctx) -> Result<Self>

The function with the given (argument, value) pairs (TLC FcnRcdValue, as built by :>, @@ or [x \in S |-> e]), in canonical form (see Fcn). The domain is normalized with TLC’s comparability rules.

§Errors

Comparison errors from normalizing the domain, and ErrorKind::Duplicate when an argument repeats (TLC: The value\nd\noccurs multiple times in the function domain.).

Source

pub fn fcn_controlled( pairs: Vec<(Self, Self)>, ctx: Ctx, proceed: &mut dyn FnMut() -> bool, ) -> Result<Self, ConstructionError>

Constructs a function with the controls and symbolic fallback described by Self::set_controlled.

§Errors

The original domain error, interruption, or temporary allocation failure.

Source

pub fn record_controlled( fields: Vec<(Atom, Self)>, ctx: Ctx, proceed: &mut dyn FnMut() -> bool, ) -> Result<Self, ConstructionError>

Constructs a record with cooperative field sorting and fallible scratch storage. Final shared storage retains Rust’s allocation behavior.

§Errors

The original duplicate-field error, interruption, or scratch allocation failure.

Trait Implementations§

Source§

impl Clone for Value

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Value

The TLC printing of the value. Formatting never changes how TLC’s operations behave: it does not normalize unnormalized sets.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Value

Source§

impl From<Int> for Value

Source§

fn from(v: Int) -> Self

Converts to this type from the input type.
Source§

impl From<bool> for Value

Source§

fn from(b: bool) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Value

Source§

fn from(v: i64) -> Self

Converts to this type from the input type.
Source§

impl Hash for Value

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Value

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Value

§

impl !UnwindSafe for Value

§

impl Forget for Value

§

impl Freeze for Value

§

impl Move for Value

§

impl Send for Value

§

impl Sync for Value

§

impl Unpin for Value

§

impl UnsafeUnpin for Value

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.