Skip to main content

Value

Enum Value 

Source
pub enum Value {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    String(Rc<NixString>),
    Path(Box<SmolStr>),
    List(Rc<NixList>),
    Attrs(Rc<NixAttrs>),
    Lambda(Rc<Closure>),
    Builtin(Box<BuiltinFn>),
    Thunk(Thunk),
}
Expand description

A Nix value — potentially lazy (may be a Thunk).

To get a guaranteed-concrete value, call .demand() which returns Concrete. The Concrete type has thunk-free accessors that the compiler enforces — you cannot accidentally skip forcing.

Variants§

§

Null

§

Bool(bool)

§

Int(i64)

§

Float(f64)

§

String(Rc<NixString>)

§

Path(Box<SmolStr>)

§

List(Rc<NixList>)

§

Attrs(Rc<NixAttrs>)

§

Lambda(Rc<Closure>)

§

Builtin(Box<BuiltinFn>)

§

Thunk(Thunk)

A lazy value (thunk) with memoization and blackhole detection.

Implementations§

Source§

impl Value

Source

pub fn demand(&self) -> Result<Concrete, EvalError>

Demand a concrete value. Forces if Thunk, returns as-is if concrete.

This is the TYPED forcing API. The returned Concrete is guaranteed non-Thunk — enforced by the Concrete enum having NO Thunk variant.

Source§

impl Value

Source

pub fn string(s: impl Into<SmolStr>) -> Self

Convenience constructor for a context-free string.

Source

pub fn list(items: Vec<Value>) -> Self

Convenience constructor that wraps a Vec<Value> in Rc for the List variant.

Source

pub fn is_uniquely_owned_list(&self) -> bool

True when self is a List whose backing Rc<Vec> is uniquely owned (refcount 1). Used by concat_lists to decide the in-place fast path.

Source

pub fn to_json(&self) -> Value

Convert a value to JSON for API output.

Source

pub fn try_to_json(&self) -> Result<Value, EvalError>

Like Self::to_json, but refuses where that one emits a placeholder.

to_json renders a lambda as the string "<lambda>", a builtin as "<builtin name>", and — worst — a thunk whose force FAILED as "<thunk:error>". All three produce valid JSON and let the caller exit 0. Measured against nix 2.31.5:

nix eval --json --expr '{ f = x: x; }'        exit 1
sui eval --json -E    '{ f = x: x; }'         exit 0  {"f":"<lambda>"}
nix eval --json --expr '{ x = throw "boom"; }' exit 1
sui eval --json -E    '{ x = throw "boom"; }'  exit 0  {"x":"<thunk:error>"}

The last one is the sharpest silent divergence in the CLI: a real evaluation error becomes a VALUE, and a consumer parsing that JSON sees a string where nix would have refused outright.

to_json itself is deliberately left alone. It is the body of builtins.toJSON, whose placeholder behaviour is load-bearing for the existing corpus, and changing it would be a language-semantics change rather than a CLI fix. This variant is for OUTPUT BOUNDARIES — where a human or a script reads the result and an exit code is the contract.

§Errors

A function, a builtin, or a thunk whose force fails. The force error is propagated verbatim so the operator sees the throw’s own message rather than a generic refusal.

Source

pub fn to_json_with_context( &self, ctx: &mut StringContext, ) -> Result<Value, EvalError>

Like [to_json] but threads string context into ctx. Used by __structuredAttrs derivation-env building: a derivation value serializes to its outPath (a store-path string) and its drv reference must flow into the derivation’s inputDrvs; a bare path is copy-to-store coerced. (to_json drops context, which is fine for builtins.toJSON but not for building a derivation’s __json.)

Source

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

Return the Nix type name for this value (e.g. "int", "set").

Source

pub fn as_bool(&self) -> Result<bool, EvalError>

Extract a bool, forcing thunks if needed.

Source

pub fn as_int(&self) -> Result<i64, EvalError>

Extract an integer, forcing thunks if needed.

Source

pub fn as_string(&self) -> Result<&str, EvalError>

Borrow the string content without forcing thunks.

Source

pub fn as_nix_string(&self) -> Result<&NixString, EvalError>

Return a reference to the full NixString (with context).

Source

pub fn to_str(&self) -> Result<String, EvalError>

Force-aware string extraction. Returns an owned String by forcing thunks if needed. Use this instead of as_string() when you may be operating on thunked attrset values.

Source

pub fn to_nix_string(&self) -> Result<NixString, EvalError>

Force-aware NixString extraction. Returns an owned NixString (with context) by forcing thunks if needed.

Source

pub fn as_attrs(&self) -> Result<&NixAttrs, EvalError>

