tvix_eval/value/
mod.rs

1//! This module implements the backing representation of runtime
2//! values in the Nix language.
3use std::cmp::Ordering;
4use std::fmt::Display;
5use std::num::{NonZeroI32, NonZeroUsize};
6use std::path::PathBuf;
7use std::rc::Rc;
8use std::sync::LazyLock;
9
10use bstr::{BString, ByteVec};
11use codemap::Span;
12use lexical_core::format::CXX_LITERAL;
13use serde::Deserialize;
14
15#[cfg(feature = "arbitrary")]
16mod arbitrary;
17mod attrs;
18mod builtin;
19mod function;
20mod json;
21mod list;
22mod path;
23mod string;
24mod thunk;
25
26use crate::errors::{CatchableErrorKind, ErrorKind};
27use crate::opcode::StackIdx;
28use crate::vm::generators::{self, GenCo};
29use crate::AddContext;
30pub use attrs::NixAttrs;
31pub use builtin::{Builtin, BuiltinResult};
32pub(crate) use function::Formals;
33pub use function::{Closure, Lambda};
34pub use list::NixList;
35pub use path::canon_path;
36pub use string::{NixContext, NixContextElement, NixString};
37pub use thunk::Thunk;
38
39pub use self::thunk::ThunkSet;
40
41#[warn(variant_size_differences)]
42#[derive(Clone, Debug, Deserialize)]
43#[serde(untagged)]
44pub enum Value {
45    Null,
46    Bool(bool),
47    Integer(i64),
48    Float(f64),
49    String(NixString),
50
51    #[serde(skip)]
52    Path(Box<PathBuf>),
53    Attrs(Box<NixAttrs>),
54    List(NixList),
55
56    #[serde(skip)]
57    Closure(Rc<Closure>), // must use Rc<Closure> here in order to get proper pointer equality
58
59    #[serde(skip)]
60    Builtin(Builtin),
61
62    // Internal values that, while they technically exist at runtime,
63    // are never returned to or created directly by users.
64    #[serde(skip_deserializing)]
65    Thunk(Thunk),
66
67    // See [`compiler::compile_select_or()`] for explanation
68    #[serde(skip)]
69    AttrNotFound,
70
71    // this can only occur in Chunk::Constants and nowhere else
72    #[serde(skip)]
73    Blueprint(Rc<Lambda>),
74
75    #[serde(skip)]
76    DeferredUpvalue(StackIdx),
77    #[serde(skip)]
78    UnresolvedPath(Box<PathBuf>),
79
80    #[serde(skip)]
81    FinaliseRequest(bool),
82
83    #[serde(skip)]
84    Catchable(Box<CatchableErrorKind>),
85}
86
87impl From<CatchableErrorKind> for Value {
88    #[inline]
89    fn from(c: CatchableErrorKind) -> Value {
90        Value::Catchable(Box::new(c))
91    }
92}
93
94impl<V> From<Result<V, CatchableErrorKind>> for Value
95where
96    Value: From<V>,
97{
98    #[inline]
99    fn from(v: Result<V, CatchableErrorKind>) -> Value {
100        match v {
101            Ok(v) => v.into(),
102            Err(e) => Value::Catchable(Box::new(e)),
103        }
104    }
105}
106
107static WRITE_FLOAT_OPTIONS: LazyLock<lexical_core::WriteFloatOptions> = LazyLock::new(|| {
108    lexical_core::WriteFloatOptionsBuilder::new()
109        .trim_floats(true)
110        .round_mode(lexical_core::write_float_options::RoundMode::Round)
111        .positive_exponent_break(Some(NonZeroI32::new(5).unwrap()))
112        .max_significant_digits(Some(NonZeroUsize::new(6).unwrap()))
113        .build()
114        .unwrap()
115});
116
117// Helper macros to generate the to_*/as_* macros while accounting for
118// thunks.
119
120/// Generate an `as_*` method returning a reference to the expected
121/// type, or a type error. This only works for types that implement
122/// `Copy`, as returning a reference to an inner thunk value is not
123/// possible.
124///
125/// Generate an `as_*/to_*` accessor method that returns either the
126/// expected type, or a type error.
127macro_rules! gen_cast {
128    ( $name:ident, $type:ty, $expected:expr, $variant:pat, $result:expr ) => {
129        pub fn $name(&self) -> Result<$type, ErrorKind> {
130            match self {
131                $variant => Ok($result),
132                Value::Thunk(thunk) => Self::$name(&thunk.value()),
133                other => Err(type_error($expected, &other)),
134            }
135        }
136    };
137}
138
139/// Generate an `as_*_mut/to_*_mut` accessor method that returns either the
140/// expected type, or a type error.
141macro_rules! gen_cast_mut {
142    ( $name:ident, $type:ty, $expected:expr, $variant:ident) => {
143        pub fn $name(&mut self) -> Result<&mut $type, ErrorKind> {
144            match self {
145                Value::$variant(x) => Ok(x),
146                other => Err(type_error($expected, &other)),
147            }
148        }
149    };
150}
151
152/// Generate an `is_*` type-checking method.
153macro_rules! gen_is {
154    ( $name:ident, $variant:pat ) => {
155        pub fn $name(&self) -> bool {
156            match self {
157                $variant => true,
158                Value::Thunk(thunk) => Self::$name(&thunk.value()),
159                _ => false,
160            }
161        }
162    };
163}
164
165/// Describes what input types are allowed when coercing a `Value` to a string
166#[derive(Clone, Copy, PartialEq, Eq, Debug)]
167pub struct CoercionKind {
168    /// If false only coerce already "stringly" types like strings and paths, but
169    /// also coerce sets that have a `__toString` attribute. In Tvix, this is
170    /// usually called a weak coercion. Equivalent to passing `false` as the
171    /// `coerceMore` argument of `EvalState::coerceToString` in C++ Nix.
172    ///
173    /// If true coerce all value types included by a weak coercion, but also
174    /// coerce `null`, booleans, integers, floats and lists of coercible types.
175    /// Consequently, we call this a strong coercion. Equivalent to passing
176    /// `true` as `coerceMore` in C++ Nix.
177    pub strong: bool,
178
179    /// If `import_paths` is `true`, paths are imported into the store and their
180    /// store path is the result of the coercion (equivalent to the
181    /// `copyToStore` argument of `EvalState::coerceToString` in C++ Nix).
182    pub import_paths: bool,
183}
184
185impl From<CoercionKind> for u8 {
186    fn from(k: CoercionKind) -> u8 {
187        k.strong as u8 | ((k.import_paths as u8) << 1)
188    }
189}
190
191impl From<u8> for CoercionKind {
192    fn from(byte: u8) -> Self {
193        CoercionKind {
194            strong: byte & 0x01 != 0,
195            import_paths: byte & 0x02 != 0,
196        }
197    }
198}
199
200impl<T> From<T> for Value
201where
202    T: Into<NixString>,
203{
204    fn from(t: T) -> Self {
205        Self::String(t.into())
206    }
207}
208
209/// Controls what kind of by-pointer equality comparison is allowed.
210///
211/// See `//tvix/docs/value-pointer-equality.md` for details.
212#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
213pub enum PointerEquality {
214    /// Pointer equality not allowed at all.
215    ForbidAll,
216
217    /// Pointer equality comparisons only allowed for nested values.
218    AllowNested,
219
220    /// Pointer equality comparisons are allowed in all contexts.
221    AllowAll,
222}
223
224impl Value {
225    /// Construct a [`Value::Attrs`] from a [`NixAttrs`].
226    pub fn attrs(attrs: NixAttrs) -> Self {
227        Self::Attrs(Box::new(attrs))
228    }
229
230    /// Deeply forces a value, traversing e.g. lists and attribute sets and forcing
231    /// their contents, too.
232    ///
233    /// This is a generator function.
234    pub(super) async fn deep_force(self, co: GenCo, span: Span) -> Result<Value, ErrorKind> {
235        if let Some(v) = Self::deep_force_(self.clone(), co, span).await? {
236            Ok(v)
237        } else {
238            Ok(self)
239        }
240    }
241
242    /// Returns Some(v) or None to indicate the returned value is myself
243    async fn deep_force_(myself: Value, co: GenCo, span: Span) -> Result<Option<Value>, ErrorKind> {
244        // This is a stack of values which still remain to be forced.
245        let mut vals = vec![myself];
246
247        let mut thunk_set: ThunkSet = Default::default();
248
249        loop {
250            let v = if let Some(v) = vals.pop() {
251                v
252            } else {
253                return Ok(None);
254            };
255
256            // Get rid of any top-level thunks, and bail out of self-recursive
257            // thunks.
258            let value = if let Value::Thunk(t) = &v {
259                if !thunk_set.insert(t) {
260                    continue;
261                }
262                Thunk::force_(t.clone(), &co, span).await?
263            } else {
264                v
265            };
266
267            match value {
268                // Short-circuit on already evaluated values, or fail on internal values.
269                Value::Null
270                | Value::Bool(_)
271                | Value::Integer(_)
272                | Value::Float(_)
273                | Value::String(_)
274                | Value::Path(_)
275                | Value::Closure(_)
276                | Value::Builtin(_) => continue,
277
278                Value::List(list) => {
279                    for val in list.into_iter().rev() {
280                        vals.push(val);
281                    }
282                    continue;
283                }
284
285                Value::Attrs(attrs) => {
286                    for (_, val) in attrs.into_iter_sorted().rev() {
287                        vals.push(val);
288                    }
289                    continue;
290                }
291
292                Value::Thunk(_) => panic!("Tvix bug: force_value() returned a thunk"),
293
294                Value::Catchable(_) => return Ok(Some(value)),
295
296                Value::AttrNotFound
297                | Value::Blueprint(_)
298                | Value::DeferredUpvalue(_)
299                | Value::UnresolvedPath(_)
300                | Value::FinaliseRequest(_) => panic!(
301                    "Tvix bug: internal value left on stack: {}",
302                    value.type_of()
303                ),
304            }
305        }
306    }
307
308    pub async fn coerce_to_string(
309        self,
310        co: GenCo,
311        kind: CoercionKind,
312        span: Span,
313    ) -> Result<Value, ErrorKind> {
314        self.coerce_to_string_(&co, kind, span).await
315    }
316
317    /// Coerce a `Value` to a string. See `CoercionKind` for a rundown of what
318    /// input types are accepted under what circumstances.
319    pub async fn coerce_to_string_(
320        self,
321        co: &GenCo,
322        kind: CoercionKind,
323        span: Span,
324    ) -> Result<Value, ErrorKind> {
325        let mut result = BString::default();
326        let mut vals = vec![self];
327        // Track if we are coercing the first value of a list to correctly emit
328        // separating white spaces.
329        let mut is_list_head = None;
330        // FIXME(raitobezarius): as per https://b.tvl.fyi/issues/364
331        // we might be interested into more powerful context-related coercion kinds.
332        let mut context: NixContext = NixContext::new();
333
334        loop {
335            let value = if let Some(v) = vals.pop() {
336                v.force(co, span).await?
337            } else {
338                return Ok(Value::String(NixString::new_context_from(context, result)));
339            };
340            let coerced: Result<BString, _> = match (value, kind) {
341                // coercions that are always done
342                (Value::String(mut s), _) => {
343                    if let Some(ctx) = s.take_context() {
344                        context.extend(ctx.into_iter());
345                    }
346                    Ok((*s).into())
347                }
348
349                // TODO(sterni): Think about proper encoding handling here. This needs
350                // general consideration anyways, since one current discrepancy between
351                // C++ Nix and Tvix is that the former's strings are arbitrary byte
352                // sequences without NUL bytes, whereas Tvix only allows valid
353                // Unicode. See also b/189.
354                (
355                    Value::Path(p),
356                    CoercionKind {
357                        import_paths: true, ..
358                    },
359                ) => {
360                    let imported = generators::request_path_import(co, *p).await;
361                    // When we import a path from the evaluator, we must attach
362                    // its original path as its context.
363                    context = context.append(NixContextElement::Plain(
364                        imported.to_string_lossy().to_string(),
365                    ));
366                    Ok(imported.into_os_string().into_encoded_bytes().into())
367                }
368                (
369                    Value::Path(p),
370                    CoercionKind {
371                        import_paths: false,
372                        ..
373                    },
374                ) => Ok(p.into_os_string().into_encoded_bytes().into()),
375
376                // Attribute sets can be converted to strings if they either have an
377                // `__toString` attribute which holds a function that receives the
378                // set itself or an `outPath` attribute which should be a string.
379                // `__toString` is preferred.
380                (Value::Attrs(attrs), kind) => {
381                    if let Some(to_string) = attrs.select_str("__toString") {
382                        let callable = to_string.clone().force(co, span).await?;
383
384                        // Leave the attribute set on the stack as an argument
385                        // to the function call.
386                        generators::request_stack_push(co, Value::Attrs(attrs.clone())).await;
387
388                        // Call the callable ...
389                        let result = generators::request_call(co, callable).await;
390
391                        // Recurse on the result, as attribute set coercion
392                        // actually works recursively, e.g. you can even return
393                        // /another/ set with a __toString attr.
394                        vals.push(result);
395                        continue;
396                    } else if let Some(out_path) = attrs.select_str("outPath") {
397                        vals.push(out_path.clone());
398                        continue;
399                    } else {
400                        return Err(ErrorKind::NotCoercibleToString { from: "set", kind });
401                    }
402                }
403
404                // strong coercions
405                (Value::Null, CoercionKind { strong: true, .. })
406                | (Value::Bool(false), CoercionKind { strong: true, .. }) => Ok("".into()),
407                (Value::Bool(true), CoercionKind { strong: true, .. }) => Ok("1".into()),
408
409                (Value::Integer(i), CoercionKind { strong: true, .. }) => Ok(format!("{i}").into()),
410                (Value::Float(f), CoercionKind { strong: true, .. }) => {
411                    // contrary to normal Display, coercing a float to a string will
412                    // result in unconditional 6 decimal places
413                    Ok(format!("{f:.6}").into())
414                }
415
416                // Lists are coerced by coercing their elements and interspersing spaces
417                (Value::List(list), CoercionKind { strong: true, .. }) => {
418                    for elem in list.into_iter().rev() {
419                        vals.push(elem);
420                    }
421                    // In case we are coercing a list within a list we don't want
422                    // to touch this. Since the algorithm is nonrecursive, the
423                    // space would not have been created yet (due to continue).
424                    if is_list_head.is_none() {
425                        is_list_head = Some(true);
426                    }
427                    continue;
428                }
429
430                (Value::Thunk(_), _) => panic!("Tvix bug: force returned unforced thunk"),
431
432                val @ (Value::Closure(_), _)
433                | val @ (Value::Builtin(_), _)
434                | val @ (Value::Null, _)
435                | val @ (Value::Bool(_), _)
436                | val @ (Value::Integer(_), _)
437                | val @ (Value::Float(_), _)
438                | val @ (Value::List(_), _) => Err(ErrorKind::NotCoercibleToString {
439                    from: val.0.type_of(),
440                    kind,
441                }),
442
443                (c @ Value::Catchable(_), _) => return Ok(c),
444
445                (Value::AttrNotFound, _)
446                | (Value::Blueprint(_), _)
447                | (Value::DeferredUpvalue(_), _)
448                | (Value::UnresolvedPath(_), _)
449                | (Value::FinaliseRequest(_), _) => {
450                    panic!("tvix bug: .coerce_to_string() called on internal value")
451                }
452            };
453
454            if let Some(head) = is_list_head {
455                if !head {
456                    result.push(b' ');
457                } else {
458                    is_list_head = Some(false);
459                }
460            }
461
462            result.push_str(&coerced?);
463        }
464    }
465
466    pub(crate) async fn nix_eq_owned_genco(
467        self,
468        other: Value,
469        co: GenCo,
470        ptr_eq: PointerEquality,
471        span: Span,
472    ) -> Result<Value, ErrorKind> {
473        self.nix_eq(other, &co, ptr_eq, span).await
474    }
475
476    /// Compare two Nix values for equality, forcing nested parts of the structure
477    /// as needed.
478    ///
479    /// This comparison needs to be invoked for nested values (e.g. in lists and
480    /// attribute sets) as well, which is done by suspending and asking the VM to
481    /// perform the nested comparison.
482    ///
483    /// The `top_level` parameter controls whether this invocation is the top-level
484    /// comparison, or a nested value comparison. See
485    /// `//tvix/docs/value-pointer-equality.md`
486    pub(crate) async fn nix_eq(
487        self,
488        other: Value,
489        co: &GenCo,
490        ptr_eq: PointerEquality,
491        span: Span,
492    ) -> Result<Value, ErrorKind> {
493        // this is a stack of ((v1,v2),peq) triples to be compared;
494        // after each triple is popped off of the stack, v1 is
495        // compared to v2 using peq-mode PointerEquality
496        let mut vals = vec![((self, other), ptr_eq)];
497
498        loop {
499            let ((a, b), ptr_eq) = if let Some(abp) = vals.pop() {
500                abp
501            } else {
502                // stack is empty, so comparison has succeeded
503                return Ok(Value::Bool(true));
504            };
505            let a = match a {
506                Value::Thunk(thunk) => {
507                    // If both values are thunks, and thunk comparisons are allowed by
508                    // pointer, do that and move on.
509                    if ptr_eq == PointerEquality::AllowAll {
510                        if let Value::Thunk(t1) = &b {
511                            if t1.ptr_eq(&thunk) {
512                                continue;
513                            }
514                        }
515                    };
516
517                    Thunk::force_(thunk, co, span).await?
518                }
519
520                _ => a,
521            };
522
523            let b = b.force(co, span).await?;
524
525            debug_assert!(!matches!(a, Value::Thunk(_)));
526            debug_assert!(!matches!(b, Value::Thunk(_)));
527
528            let result = match (a, b) {
529                // Trivial comparisons
530                (c @ Value::Catchable(_), _) => return Ok(c),
531                (_, c @ Value::Catchable(_)) => return Ok(c),
532                (Value::Null, Value::Null) => true,
533                (Value::Bool(b1), Value::Bool(b2)) => b1 == b2,
534                (Value::String(s1), Value::String(s2)) => s1 == s2,
535                (Value::Path(p1), Value::Path(p2)) => p1 == p2,
536
537                // Numerical comparisons (they work between float & int)
538                (Value::Integer(i1), Value::Integer(i2)) => i1 == i2,
539                (Value::Integer(i), Value::Float(f)) => i as f64 == f,
540                (Value::Float(f1), Value::Float(f2)) => f1 == f2,
541                (Value::Float(f), Value::Integer(i)) => i as f64 == f,
542
543                // List comparisons
544                (Value::List(l1), Value::List(l2)) => {
545                    if ptr_eq >= PointerEquality::AllowNested && l1.ptr_eq(&l2) {
546                        continue;
547                    }
548
549                    if l1.len() != l2.len() {
550                        return Ok(Value::Bool(false));
551                    }
552
553                    vals.extend(l1.into_iter().rev().zip(l2.into_iter().rev()).zip(
554                        std::iter::repeat(std::cmp::max(ptr_eq, PointerEquality::AllowNested)),
555                    ));
556                    continue;
557                }
558
559                (_, Value::List(_)) | (Value::List(_), _) => return Ok(Value::Bool(false)),
560
561                // Attribute set comparisons
562                (Value::Attrs(a1), Value::Attrs(a2)) => {
563                    if ptr_eq >= PointerEquality::AllowNested && a1.ptr_eq(&a2) {
564                        continue;
565                    }
566
567                    // Special-case for derivation comparisons: If both attribute sets
568                    // have `type = derivation`, compare them by `outPath`.
569                    #[allow(clippy::single_match)] // might need more match arms later
570                    match (a1.select_str("type"), a2.select_str("type")) {
571                        (Some(v1), Some(v2)) => {
572                            let s1 = v1.clone().force(co, span).await?;
573                            if s1.is_catchable() {
574                                return Ok(s1);
575                            }
576                            let s2 = v2.clone().force(co, span).await?;
577                            if s2.is_catchable() {
578                                return Ok(s2);
579                            }
580                            let s1 = s1.to_str();
581                            let s2 = s2.to_str();
582
583                            if let (Ok(s1), Ok(s2)) = (s1, s2) {
584                                if s1 == "derivation" && s2 == "derivation" {
585                                    // TODO(tazjin): are the outPaths really required,
586                                    // or should it fall through?
587                                    let out1 = a1
588                                        .select_required("outPath")
589                                        .context("comparing derivations")?
590                                        .clone();
591
592                                    let out2 = a2
593                                        .select_required("outPath")
594                                        .context("comparing derivations")?
595                                        .clone();
596
597                                    let out1 = out1.clone().force(co, span).await?;
598                                    let out2 = out2.clone().force(co, span).await?;
599
600                                    if out1.is_catchable() {
601                                        return Ok(out1);
602                                    }
603
604                                    if out2.is_catchable() {
605                                        return Ok(out2);
606                                    }
607
608                                    let result =
609                                        out1.to_contextful_str()? == out2.to_contextful_str()?;
610                                    if !result {
611                                        return Ok(Value::Bool(false));
612                                    } else {
613                                        continue;
614                                    }
615                                }
616                            }
617                        }
618                        _ => {}
619                    };
620
621                    if a1.len() != a2.len() {
622                        return Ok(Value::Bool(false));
623                    }
624
625                    for (key, v1) in a1.into_iter() {
626                        match a2.select(&key) {
627                            None => return Ok(Value::Bool(false)),
628
629                            Some(v2) => {
630                                vals.push((
631                                    (v1, v2.clone()),
632                                    std::cmp::max(ptr_eq, PointerEquality::AllowNested),
633                                ));
634                            }
635                        }
636                    }
637
638                    continue;
639                }
640
641                (Value::Attrs(_), _) | (_, Value::Attrs(_)) => return Ok(Value::Bool(false)),
642
643                (Value::Closure(c1), Value::Closure(c2))
644                    if ptr_eq >= PointerEquality::AllowNested =>
645                {
646                    if Rc::ptr_eq(&c1, &c2) {
647                        continue;
648                    } else {
649                        return Ok(Value::Bool(false));
650                    }
651                }
652
653                // Everything else is either incomparable (e.g. internal types) or
654                // false.
655                _ => return Ok(Value::Bool(false)),
656            };
657            if !result {
658                return Ok(Value::Bool(false));
659            }
660        }
661    }
662
663    pub fn type_of(&self) -> &'static str {
664        match self {
665            Value::Null => "null",
666            Value::Bool(_) => "bool",
667            Value::Integer(_) => "int",
668            Value::Float(_) => "float",
669            Value::String(_) => "string",
670            Value::Path(_) => "path",
671            Value::Attrs(_) => "set",
672            Value::List(_) => "list",
673            Value::Closure(_) | Value::Builtin(_) => "lambda",
674
675            // Internal types. Note: These are only elaborated here
676            // because it makes debugging easier. If a user ever sees
677            // any of these strings, it's a bug.
678            Value::Thunk(_) => "internal[thunk]",
679            Value::AttrNotFound => "internal[attr_not_found]",
680            Value::Blueprint(_) => "internal[blueprint]",
681            Value::DeferredUpvalue(_) => "internal[deferred_upvalue]",
682            Value::UnresolvedPath(_) => "internal[unresolved_path]",
683            Value::FinaliseRequest(_) => "internal[finaliser_sentinel]",
684            Value::Catchable(_) => "internal[catchable]",
685        }
686    }
687
688    gen_cast!(as_bool, bool, "bool", Value::Bool(b), *b);
689    gen_cast!(as_int, i64, "int", Value::Integer(x), *x);
690    gen_cast!(as_float, f64, "float", Value::Float(x), *x);
691
692    /// Cast the current value into a **context-less** string.
693    /// If you wanted to cast it into a potentially contextful string,
694    /// you have to explicitly use `to_contextful_str`.
695    /// Contextful strings are special, they should not be obtained
696    /// everytime you want a string.
697    pub fn to_str(&self) -> Result<NixString, ErrorKind> {
698        match self {
699            Value::String(s) if !s.has_context() => Ok((*s).clone()),
700            Value::Thunk(thunk) => Self::to_str(&thunk.value()),
701            other => Err(type_error("contextless strings", other)),
702        }
703    }
704
705    gen_cast!(
706        to_contextful_str,
707        NixString,
708        "contextful string",
709        Value::String(s),
710        (*s).clone()
711    );
712    gen_cast!(to_path, Box<PathBuf>, "path", Value::Path(p), p.clone());
713    gen_cast!(to_attrs, Box<NixAttrs>, "set", Value::Attrs(a), a.clone());
714    gen_cast!(to_list, NixList, "list", Value::List(l), l.clone());
715    gen_cast!(
716        as_closure,
717        Rc<Closure>,
718        "lambda",
719        Value::Closure(c),
720        c.clone()
721    );
722
723    gen_cast_mut!(as_list_mut, NixList, "list", List);
724
725    gen_is!(is_path, Value::Path(_));
726    gen_is!(is_number, Value::Integer(_) | Value::Float(_));
727    gen_is!(is_bool, Value::Bool(_));
728    gen_is!(is_attrs, Value::Attrs(_));
729    gen_is!(is_catchable, Value::Catchable(_));
730
731    /// Returns `true` if the value is a [`Thunk`].
732    ///
733    /// [`Thunk`]: Value::Thunk
734    pub fn is_thunk(&self) -> bool {
735        matches!(self, Self::Thunk(..))
736    }
737
738    /// Compare `self` against other using (fallible) Nix ordering semantics.
739    ///
740    /// The function is intended to be used from within other generator
741    /// functions or `gen!` blocks.
742    pub async fn nix_cmp_ordering(
743        self,
744        other: Self,
745        co: GenCo,
746        span: Span,
747    ) -> Result<Result<Ordering, CatchableErrorKind>, ErrorKind> {
748        Self::nix_cmp_ordering_(self, other, co, span).await
749    }
750
751    async fn nix_cmp_ordering_(
752        myself: Self,
753        other: Self,
754        co: GenCo,
755        span: Span,
756    ) -> Result<Result<Ordering, CatchableErrorKind>, ErrorKind> {
757        // this is a stack of ((v1,v2),peq) triples to be compared;
758        // after each triple is popped off of the stack, v1 is
759        // compared to v2 using peq-mode PointerEquality
760        let mut vals = vec![((myself, other), PointerEquality::ForbidAll)];
761
762        loop {
763            let ((mut a, mut b), ptr_eq) = if let Some(abp) = vals.pop() {
764                abp
765            } else {
766                // stack is empty, so they are equal
767                return Ok(Ok(Ordering::Equal));
768            };
769            if ptr_eq == PointerEquality::AllowAll {
770                if a.clone()
771                    .nix_eq(b.clone(), &co, PointerEquality::AllowAll, span)
772                    .await?
773                    .as_bool()?
774                {
775                    continue;
776                }
777                a = a.force(&co, span).await?;
778                b = b.force(&co, span).await?;
779            }
780            let result = match (a, b) {
781                (Value::Catchable(c), _) => return Ok(Err(*c)),
782                (_, Value::Catchable(c)) => return Ok(Err(*c)),
783                // same types
784                (Value::Integer(i1), Value::Integer(i2)) => i1.cmp(&i2),
785                (Value::Float(f1), Value::Float(f2)) => f1.total_cmp(&f2),
786                (Value::String(s1), Value::String(s2)) => s1.cmp(&s2),
787                (Value::List(l1), Value::List(l2)) => {
788                    let max = l1.len().max(l2.len());
789                    for j in 0..max {
790                        let i = max - 1 - j;
791                        if i >= l2.len() {
792                            vals.push(((1.into(), 0.into()), PointerEquality::ForbidAll));
793                        } else if i >= l1.len() {
794                            vals.push(((0.into(), 1.into()), PointerEquality::ForbidAll));
795                        } else {
796                            vals.push(((l1[i].clone(), l2[i].clone()), PointerEquality::AllowAll));
797                        }
798                    }
799                    continue;
800                }
801
802                // different types
803                (Value::Integer(i1), Value::Float(f2)) => (i1 as f64).total_cmp(&f2),
804                (Value::Float(f1), Value::Integer(i2)) => f1.total_cmp(&(i2 as f64)),
805
806                // unsupported types
807                (lhs, rhs) => {
808                    return Err(ErrorKind::Incomparable {
809                        lhs: lhs.type_of(),
810                        rhs: rhs.type_of(),
811                    })
812                }
813            };
814            if result != Ordering::Equal {
815                return Ok(Ok(result));
816            }
817        }
818    }
819
820    // TODO(amjoseph): de-asyncify this (when called directly by the VM)
821    pub async fn force(self, co: &GenCo, span: Span) -> Result<Value, ErrorKind> {
822        if let Value::Thunk(thunk) = self {
823            // TODO(amjoseph): use #[tailcall::mutual]
824            return Thunk::force_(thunk, co, span).await;
825        }
826        Ok(self)
827    }
828
829    // need two flavors, because async
830    pub async fn force_owned_genco(self, co: GenCo, span: Span) -> Result<Value, ErrorKind> {
831        if let Value::Thunk(thunk) = self {
832            // TODO(amjoseph): use #[tailcall::mutual]
833            return Thunk::force_(thunk, &co, span).await;
834        }
835        Ok(self)
836    }
837
838    /// Explain a value in a human-readable way, e.g. by presenting
839    /// the docstrings of functions if present.
840    pub fn explain(&self) -> String {
841        match self {
842            Value::Null => "the 'null' value".into(),
843            Value::Bool(b) => format!("the boolean value '{b}'"),
844            Value::Integer(i) => format!("the integer '{i}'"),
845            Value::Float(f) => format!("the float '{f}'"),
846            Value::String(s) if s.has_context() => format!("the contextful string '{s}'"),
847            Value::String(s) => format!("the contextless string '{s}'"),
848            Value::Path(p) => format!("the path '{}'", p.to_string_lossy()),
849            Value::Attrs(attrs) => format!("a {}-item attribute set", attrs.len()),
850            Value::List(list) => format!("a {}-item list", list.len()),
851
852            Value::Closure(f) => {
853                if let Some(name) = &f.lambda.name {
854                    format!("the user-defined Nix function '{name}'")
855                } else {
856                    "a user-defined Nix function".to_string()
857                }
858            }
859
860            Value::Builtin(b) => {
861                let mut out = format!("the builtin function '{}'", b.name());
862                if let Some(docs) = b.documentation() {
863                    out.push_str("\n\n");
864                    out.push_str(docs);
865                }
866                out
867            }
868
869            // TODO: handle suspended thunks with a different explanation instead of panicking
870            Value::Thunk(t) => t.value().explain(),
871
872            Value::Catchable(_) => "a catchable failure".into(),
873
874            Value::AttrNotFound
875            | Value::Blueprint(_)
876            | Value::DeferredUpvalue(_)
877            | Value::UnresolvedPath(_)
878            | Value::FinaliseRequest(_) => "an internal Tvix evaluator value".into(),
879        }
880    }
881
882    /// Constructs a thunk that will be evaluated lazily at runtime. This lets
883    /// users of Tvix implement their own lazy builtins and so on.
884    pub fn suspended_native_thunk(native: Box<dyn Fn() -> Result<Value, ErrorKind>>) -> Self {
885        Value::Thunk(Thunk::new_suspended_native(native))
886    }
887}
888
889trait TotalDisplay {
890    fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result;
891}
892
893impl Display for Value {
894    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
895        self.total_fmt(f, &mut Default::default())
896    }
897}
898
899/// Emulates the C++-Nix style formatting of floats, which diverges
900/// significantly from Rust's native float formatting.
901fn total_fmt_float<F: std::fmt::Write>(num: f64, mut f: F) -> std::fmt::Result {
902    let mut buf = [b'0'; lexical_core::BUFFER_SIZE];
903    let mut s = lexical_core::write_with_options::<f64, { CXX_LITERAL }>(
904        num,
905        &mut buf,
906        &WRITE_FLOAT_OPTIONS,
907    );
908
909    // apply some postprocessing on the buffer. If scientific
910    // notation is used (we see an `e`), and the next character is
911    // a digit, add the missing `+` sign.)
912    let mut new_s = Vec::with_capacity(s.len());
913
914    if s.contains(&b'e') {
915        for (i, c) in s.iter().enumerate() {
916            // encountered `e`
917            if c == &b'e' {
918                // next character is a digit (so no negative exponent)
919                if s.len() > i && s[i + 1].is_ascii_digit() {
920                    // copy everything from the start up to (including) the e
921                    new_s.extend_from_slice(&s[0..=i]);
922                    // add the missing '+'
923                    new_s.push(b'+');
924                    // check for the remaining characters.
925                    // If it's only one, we need to prepend a trailing zero
926                    if s.len() == i + 2 {
927                        new_s.push(b'0');
928                    }
929                    new_s.extend_from_slice(&s[i + 1..]);
930                    break;
931                }
932            }
933        }
934
935        // if we modified the scientific notation, flip the reference
936        if !new_s.is_empty() {
937            s = &mut new_s
938        }
939    } else if s.contains(&b'.') {
940        // else, if this is not scientific notation, and there's a
941        // decimal point, make sure we really drop trailing zeroes.
942        // In some cases, lexical_core doesn't.
943        for (i, c) in s.iter().enumerate() {
944            // at `.``
945            if c == &b'.' {
946                // trim zeroes from the right side.
947                let frac = String::from_utf8_lossy(&s[i + 1..]);
948                let frac_no_trailing_zeroes = frac.trim_end_matches('0');
949
950                if frac.len() != frac_no_trailing_zeroes.len() {
951                    // we managed to strip something, construct new_s
952                    if frac_no_trailing_zeroes.is_empty() {
953                        // if frac_no_trailing_zeroes is empty, the fractional part was all zeroes, so we can drop the decimal point as well
954                        new_s.extend_from_slice(&s[0..=i - 1]);
955                    } else {
956                        // else, assemble the rest of the string
957                        new_s.extend_from_slice(&s[0..=i]);
958                        new_s.extend_from_slice(frac_no_trailing_zeroes.as_bytes());
959                    }
960
961                    // flip the reference
962                    s = &mut new_s;
963                    break;
964                }
965            }
966        }
967    }
968
969    write!(f, "{}", String::from_utf8_lossy(s))
970}
971
972impl TotalDisplay for Value {
973    fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result {
974        match self {
975            Value::Null => f.write_str("null"),
976            Value::Bool(true) => f.write_str("true"),
977            Value::Bool(false) => f.write_str("false"),
978            Value::Integer(num) => write!(f, "{num}"),
979            Value::String(s) => s.fmt(f),
980            Value::Path(p) => p.display().fmt(f),
981            Value::Attrs(attrs) => attrs.total_fmt(f, set),
982            Value::List(list) => list.total_fmt(f, set),
983            // TODO: fancy REPL display with position
984            Value::Closure(_) => f.write_str("<LAMBDA>"),
985            Value::Builtin(builtin) => builtin.fmt(f),
986
987            // Nix prints floats with a maximum precision of 5 digits
988            // only. Except when it decides to use scientific notation
989            // (with a + after the `e`, and zero-padded to 0 digits)
990            Value::Float(num) => total_fmt_float(*num, f),
991
992            // internal types
993            Value::AttrNotFound => f.write_str("internal[not found]"),
994            Value::Blueprint(_) => f.write_str("internal[blueprint]"),
995            Value::DeferredUpvalue(_) => f.write_str("internal[deferred_upvalue]"),
996            Value::UnresolvedPath(_) => f.write_str("internal[unresolved_path]"),
997            Value::FinaliseRequest(_) => f.write_str("internal[finaliser_sentinel]"),
998
999            // Delegate thunk display to the type, as it must handle
1000            // the case of already evaluated or cyclic thunks.
1001            Value::Thunk(t) => t.total_fmt(f, set),
1002            Value::Catchable(_) => panic!("total_fmt() called on a CatchableErrorKind"),
1003        }
1004    }
1005}
1006
1007impl From<bool> for Value {
1008    fn from(b: bool) -> Self {
1009        Value::Bool(b)
1010    }
1011}
1012
1013impl From<i64> for Value {
1014    fn from(i: i64) -> Self {
1015        Self::Integer(i)
1016    }
1017}
1018
1019impl From<f64> for Value {
1020    fn from(i: f64) -> Self {
1021        Self::Float(i)
1022    }
1023}
1024
1025impl From<PathBuf> for Value {
1026    fn from(path: PathBuf) -> Self {
1027        Self::Path(Box::new(path))
1028    }
1029}
1030
1031fn type_error(expected: &'static str, actual: &Value) -> ErrorKind {
1032    ErrorKind::TypeError {
1033        expected,
1034        actual: actual.type_of(),
1035    }
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040    use super::*;
1041    use std::mem::size_of;
1042
1043    #[test]
1044    fn size() {
1045        assert_eq!(size_of::<Value>(), 16);
1046    }
1047
1048    mod floats {
1049        use crate::value::total_fmt_float;
1050
1051        #[test]
1052        fn format_float() {
1053            let ff = [
1054                (0f64, "0"),
1055                (1.0f64, "1"),
1056                (-0.01, "-0.01"),
1057                (5e+22, "5e+22"),
1058                (1e6, "1e+06"),
1059                (-2E-2, "-0.02"),
1060                (6.626e-34, "6.626e-34"),
1061                (9_224_617.445_991_227, "9.22462e+06"),
1062            ];
1063            for (n, expected) in ff.iter() {
1064                let mut buf = String::new();
1065                let res = total_fmt_float(*n, &mut buf);
1066                assert!(res.is_ok());
1067                assert_eq!(
1068                    expected, &buf,
1069                    "{} should be formatted as {}, but got {}",
1070                    n, expected, &buf
1071                );
1072            }
1073        }
1074    }
1075}