Borrow the inner attrs without forcing. If the value is a thunk, the caller should have force_value’d it first; we return an error rather than silently mutating the thunk (which would require &mut self).

Most call sites should use to_attrs() (which forces and clones) unless they’re certain the value is already concrete and want to avoid the clone.

Source

pub fn as_list(&self) -> Result<&[Value], EvalError>

Borrow the list content without forcing thunks.

Source

pub fn to_attrs(&self) -> Result<NixAttrs, EvalError>

Force-aware attrs extraction. Forces the value if it is a thunk.

Source

pub fn to_list(&self) -> Result<Vec<Value>, EvalError>

Force-aware list extraction. Forces the value if it is a thunk.

Source

pub fn coerce_to_path(&self, context: &str) -> Result<String, EvalError>

Extract a filesystem path from a Path or String value.

Many builtins (readFile, import, pathExists, etc.) accept either Path or String arguments. This method centralises that coercion so every call-site doesn’t repeat the same match.

Source

pub fn coerce_to_realized_path( &self, context: &str, ) -> Result<String, EvalError>

Coerce to a filesystem path AND, if this value is a derivation whose output is not yet materialized on disk, realize that output first (import-from-derivation).

Used by the disk-read builtins (import, readFile, readDir, pathExists, builtins.path) so a read under a derivation’s outPath triggers a build/substitute of that output, exactly as cppnix does.

Semantics:

  • A Path/String coerces as usual — no realize (nothing to build).
  • A derivation attrset (type == "derivation" with drvPath + outPath) whose outPath (after input-source materialization) does not exist on disk invokes the realize hook with (drvPath, outPath). On success the returned path is the (now-present) outPath.
  • A non-derivation attrset with outPath coerces via outPath as usual (no drv to realize).
  • If no realize hook is installed, this degrades to coerce_to_path (the read that follows will ENOENT — a real error, never a wrong value).

The realize hook mutates no value the evaluator observes; it only makes the bytes at the already-byte-correct outPath present on disk (see crate::realize).

Source

pub fn to_float(&self) -> Result<f64, EvalError>

Coerce a numeric value to float.

Source

pub fn coerce_to_string(&self) -> Result<(String, StringContext), EvalError>

Coerce this value to a string following CppNix semantics.

This is the single source of truth for string coercion used by string interpolation, builtins.toString, and derivation env var construction.

Rules (in order):

  • String → its content (with context)
  • Path → path string (adds Plain context element)
  • Int → decimal representation
  • Float → decimal representation
  • Bool → “1” for true, “” for false
  • Null → “”
  • Attrs with __toString → call __toString(self) and coerce result
  • Attrs with outPath → coerce outPath recursively
  • List → space-joined coerced elements
  • Lambda/Builtin/Thunk → error
Source

pub fn coerce_to_string_copy_to_store( &self, ) -> Result<(String, StringContext), EvalError>

Coerce to string in CppNix copy-to-store mode — the coercion used by string interpolation ("${./foo}") and derivation-attribute population. A source path that isn’t already in the store is absolutized, canonicalized, required to exist, and NAR-copied into /nix/store/<hash>-<basename>; the result string is that store path and it carries store-path context. This is what makes src = ./. reference the correct store path (and thus the correct drv hash) instead of a raw filesystem path. builtins.toString keeps the plain mode ([coerce_to_string]) — it does not copy.

Trait Implementations§

Source§

impl Clone for Value

Source§

fn clone(&self) -> Value

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

Source§

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

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

impl Default for Value

Source§

fn default() -> Value

Returns the “default value” for a type. Read more
Source§

impl Display for Value

Source§

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

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

impl From<&Value> for Value

Source§

fn from(json: &Value) -> Self

Converts to this type from the input type.
Source§

impl From<&Value> for Value

Source§

fn from(v: &Value) -> Self

Converts to this type from the input type.
Source§

impl From<Concrete> for Value

Source§

fn from(c: Concrete) -> Value

Converts to this type from the input type.
Source§

impl From<NixAttrs> for Value

Source§

fn from(attrs: NixAttrs) -> Self

Converts to this type from the input type.
Source§

impl From<NixString> for Value

Source§

fn from(s: NixString) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<Value>> for Value

Source§

fn from(list: Vec<Value>) -> 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<f64> for Value

Source§

fn from(f: f64) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Value

Source§

fn from(n: i64) -> Self

Converts to this type from the input type.
Source§

impl FromIterator<Value> for NixList

Source§

fn from_iter<I: IntoIterator<Item = Value>>(iter: I) -> Self

Creates a value from an iterator. 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 !Send for Value

§

impl !Sync for Value

§

impl !UnwindSafe for Value

§

impl Freeze 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> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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> ToSmolStr for T
where T: Display + ?Sized,

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more