2022-08-07 22:40:12 +02:00
|
|
|
//! This module implements the backing representation of runtime
|
|
|
|
//! values in the Nix language.
|
2022-10-23 19:24:05 +02:00
|
|
|
use std::cmp::Ordering;
|
feat(tvix/eval): use lexical-core to format float
Apparently our naive implementation of float formatting, which simply
used {:.5}, and trimmed trailing "0" strings not sufficient.
It wrongly trimmed numbers with zeroes but no decimal point, like
`10000` got trimmed to `1`.
Nix uses `std::to_string` on the double, which according to
https://en.cppreference.com/w/cpp/string/basic_string/to_string
is equivalent to `std::sprintf(buf, "%f", value)`.
https://en.cppreference.com/w/cpp/io/c/fprintf mentions this is treated
like this:
> Precision specifies the exact number of digits to appear after
> the decimal point character. The default precision is 6. In the
> alternative implementation decimal point character is written even if
> no digits follow it. For infinity and not-a-number conversion style
> see notes.
This doesn't seem to be the case though, and Nix uses scientific
notation in some cases.
There's a whole bunch of strategies to determine which is a more compact
notation, and which notation should be used for a given number.
https://github.com/rust-lang/rust/issues/24556 provides some pointers
into various rabbit holes for those interested.
This gist seems to be that currently a different formatting is not
exposed in rust directly, at least not for public consumption.
There is the
[lexical-core](https://github.com/Alexhuszagh/rust-lexical) crate
though, which provides a way to format floats with various strategies
and formats.
Change our implementation of `TotalDisplay` for the `Value::Float` case
to use that. We still need to do some post-processing, because Nix
always adds the sign in scientific notation (and there's no way to
configure lexical-core to do that), and lexical-core in some cases keeps
the trailing zeros.
Even with all that in place, there as a difference in `eval-okay-
fromjson.nix` (from tvix-tests), which I couldn't get to work. I updated
the fixture to a less problematic number.
With this, the testsuite passes again, and does for the upcoming CL
introducing builtins.fromTOML, and enabling the nix testsuite bits for
it, too.
Change-Id: Ie6fba5619e1d9fd7ce669a51594658b029057acc
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7922
Tested-by: BuildkiteCI
Autosubmit: flokli <flokli@flokli.de>
Reviewed-by: tazjin <tazjin@tvl.su>
2023-01-24 19:27:20 +01:00
|
|
|
use std::num::{NonZeroI32, NonZeroUsize};
|
2022-09-18 22:53:08 +02:00
|
|
|
use std::ops::Deref;
|
2022-10-22 15:51:29 +02:00
|
|
|
use std::path::PathBuf;
|
2022-08-08 16:27:16 +02:00
|
|
|
use std::rc::Rc;
|
2022-10-22 15:51:29 +02:00
|
|
|
use std::{cell::Ref, fmt::Display};
|
2022-08-08 01:55:13 +02:00
|
|
|
|
feat(tvix/eval): use lexical-core to format float
Apparently our naive implementation of float formatting, which simply
used {:.5}, and trimmed trailing "0" strings not sufficient.
It wrongly trimmed numbers with zeroes but no decimal point, like
`10000` got trimmed to `1`.
Nix uses `std::to_string` on the double, which according to
https://en.cppreference.com/w/cpp/string/basic_string/to_string
is equivalent to `std::sprintf(buf, "%f", value)`.
https://en.cppreference.com/w/cpp/io/c/fprintf mentions this is treated
like this:
> Precision specifies the exact number of digits to appear after
> the decimal point character. The default precision is 6. In the
> alternative implementation decimal point character is written even if
> no digits follow it. For infinity and not-a-number conversion style
> see notes.
This doesn't seem to be the case though, and Nix uses scientific
notation in some cases.
There's a whole bunch of strategies to determine which is a more compact
notation, and which notation should be used for a given number.
https://github.com/rust-lang/rust/issues/24556 provides some pointers
into various rabbit holes for those interested.
This gist seems to be that currently a different formatting is not
exposed in rust directly, at least not for public consumption.
There is the
[lexical-core](https://github.com/Alexhuszagh/rust-lexical) crate
though, which provides a way to format floats with various strategies
and formats.
Change our implementation of `TotalDisplay` for the `Value::Float` case
to use that. We still need to do some post-processing, because Nix
always adds the sign in scientific notation (and there's no way to
configure lexical-core to do that), and lexical-core in some cases keeps
the trailing zeros.
Even with all that in place, there as a difference in `eval-okay-
fromjson.nix` (from tvix-tests), which I couldn't get to work. I updated
the fixture to a less problematic number.
With this, the testsuite passes again, and does for the upcoming CL
introducing builtins.fromTOML, and enabling the nix testsuite bits for
it, too.
Change-Id: Ie6fba5619e1d9fd7ce669a51594658b029057acc
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7922
Tested-by: BuildkiteCI
Autosubmit: flokli <flokli@flokli.de>
Reviewed-by: tazjin <tazjin@tvl.su>
2023-01-24 19:27:20 +01:00
|
|
|
use lexical_core::format::CXX_LITERAL;
|
2023-01-10 12:52:59 +01:00
|
|
|
use serde::{Deserialize, Serialize};
|
2022-12-24 18:18:26 +01:00
|
|
|
|
2022-09-17 20:14:33 +02:00
|
|
|
#[cfg(feature = "arbitrary")]
|
|
|
|
mod arbitrary;
|
2022-08-08 16:09:50 +02:00
|
|
|
mod attrs;
|
2022-08-24 10:00:30 +02:00
|
|
|
mod builtin;
|
2022-08-24 21:08:26 +02:00
|
|
|
mod function;
|
2022-08-09 16:08:10 +02:00
|
|
|
mod list;
|
2022-10-13 06:58:42 +02:00
|
|
|
mod path;
|
2022-08-08 16:09:21 +02:00
|
|
|
mod string;
|
2022-08-28 22:50:55 +02:00
|
|
|
mod thunk;
|
2022-08-08 16:09:21 +02:00
|
|
|
|
2022-09-01 22:50:27 +02:00
|
|
|
use crate::errors::ErrorKind;
|
2022-08-28 15:59:08 +02:00
|
|
|
use crate::opcode::StackIdx;
|
2022-09-13 15:37:19 +02:00
|
|
|
use crate::vm::VM;
|
2022-08-09 15:52:01 +02:00
|
|
|
pub use attrs::NixAttrs;
|
2022-11-06 16:28:34 +01:00
|
|
|
pub use builtin::{Builtin, BuiltinArgument};
|
2022-10-13 05:27:09 +02:00
|
|
|
pub(crate) use function::Formals;
|
2022-08-24 21:08:26 +02:00
|
|
|
pub use function::{Closure, Lambda};
|
2022-08-09 16:08:10 +02:00
|
|
|
pub use list::NixList;
|
2022-10-13 06:58:42 +02:00
|
|
|
pub use path::canon_path;
|
2022-08-09 15:52:01 +02:00
|
|
|
pub use string::NixString;
|
2022-08-28 22:50:55 +02:00
|
|
|
pub use thunk::Thunk;
|
2022-08-08 16:27:16 +02:00
|
|
|
|
2022-10-13 04:47:23 +02:00
|
|
|
use self::thunk::ThunkSet;
|
|
|
|
|
feat(tvix/eval): use lexical-core to format float
Apparently our naive implementation of float formatting, which simply
used {:.5}, and trimmed trailing "0" strings not sufficient.
It wrongly trimmed numbers with zeroes but no decimal point, like
`10000` got trimmed to `1`.
Nix uses `std::to_string` on the double, which according to
https://en.cppreference.com/w/cpp/string/basic_string/to_string
is equivalent to `std::sprintf(buf, "%f", value)`.
https://en.cppreference.com/w/cpp/io/c/fprintf mentions this is treated
like this:
> Precision specifies the exact number of digits to appear after
> the decimal point character. The default precision is 6. In the
> alternative implementation decimal point character is written even if
> no digits follow it. For infinity and not-a-number conversion style
> see notes.
This doesn't seem to be the case though, and Nix uses scientific
notation in some cases.
There's a whole bunch of strategies to determine which is a more compact
notation, and which notation should be used for a given number.
https://github.com/rust-lang/rust/issues/24556 provides some pointers
into various rabbit holes for those interested.
This gist seems to be that currently a different formatting is not
exposed in rust directly, at least not for public consumption.
There is the
[lexical-core](https://github.com/Alexhuszagh/rust-lexical) crate
though, which provides a way to format floats with various strategies
and formats.
Change our implementation of `TotalDisplay` for the `Value::Float` case
to use that. We still need to do some post-processing, because Nix
always adds the sign in scientific notation (and there's no way to
configure lexical-core to do that), and lexical-core in some cases keeps
the trailing zeros.
Even with all that in place, there as a difference in `eval-okay-
fromjson.nix` (from tvix-tests), which I couldn't get to work. I updated
the fixture to a less problematic number.
With this, the testsuite passes again, and does for the upcoming CL
introducing builtins.fromTOML, and enabling the nix testsuite bits for
it, too.
Change-Id: Ie6fba5619e1d9fd7ce669a51594658b029057acc
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7922
Tested-by: BuildkiteCI
Autosubmit: flokli <flokli@flokli.de>
Reviewed-by: tazjin <tazjin@tvl.su>
2023-01-24 19:27:20 +01:00
|
|
|
use lazy_static::lazy_static;
|
|
|
|
|
2022-08-12 16:45:22 +02:00
|
|
|
#[warn(variant_size_differences)]
|
2023-01-10 12:52:59 +01:00
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
2022-12-24 18:18:26 +01:00
|
|
|
#[serde(untagged)]
|
2022-08-07 22:40:12 +02:00
|
|
|
pub enum Value {
|
|
|
|
Null,
|
|
|
|
Bool(bool),
|
|
|
|
Integer(i64),
|
|
|
|
Float(f64),
|
2022-08-08 16:27:16 +02:00
|
|
|
String(NixString),
|
2022-12-24 18:18:26 +01:00
|
|
|
|
|
|
|
#[serde(skip)]
|
2022-08-12 16:44:48 +02:00
|
|
|
Path(PathBuf),
|
2022-12-29 15:34:08 +01:00
|
|
|
Attrs(Box<NixAttrs>),
|
2022-08-09 16:08:10 +02:00
|
|
|
List(NixList),
|
2022-12-24 18:18:26 +01:00
|
|
|
|
|
|
|
#[serde(skip)]
|
2022-11-27 09:54:39 +01:00
|
|
|
Closure(Rc<Closure>), // must use Rc<Closure> here in order to get proper pointer equality
|
2023-01-10 12:52:59 +01:00
|
|
|
|
2022-12-24 18:18:26 +01:00
|
|
|
#[serde(skip)]
|
2022-08-24 10:00:30 +02:00
|
|
|
Builtin(Builtin),
|
2022-08-09 17:49:05 +02:00
|
|
|
|
|
|
|
// Internal values that, while they technically exist at runtime,
|
|
|
|
// are never returned to or created directly by users.
|
2023-01-10 12:52:59 +01:00
|
|
|
#[serde(skip_deserializing)]
|
2022-08-28 22:50:55 +02:00
|
|
|
Thunk(Thunk),
|
2022-10-16 02:06:08 +02:00
|
|
|
|
|
|
|
// See [`compiler::compile_select_or()`] for explanation
|
2022-12-24 18:18:26 +01:00
|
|
|
#[serde(skip)]
|
2022-08-26 17:40:55 +02:00
|
|
|
AttrNotFound,
|
2022-10-16 02:06:08 +02:00
|
|
|
|
|
|
|
// this can only occur in Chunk::Constants and nowhere else
|
2022-12-24 18:18:26 +01:00
|
|
|
#[serde(skip)]
|
2022-08-28 05:07:20 +02:00
|
|
|
Blueprint(Rc<Lambda>),
|
2022-10-16 02:06:08 +02:00
|
|
|
|
2022-12-24 18:18:26 +01:00
|
|
|
#[serde(skip)]
|
2022-08-28 15:59:08 +02:00
|
|
|
DeferredUpvalue(StackIdx),
|
2022-12-24 18:18:26 +01:00
|
|
|
#[serde(skip)]
|
2022-10-15 16:21:14 +02:00
|
|
|
UnresolvedPath(PathBuf),
|
2022-08-07 22:40:12 +02:00
|
|
|
}
|
2022-08-08 01:16:28 +02:00
|
|
|
|
feat(tvix/eval): use lexical-core to format float
Apparently our naive implementation of float formatting, which simply
used {:.5}, and trimmed trailing "0" strings not sufficient.
It wrongly trimmed numbers with zeroes but no decimal point, like
`10000` got trimmed to `1`.
Nix uses `std::to_string` on the double, which according to
https://en.cppreference.com/w/cpp/string/basic_string/to_string
is equivalent to `std::sprintf(buf, "%f", value)`.
https://en.cppreference.com/w/cpp/io/c/fprintf mentions this is treated
like this:
> Precision specifies the exact number of digits to appear after
> the decimal point character. The default precision is 6. In the
> alternative implementation decimal point character is written even if
> no digits follow it. For infinity and not-a-number conversion style
> see notes.
This doesn't seem to be the case though, and Nix uses scientific
notation in some cases.
There's a whole bunch of strategies to determine which is a more compact
notation, and which notation should be used for a given number.
https://github.com/rust-lang/rust/issues/24556 provides some pointers
into various rabbit holes for those interested.
This gist seems to be that currently a different formatting is not
exposed in rust directly, at least not for public consumption.
There is the
[lexical-core](https://github.com/Alexhuszagh/rust-lexical) crate
though, which provides a way to format floats with various strategies
and formats.
Change our implementation of `TotalDisplay` for the `Value::Float` case
to use that. We still need to do some post-processing, because Nix
always adds the sign in scientific notation (and there's no way to
configure lexical-core to do that), and lexical-core in some cases keeps
the trailing zeros.
Even with all that in place, there as a difference in `eval-okay-
fromjson.nix` (from tvix-tests), which I couldn't get to work. I updated
the fixture to a less problematic number.
With this, the testsuite passes again, and does for the upcoming CL
introducing builtins.fromTOML, and enabling the nix testsuite bits for
it, too.
Change-Id: Ie6fba5619e1d9fd7ce669a51594658b029057acc
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7922
Tested-by: BuildkiteCI
Autosubmit: flokli <flokli@flokli.de>
Reviewed-by: tazjin <tazjin@tvl.su>
2023-01-24 19:27:20 +01:00
|
|
|
lazy_static! {
|
|
|
|
static ref WRITE_FLOAT_OPTIONS: lexical_core::WriteFloatOptions =
|
|
|
|
lexical_core::WriteFloatOptionsBuilder::new()
|
|
|
|
.trim_floats(true)
|
|
|
|
.round_mode(lexical_core::write_float_options::RoundMode::Round)
|
|
|
|
.positive_exponent_break(Some(NonZeroI32::new(5).unwrap()))
|
|
|
|
.max_significant_digits(Some(NonZeroUsize::new(6).unwrap()))
|
|
|
|
.build()
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
|
2022-09-02 04:40:50 +02:00
|
|
|
// Helper macros to generate the to_*/as_* macros while accounting for
|
|
|
|
// thunks.
|
|
|
|
|
|
|
|
/// Generate an `as_*` method returning a reference to the expected
|
|
|
|
/// type, or a type error. This only works for types that implement
|
|
|
|
/// `Copy`, as returning a reference to an inner thunk value is not
|
|
|
|
/// possible.
|
|
|
|
|
|
|
|
/// Generate an `as_*/to_*` accessor method that returns either the
|
|
|
|
/// expected type, or a type error.
|
|
|
|
macro_rules! gen_cast {
|
|
|
|
( $name:ident, $type:ty, $expected:expr, $variant:pat, $result:expr ) => {
|
|
|
|
pub fn $name(&self) -> Result<$type, ErrorKind> {
|
|
|
|
match self {
|
|
|
|
$variant => Ok($result),
|
|
|
|
Value::Thunk(thunk) => Self::$name(&thunk.value()),
|
|
|
|
other => Err(type_error($expected, &other)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-10-18 12:32:35 +02:00
|
|
|
/// Generate an `as_*_mut/to_*_mut` accessor method that returns either the
|
|
|
|
/// expected type, or a type error.
|
|
|
|
macro_rules! gen_cast_mut {
|
|
|
|
( $name:ident, $type:ty, $expected:expr, $variant:ident) => {
|
|
|
|
pub fn $name(&mut self) -> Result<&mut $type, ErrorKind> {
|
|
|
|
match self {
|
|
|
|
Value::$variant(x) => Ok(x),
|
|
|
|
other => Err(type_error($expected, &other)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-09-02 04:40:50 +02:00
|
|
|
/// Generate an `is_*` type-checking method.
|
|
|
|
macro_rules! gen_is {
|
|
|
|
( $name:ident, $variant:pat ) => {
|
|
|
|
pub fn $name(&self) -> bool {
|
|
|
|
match self {
|
|
|
|
$variant => true,
|
|
|
|
Value::Thunk(thunk) => Self::$name(&thunk.value()),
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2022-08-08 01:16:28 +02:00
|
|
|
|
2022-09-13 15:37:19 +02:00
|
|
|
/// Describes what input types are allowed when coercing a `Value` to a string
|
2022-11-26 01:47:26 +01:00
|
|
|
#[derive(Clone, Copy, PartialEq, Debug)]
|
2022-09-13 15:37:19 +02:00
|
|
|
pub enum CoercionKind {
|
2022-11-26 01:47:26 +01:00
|
|
|
/// Force thunks, but perform no other coercions.
|
|
|
|
ThunksOnly,
|
2022-09-13 15:37:19 +02:00
|
|
|
/// Only coerce already "stringly" types like strings and paths, but also
|
|
|
|
/// coerce sets that have a `__toString` attribute. Equivalent to
|
|
|
|
/// `!coerceMore` in C++ Nix.
|
|
|
|
Weak,
|
|
|
|
/// Coerce all value types included by `Weak`, but also coerce `null`,
|
|
|
|
/// booleans, integers, floats and lists of coercible types. Equivalent to
|
|
|
|
/// `coerceMore` in C++ Nix.
|
|
|
|
Strong,
|
|
|
|
}
|
|
|
|
|
2022-09-18 22:53:08 +02:00
|
|
|
/// A reference to a [`Value`] returned by a call to [`Value::force`], whether the value was
|
|
|
|
/// originally a thunk or not.
|
|
|
|
///
|
|
|
|
/// Implements [`Deref`] to [`Value`], so can generally be used as a [`Value`]
|
2023-01-13 23:47:51 +01:00
|
|
|
pub enum ForceResult<'a> {
|
2022-09-18 22:53:08 +02:00
|
|
|
ForcedThunk(Ref<'a, Value>),
|
|
|
|
Immediate(&'a Value),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Deref for ForceResult<'a> {
|
|
|
|
type Target = Value;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
match self {
|
|
|
|
ForceResult::ForcedThunk(r) => r,
|
|
|
|
ForceResult::Immediate(v) => v,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-09 21:46:16 +02:00
|
|
|
impl<T> From<T> for Value
|
|
|
|
where
|
|
|
|
T: Into<NixString>,
|
|
|
|
{
|
|
|
|
fn from(t: T) -> Self {
|
|
|
|
Self::String(t.into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-08 19:33:33 +02:00
|
|
|
/// Constructors
|
|
|
|
impl Value {
|
|
|
|
/// Construct a [`Value::Attrs`] from a [`NixAttrs`].
|
|
|
|
pub fn attrs(attrs: NixAttrs) -> Self {
|
2022-12-29 15:34:08 +01:00
|
|
|
Self::Attrs(Box::new(attrs))
|
2022-10-08 19:33:33 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-02 04:40:50 +02:00
|
|
|
impl Value {
|
2022-09-13 15:37:19 +02:00
|
|
|
/// Coerce a `Value` to a string. See `CoercionKind` for a rundown of what
|
|
|
|
/// input types are accepted under what circumstances.
|
|
|
|
pub fn coerce_to_string(
|
|
|
|
&self,
|
|
|
|
kind: CoercionKind,
|
|
|
|
vm: &mut VM,
|
|
|
|
) -> Result<NixString, ErrorKind> {
|
2022-09-13 20:11:07 +02:00
|
|
|
// TODO: eventually, this will need to handle string context and importing
|
|
|
|
// files into the Nix store depending on what context the coercion happens in
|
2022-09-13 15:37:19 +02:00
|
|
|
if let Value::Thunk(t) = self {
|
|
|
|
t.force(vm)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
match (self, kind) {
|
|
|
|
// deal with thunks
|
|
|
|
(Value::Thunk(t), _) => t.value().coerce_to_string(kind, vm),
|
|
|
|
|
|
|
|
// coercions that are always done
|
|
|
|
(Value::String(s), _) => Ok(s.clone()),
|
2022-11-26 01:47:26 +01:00
|
|
|
|
2022-09-13 15:37:19 +02:00
|
|
|
// TODO(sterni): Think about proper encoding handling here. This needs
|
|
|
|
// general consideration anyways, since one current discrepancy between
|
|
|
|
// C++ Nix and Tvix is that the former's strings are arbitrary byte
|
|
|
|
// sequences without NUL bytes, whereas Tvix only allows valid
|
|
|
|
// Unicode. See also b/189.
|
2022-11-26 01:47:26 +01:00
|
|
|
(Value::Path(p), kind) if kind != CoercionKind::ThunksOnly => {
|
2022-12-12 22:12:13 +01:00
|
|
|
let imported = vm.io().import_path(p)?;
|
|
|
|
Ok(imported.to_string_lossy().into_owned().into())
|
2022-11-26 01:47:26 +01:00
|
|
|
}
|
2022-09-13 15:37:19 +02:00
|
|
|
|
|
|
|
// Attribute sets can be converted to strings if they either have an
|
|
|
|
// `__toString` attribute which holds a function that receives the
|
|
|
|
// set itself or an `outPath` attribute which should be a string.
|
|
|
|
// `__toString` is preferred.
|
2022-11-26 01:47:26 +01:00
|
|
|
(Value::Attrs(attrs), kind) if kind != CoercionKind::ThunksOnly => {
|
2022-09-13 15:37:19 +02:00
|
|
|
match (attrs.select("__toString"), attrs.select("outPath")) {
|
2022-09-16 23:13:02 +02:00
|
|
|
(None, None) => Err(ErrorKind::NotCoercibleToString { from: "set", kind }),
|
2022-09-13 15:37:19 +02:00
|
|
|
|
|
|
|
(Some(f), _) => {
|
|
|
|
// use a closure here to deal with the thunk borrow we need to do below
|
|
|
|
let call_to_string = |value: &Value, vm: &mut VM| {
|
2022-09-20 23:32:49 +02:00
|
|
|
// Leave self on the stack as an argument to the function call.
|
|
|
|
vm.push(self.clone());
|
2022-10-11 01:14:47 +02:00
|
|
|
vm.call_value(value)?;
|
|
|
|
let result = vm.pop();
|
2022-09-13 15:37:19 +02:00
|
|
|
|
|
|
|
match result {
|
|
|
|
Value::String(s) => Ok(s),
|
|
|
|
// Attribute set coercion actually works
|
|
|
|
// recursively, e.g. you can even return
|
|
|
|
// /another/ set with a __toString attr.
|
|
|
|
_ => result.coerce_to_string(kind, vm),
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
if let Value::Thunk(t) = f {
|
|
|
|
t.force(vm)?;
|
|
|
|
let guard = t.value();
|
2022-12-20 15:22:56 +01:00
|
|
|
call_to_string(&guard, vm)
|
2022-09-13 15:37:19 +02:00
|
|
|
} else {
|
2022-09-16 23:13:02 +02:00
|
|
|
call_to_string(f, vm)
|
2022-09-13 15:37:19 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Similarly to `__toString` we also coerce recursively for `outPath`
|
|
|
|
(None, Some(s)) => s.coerce_to_string(kind, vm),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// strong coercions
|
|
|
|
(Value::Null, CoercionKind::Strong) | (Value::Bool(false), CoercionKind::Strong) => {
|
|
|
|
Ok("".into())
|
|
|
|
}
|
|
|
|
(Value::Bool(true), CoercionKind::Strong) => Ok("1".into()),
|
|
|
|
|
|
|
|
(Value::Integer(i), CoercionKind::Strong) => Ok(format!("{i}").into()),
|
|
|
|
(Value::Float(f), CoercionKind::Strong) => {
|
|
|
|
// contrary to normal Display, coercing a float to a string will
|
|
|
|
// result in unconditional 6 decimal places
|
|
|
|
Ok(format!("{:.6}", f).into())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lists are coerced by coercing their elements and interspersing spaces
|
|
|
|
(Value::List(l), CoercionKind::Strong) => {
|
|
|
|
// TODO(sterni): use intersperse when it becomes available?
|
|
|
|
// https://github.com/rust-lang/rust/issues/79524
|
|
|
|
l.iter()
|
|
|
|
.map(|v| v.coerce_to_string(kind, vm))
|
|
|
|
.reduce(|acc, string| {
|
|
|
|
let a = acc?;
|
|
|
|
let s = &string?;
|
|
|
|
Ok(a.concat(&" ".into()).concat(s))
|
|
|
|
})
|
|
|
|
// None from reduce indicates empty iterator
|
2022-09-16 23:13:02 +02:00
|
|
|
.unwrap_or_else(|| Ok("".into()))
|
2022-09-13 15:37:19 +02:00
|
|
|
}
|
|
|
|
|
2022-11-26 01:47:26 +01:00
|
|
|
(Value::Path(_), _)
|
|
|
|
| (Value::Attrs(_), _)
|
|
|
|
| (Value::Closure(_), _)
|
2022-09-13 15:37:19 +02:00
|
|
|
| (Value::Builtin(_), _)
|
|
|
|
| (Value::Null, _)
|
|
|
|
| (Value::Bool(_), _)
|
|
|
|
| (Value::Integer(_), _)
|
|
|
|
| (Value::Float(_), _)
|
|
|
|
| (Value::List(_), _) => Err(ErrorKind::NotCoercibleToString {
|
|
|
|
from: self.type_of(),
|
2022-09-16 23:13:02 +02:00
|
|
|
kind,
|
2022-09-13 15:37:19 +02:00
|
|
|
}),
|
|
|
|
|
2022-09-24 15:00:32 +02:00
|
|
|
(Value::AttrNotFound, _)
|
2022-09-13 15:37:19 +02:00
|
|
|
| (Value::Blueprint(_), _)
|
2022-10-15 16:21:14 +02:00
|
|
|
| (Value::DeferredUpvalue(_), _)
|
|
|
|
| (Value::UnresolvedPath(_), _) => {
|
2022-09-13 15:37:19 +02:00
|
|
|
panic!("tvix bug: .coerce_to_string() called on internal value")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-08 01:16:28 +02:00
|
|
|
pub fn type_of(&self) -> &'static str {
|
|
|
|
match self {
|
|
|
|
Value::Null => "null",
|
|
|
|
Value::Bool(_) => "bool",
|
|
|
|
Value::Integer(_) => "int",
|
|
|
|
Value::Float(_) => "float",
|
2022-08-08 16:27:16 +02:00
|
|
|
Value::String(_) => "string",
|
2022-08-12 16:44:48 +02:00
|
|
|
Value::Path(_) => "path",
|
2022-08-08 16:27:16 +02:00
|
|
|
Value::Attrs(_) => "set",
|
2022-08-09 16:08:10 +02:00
|
|
|
Value::List(_) => "list",
|
2022-08-24 21:08:26 +02:00
|
|
|
Value::Closure(_) | Value::Builtin(_) => "lambda",
|
2022-08-09 17:49:05 +02:00
|
|
|
|
2023-02-01 23:46:58 +01:00
|
|
|
// Internal types. Note: These are only elaborated here
|
|
|
|
// because it makes debugging easier. If a user ever sees
|
|
|
|
// any of these strings, it's a bug.
|
|
|
|
Value::Thunk(_) => "internal[thunk]",
|
|
|
|
Value::AttrNotFound => "internal[attr_not_found]",
|
|
|
|
Value::Blueprint(_) => "internal[blueprint]",
|
|
|
|
Value::DeferredUpvalue(_) => "internal[deferred_upvalue]",
|
|
|
|
Value::UnresolvedPath(_) => "internal[unresolved_path]",
|
2022-08-08 01:16:28 +02:00
|
|
|
}
|
|
|
|
}
|
2022-08-08 01:55:13 +02:00
|
|
|
|
2022-09-02 04:40:50 +02:00
|
|
|
gen_cast!(as_bool, bool, "bool", Value::Bool(b), *b);
|
2022-09-06 07:16:17 +02:00
|
|
|
gen_cast!(as_int, i64, "int", Value::Integer(x), *x);
|
2022-10-17 23:37:47 +02:00
|
|
|
gen_cast!(as_float, f64, "float", Value::Float(x), *x);
|
2022-09-02 04:40:50 +02:00
|
|
|
gen_cast!(to_str, NixString, "string", Value::String(s), s.clone());
|
2022-12-29 15:34:08 +01:00
|
|
|
gen_cast!(to_attrs, Box<NixAttrs>, "set", Value::Attrs(a), a.clone());
|
2022-09-02 04:40:50 +02:00
|
|
|
gen_cast!(to_list, NixList, "list", Value::List(l), l.clone());
|
2022-11-27 09:54:39 +01:00
|
|
|
gen_cast!(
|
|
|
|
as_closure,
|
|
|
|
Rc<Closure>,
|
|
|
|
"lambda",
|
|
|
|
Value::Closure(c),
|
|
|
|
c.clone()
|
|
|
|
);
|
2022-08-11 13:56:27 +02:00
|
|
|
|
2022-10-18 12:32:35 +02:00
|
|
|
gen_cast_mut!(as_list_mut, NixList, "list", List);
|
|
|
|
|
2022-10-12 11:46:20 +02:00
|
|
|
gen_is!(is_path, Value::Path(_));
|
2022-09-02 04:40:50 +02:00
|
|
|
gen_is!(is_number, Value::Integer(_) | Value::Float(_));
|
|
|
|
gen_is!(is_bool, Value::Bool(_));
|
2022-09-18 20:04:40 +02:00
|
|
|
|
2022-09-18 21:13:20 +02:00
|
|
|
/// Compare `self` against `other` for equality using Nix equality semantics.
|
|
|
|
///
|
|
|
|
/// Takes a reference to the `VM` to allow forcing thunks during comparison
|
|
|
|
pub fn nix_eq(&self, other: &Self, vm: &mut VM) -> Result<bool, ErrorKind> {
|
2022-09-18 20:04:40 +02:00
|
|
|
match (self, other) {
|
|
|
|
// Trivial comparisons
|
|
|
|
(Value::Null, Value::Null) => Ok(true),
|
|
|
|
(Value::Bool(b1), Value::Bool(b2)) => Ok(b1 == b2),
|
|
|
|
(Value::String(s1), Value::String(s2)) => Ok(s1 == s2),
|
|
|
|
(Value::Path(p1), Value::Path(p2)) => Ok(p1 == p2),
|
|
|
|
|
|
|
|
// Numerical comparisons (they work between float & int)
|
|
|
|
(Value::Integer(i1), Value::Integer(i2)) => Ok(i1 == i2),
|
|
|
|
(Value::Integer(i), Value::Float(f)) => Ok(*i as f64 == *f),
|
|
|
|
(Value::Float(f1), Value::Float(f2)) => Ok(f1 == f2),
|
|
|
|
(Value::Float(f), Value::Integer(i)) => Ok(*i as f64 == *f),
|
|
|
|
|
2022-11-22 05:04:12 +01:00
|
|
|
(Value::Attrs(_), Value::Attrs(_))
|
|
|
|
| (Value::List(_), Value::List(_))
|
|
|
|
| (Value::Thunk(_), _)
|
|
|
|
| (_, Value::Thunk(_)) => Ok(vm.nix_eq(self.clone(), other.clone(), false)?),
|
2022-09-18 20:04:40 +02:00
|
|
|
|
|
|
|
// Everything else is either incomparable (e.g. internal
|
|
|
|
// types) or false.
|
|
|
|
_ => Ok(false),
|
|
|
|
}
|
|
|
|
}
|
2022-09-18 22:53:08 +02:00
|
|
|
|
2022-10-23 19:24:05 +02:00
|
|
|
/// Compare `self` against other using (fallible) Nix ordering semantics.
|
2022-10-23 19:37:11 +02:00
|
|
|
pub fn nix_cmp(&self, other: &Self, vm: &mut VM) -> Result<Option<Ordering>, ErrorKind> {
|
2022-10-23 19:24:05 +02:00
|
|
|
match (self, other) {
|
|
|
|
// same types
|
|
|
|
(Value::Integer(i1), Value::Integer(i2)) => Ok(i1.partial_cmp(i2)),
|
|
|
|
(Value::Float(f1), Value::Float(f2)) => Ok(f1.partial_cmp(f2)),
|
|
|
|
(Value::String(s1), Value::String(s2)) => Ok(s1.partial_cmp(s2)),
|
2022-10-23 19:37:11 +02:00
|
|
|
(Value::List(l1), Value::List(l2)) => {
|
|
|
|
for i in 0.. {
|
|
|
|
if i == l2.len() {
|
|
|
|
return Ok(Some(Ordering::Greater));
|
|
|
|
} else if i == l1.len() {
|
|
|
|
return Ok(Some(Ordering::Less));
|
2022-11-24 10:35:39 +01:00
|
|
|
} else if !vm.nix_eq(l1[i].clone(), l2[i].clone(), true)? {
|
2022-10-23 19:37:11 +02:00
|
|
|
return l1[i].force(vm)?.nix_cmp(&*l2[i].force(vm)?, vm);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unreachable!()
|
|
|
|
}
|
2022-10-23 19:24:05 +02:00
|
|
|
|
|
|
|
// different types
|
|
|
|
(Value::Integer(i1), Value::Float(f2)) => Ok((*i1 as f64).partial_cmp(f2)),
|
|
|
|
(Value::Float(f1), Value::Integer(i2)) => Ok(f1.partial_cmp(&(*i2 as f64))),
|
|
|
|
|
|
|
|
// unsupported types
|
|
|
|
(lhs, rhs) => Err(ErrorKind::Incomparable {
|
|
|
|
lhs: lhs.type_of(),
|
|
|
|
rhs: rhs.type_of(),
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-18 22:53:08 +02:00
|
|
|
/// Ensure `self` is forced if it is a thunk, and return a reference to the resulting value.
|
2023-01-13 23:47:51 +01:00
|
|
|
pub fn force(&self, vm: &mut VM) -> Result<ForceResult, ErrorKind> {
|
2022-09-18 22:53:08 +02:00
|
|
|
match self {
|
|
|
|
Self::Thunk(thunk) => {
|
|
|
|
thunk.force(vm)?;
|
|
|
|
Ok(ForceResult::ForcedThunk(thunk.value()))
|
|
|
|
}
|
|
|
|
_ => Ok(ForceResult::Immediate(self)),
|
|
|
|
}
|
|
|
|
}
|
2022-10-13 04:47:23 +02:00
|
|
|
|
|
|
|
/// Ensure `self` is *deeply* forced, including all recursive sub-values
|
|
|
|
pub(crate) fn deep_force(
|
|
|
|
&self,
|
|
|
|
vm: &mut VM,
|
|
|
|
thunk_set: &mut ThunkSet,
|
|
|
|
) -> Result<(), ErrorKind> {
|
|
|
|
match self {
|
|
|
|
Value::Null
|
|
|
|
| Value::Bool(_)
|
|
|
|
| Value::Integer(_)
|
|
|
|
| Value::Float(_)
|
|
|
|
| Value::String(_)
|
|
|
|
| Value::Path(_)
|
|
|
|
| Value::Closure(_)
|
|
|
|
| Value::Builtin(_)
|
|
|
|
| Value::AttrNotFound
|
|
|
|
| Value::Blueprint(_)
|
|
|
|
| Value::DeferredUpvalue(_)
|
|
|
|
| Value::UnresolvedPath(_) => Ok(()),
|
|
|
|
Value::Attrs(a) => {
|
|
|
|
for (_, v) in a.iter() {
|
|
|
|
v.deep_force(vm, thunk_set)?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
Value::List(l) => {
|
|
|
|
for val in l {
|
|
|
|
val.deep_force(vm, thunk_set)?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
Value::Thunk(thunk) => {
|
|
|
|
if !thunk_set.insert(thunk) {
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
|
|
|
thunk.force(vm)?;
|
|
|
|
let value = thunk.value().clone();
|
|
|
|
value.deep_force(vm, thunk_set)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-12-19 10:58:01 +01:00
|
|
|
|
|
|
|
/// Explain a value in a human-readable way, e.g. by presenting
|
|
|
|
/// the docstrings of functions if present.
|
|
|
|
pub fn explain(&self) -> String {
|
|
|
|
match self {
|
|
|
|
Value::Null => "the 'null' value".into(),
|
|
|
|
Value::Bool(b) => format!("the boolean value '{}'", b),
|
|
|
|
Value::Integer(i) => format!("the integer '{}'", i),
|
|
|
|
Value::Float(f) => format!("the float '{}'", f),
|
|
|
|
Value::String(s) => format!("the string '{}'", s),
|
|
|
|
Value::Path(p) => format!("the path '{}'", p.to_string_lossy()),
|
|
|
|
Value::Attrs(attrs) => format!("a {}-item attribute set", attrs.len()),
|
|
|
|
Value::List(list) => format!("a {}-item list", list.len()),
|
2022-12-20 13:01:24 +01:00
|
|
|
|
|
|
|
Value::Closure(f) => {
|
|
|
|
if let Some(name) = &f.lambda.name {
|
|
|
|
format!("the user-defined Nix function '{}'", name)
|
|
|
|
} else {
|
2022-12-20 15:22:56 +01:00
|
|
|
"a user-defined Nix function".to_string()
|
2022-12-20 13:01:24 +01:00
|
|
|
}
|
|
|
|
}
|
2022-12-19 10:58:01 +01:00
|
|
|
|
|
|
|
Value::Builtin(b) => {
|
|
|
|
let mut out = format!("the builtin function '{}'", b.name());
|
|
|
|
if let Some(docs) = b.documentation() {
|
|
|
|
out.push_str("\n\n");
|
|
|
|
out.push_str(docs);
|
|
|
|
}
|
|
|
|
out
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: handle suspended thunks with a different explanation instead of panicking
|
|
|
|
Value::Thunk(t) => t.value().explain(),
|
|
|
|
|
|
|
|
Value::AttrNotFound
|
|
|
|
| Value::Blueprint(_)
|
|
|
|
| Value::DeferredUpvalue(_)
|
|
|
|
| Value::UnresolvedPath(_) => "an internal Tvix evaluator value".into(),
|
|
|
|
}
|
|
|
|
}
|
2022-08-08 01:16:28 +02:00
|
|
|
}
|
2022-08-08 15:43:09 +02:00
|
|
|
|
2022-10-22 15:51:29 +02:00
|
|
|
trait TotalDisplay {
|
|
|
|
fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result;
|
|
|
|
}
|
|
|
|
|
2022-08-08 15:43:09 +02:00
|
|
|
impl Display for Value {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2022-10-22 15:51:29 +02:00
|
|
|
self.total_fmt(f, &mut Default::default())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-25 09:05:43 +01:00
|
|
|
/// Emulates the C++-Nix style formatting of floats, which diverges
|
|
|
|
/// significantly from Rust's native float formatting.
|
|
|
|
fn total_fmt_float<F: std::fmt::Write>(num: f64, mut f: F) -> std::fmt::Result {
|
|
|
|
let mut buf = [b'0'; lexical_core::BUFFER_SIZE];
|
|
|
|
let mut s = lexical_core::write_with_options::<f64, { CXX_LITERAL }>(
|
|
|
|
num.clone(),
|
|
|
|
&mut buf,
|
|
|
|
&WRITE_FLOAT_OPTIONS,
|
|
|
|
);
|
|
|
|
|
|
|
|
// apply some postprocessing on the buffer. If scientific
|
|
|
|
// notation is used (we see an `e`), and the next character is
|
|
|
|
// a digit, add the missing `+` sign.)
|
|
|
|
let mut new_s = Vec::with_capacity(s.len());
|
|
|
|
|
|
|
|
if s.contains(&b'e') {
|
|
|
|
for (i, c) in s.iter().enumerate() {
|
|
|
|
// encountered `e`
|
|
|
|
if c == &b'e' {
|
|
|
|
// next character is a digit (so no negative exponent)
|
|
|
|
if s.len() > i && s[i + 1].is_ascii_digit() {
|
|
|
|
// copy everything from the start up to (including) the e
|
|
|
|
new_s.extend_from_slice(&s[0..=i]);
|
|
|
|
// add the missing '+'
|
|
|
|
new_s.push(b'+');
|
|
|
|
// check for the remaining characters.
|
|
|
|
// If it's only one, we need to prepend a trailing zero
|
|
|
|
if s.len() == i + 2 {
|
|
|
|
new_s.push(b'0');
|
|
|
|
}
|
|
|
|
new_s.extend_from_slice(&s[i + 1..]);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// if we modified the scientific notation, flip the reference
|
2023-02-02 15:34:15 +01:00
|
|
|
if !new_s.is_empty() {
|
2023-01-25 09:05:43 +01:00
|
|
|
s = &mut new_s
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// else, if this is not scientific notation, and there's a
|
|
|
|
// decimal point, make sure we really drop trailing zeroes.
|
|
|
|
// In some cases, lexical_core doesn't.
|
|
|
|
else if s.contains(&b'.') {
|
|
|
|
for (i, c) in s.iter().enumerate() {
|
|
|
|
// at `.``
|
|
|
|
if c == &b'.' {
|
|
|
|
// trim zeroes from the right side.
|
|
|
|
let frac = String::from_utf8_lossy(&s[i + 1..]);
|
|
|
|
let frac_no_trailing_zeroes = frac.trim_end_matches("0");
|
|
|
|
|
|
|
|
if frac.len() != frac_no_trailing_zeroes.len() {
|
|
|
|
// we managed to strip something, construct new_s
|
|
|
|
if frac_no_trailing_zeroes.is_empty() {
|
|
|
|
// if frac_no_trailing_zeroes is empty, the fractional part was all zeroes, so we can drop the decimal point as well
|
|
|
|
new_s.extend_from_slice(&s[0..=i - 1]);
|
|
|
|
} else {
|
|
|
|
// else, assemble the rest of the string
|
|
|
|
new_s.extend_from_slice(&s[0..=i]);
|
|
|
|
new_s.extend_from_slice(frac_no_trailing_zeroes.as_bytes());
|
|
|
|
}
|
|
|
|
|
|
|
|
// flip the reference
|
|
|
|
s = &mut new_s;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
write!(f, "{}", format!("{}", String::from_utf8_lossy(&s)))
|
|
|
|
}
|
|
|
|
|
2022-10-22 15:51:29 +02:00
|
|
|
impl TotalDisplay for Value {
|
|
|
|
fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result {
|
2022-08-08 15:43:09 +02:00
|
|
|
match self {
|
|
|
|
Value::Null => f.write_str("null"),
|
|
|
|
Value::Bool(true) => f.write_str("true"),
|
|
|
|
Value::Bool(false) => f.write_str("false"),
|
2022-08-12 16:30:17 +02:00
|
|
|
Value::Integer(num) => write!(f, "{}", num),
|
2022-08-08 16:27:16 +02:00
|
|
|
Value::String(s) => s.fmt(f),
|
2022-08-12 16:44:48 +02:00
|
|
|
Value::Path(p) => p.display().fmt(f),
|
2022-10-22 15:51:29 +02:00
|
|
|
Value::Attrs(attrs) => attrs.total_fmt(f, set),
|
|
|
|
Value::List(list) => list.total_fmt(f, set),
|
2022-08-24 21:08:26 +02:00
|
|
|
Value::Closure(_) => f.write_str("lambda"), // TODO: print position
|
2022-08-24 10:00:30 +02:00
|
|
|
Value::Builtin(builtin) => builtin.fmt(f),
|
2022-08-09 17:49:05 +02:00
|
|
|
|
2022-08-10 19:01:23 +02:00
|
|
|
// Nix prints floats with a maximum precision of 5 digits
|
feat(tvix/eval): use lexical-core to format float
Apparently our naive implementation of float formatting, which simply
used {:.5}, and trimmed trailing "0" strings not sufficient.
It wrongly trimmed numbers with zeroes but no decimal point, like
`10000` got trimmed to `1`.
Nix uses `std::to_string` on the double, which according to
https://en.cppreference.com/w/cpp/string/basic_string/to_string
is equivalent to `std::sprintf(buf, "%f", value)`.
https://en.cppreference.com/w/cpp/io/c/fprintf mentions this is treated
like this:
> Precision specifies the exact number of digits to appear after
> the decimal point character. The default precision is 6. In the
> alternative implementation decimal point character is written even if
> no digits follow it. For infinity and not-a-number conversion style
> see notes.
This doesn't seem to be the case though, and Nix uses scientific
notation in some cases.
There's a whole bunch of strategies to determine which is a more compact
notation, and which notation should be used for a given number.
https://github.com/rust-lang/rust/issues/24556 provides some pointers
into various rabbit holes for those interested.
This gist seems to be that currently a different formatting is not
exposed in rust directly, at least not for public consumption.
There is the
[lexical-core](https://github.com/Alexhuszagh/rust-lexical) crate
though, which provides a way to format floats with various strategies
and formats.
Change our implementation of `TotalDisplay` for the `Value::Float` case
to use that. We still need to do some post-processing, because Nix
always adds the sign in scientific notation (and there's no way to
configure lexical-core to do that), and lexical-core in some cases keeps
the trailing zeros.
Even with all that in place, there as a difference in `eval-okay-
fromjson.nix` (from tvix-tests), which I couldn't get to work. I updated
the fixture to a less problematic number.
With this, the testsuite passes again, and does for the upcoming CL
introducing builtins.fromTOML, and enabling the nix testsuite bits for
it, too.
Change-Id: Ie6fba5619e1d9fd7ce669a51594658b029057acc
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7922
Tested-by: BuildkiteCI
Autosubmit: flokli <flokli@flokli.de>
Reviewed-by: tazjin <tazjin@tvl.su>
2023-01-24 19:27:20 +01:00
|
|
|
// only. Except when it decides to use scientific notation
|
|
|
|
// (with a + after the `e`, and zero-padded to 0 digits)
|
2023-01-25 09:05:43 +01:00
|
|
|
Value::Float(num) => total_fmt_float(*num, f),
|
2022-08-10 19:01:23 +02:00
|
|
|
|
2022-08-09 17:49:05 +02:00
|
|
|
// internal types
|
2022-08-26 17:40:55 +02:00
|
|
|
Value::AttrNotFound => f.write_str("internal[not found]"),
|
2022-08-28 05:07:20 +02:00
|
|
|
Value::Blueprint(_) => f.write_str("internal[blueprint]"),
|
2022-08-28 15:59:08 +02:00
|
|
|
Value::DeferredUpvalue(_) => f.write_str("internal[deferred_upvalue]"),
|
2022-10-15 16:21:14 +02:00
|
|
|
Value::UnresolvedPath(_) => f.write_str("internal[unresolved_path]"),
|
2022-10-22 15:51:29 +02:00
|
|
|
|
|
|
|
// Delegate thunk display to the type, as it must handle
|
|
|
|
// the case of already evaluated or cyclic thunks.
|
|
|
|
Value::Thunk(t) => t.total_fmt(f, set),
|
2022-08-08 15:43:09 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-08-09 19:24:04 +02:00
|
|
|
|
2022-10-10 04:11:32 +02:00
|
|
|
impl From<bool> for Value {
|
|
|
|
fn from(b: bool) -> Self {
|
|
|
|
Value::Bool(b)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-08 21:20:27 +02:00
|
|
|
impl From<i64> for Value {
|
|
|
|
fn from(i: i64) -> Self {
|
|
|
|
Self::Integer(i)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-24 18:18:26 +01:00
|
|
|
impl From<f64> for Value {
|
|
|
|
fn from(i: f64) -> Self {
|
|
|
|
Self::Float(i)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-10 03:59:41 +02:00
|
|
|
impl From<PathBuf> for Value {
|
|
|
|
fn from(path: PathBuf) -> Self {
|
|
|
|
Self::Path(path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-01 22:50:27 +02:00
|
|
|
fn type_error(expected: &'static str, actual: &Value) -> ErrorKind {
|
|
|
|
ErrorKind::TypeError {
|
|
|
|
expected,
|
|
|
|
actual: actual.type_of(),
|
|
|
|
}
|
|
|
|
}
|
2022-09-18 19:22:02 +02:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2022-12-29 15:08:14 +01:00
|
|
|
use imbl::vector;
|
2022-09-18 19:22:02 +02:00
|
|
|
|
2023-01-25 12:16:55 +01:00
|
|
|
mod floats {
|
|
|
|
use crate::value::total_fmt_float;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn format_float() {
|
|
|
|
let ff = vec![
|
|
|
|
(0f64, "0"),
|
|
|
|
(1.0f64, "1"),
|
|
|
|
(-0.01, "-0.01"),
|
|
|
|
(5e+22, "5e+22"),
|
|
|
|
(1e6, "1e+06"),
|
|
|
|
(-2E-2, "-0.02"),
|
|
|
|
(6.626e-34, "6.626e-34"),
|
|
|
|
(9_224_617.445_991_228_313, "9.22462e+06"),
|
|
|
|
];
|
|
|
|
for (n, expected) in ff.iter() {
|
|
|
|
let mut buf = String::new();
|
|
|
|
let res = total_fmt_float(*n, &mut buf);
|
|
|
|
assert!(res.is_ok());
|
|
|
|
assert_eq!(
|
|
|
|
expected, &buf,
|
|
|
|
"{} should be formatted as {}, but got {}",
|
|
|
|
n, expected, &buf
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-18 20:04:40 +02:00
|
|
|
mod nix_eq {
|
2022-09-18 21:13:20 +02:00
|
|
|
use crate::observer::NoOpObserver;
|
|
|
|
|
2022-09-18 20:04:40 +02:00
|
|
|
use super::*;
|
|
|
|
use proptest::prelude::ProptestConfig;
|
|
|
|
use test_strategy::proptest;
|
|
|
|
|
|
|
|
#[proptest(ProptestConfig { cases: 5, ..Default::default() })]
|
|
|
|
fn reflexive(x: Value) {
|
2022-09-18 21:13:20 +02:00
|
|
|
let mut observer = NoOpObserver {};
|
2023-01-20 14:18:06 +01:00
|
|
|
let mut vm = VM::new(
|
|
|
|
Default::default(),
|
|
|
|
Box::new(crate::DummyIO),
|
|
|
|
&mut observer,
|
|
|
|
Default::default(),
|
|
|
|
);
|
2022-09-18 21:13:20 +02:00
|
|
|
|
|
|
|
assert!(x.nix_eq(&x, &mut vm).unwrap())
|
2022-09-18 20:04:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[proptest(ProptestConfig { cases: 5, ..Default::default() })]
|
|
|
|
fn symmetric(x: Value, y: Value) {
|
2022-09-18 21:13:20 +02:00
|
|
|
let mut observer = NoOpObserver {};
|
2023-01-20 14:18:06 +01:00
|
|
|
let mut vm = VM::new(
|
|
|
|
Default::default(),
|
|
|
|
Box::new(crate::DummyIO),
|
|
|
|
&mut observer,
|
|
|
|
Default::default(),
|
|
|
|
);
|
2022-09-18 21:13:20 +02:00
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
x.nix_eq(&y, &mut vm).unwrap(),
|
|
|
|
y.nix_eq(&x, &mut vm).unwrap()
|
|
|
|
)
|
2022-09-18 20:04:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[proptest(ProptestConfig { cases: 5, ..Default::default() })]
|
|
|
|
fn transitive(x: Value, y: Value, z: Value) {
|
2022-09-18 21:13:20 +02:00
|
|
|
let mut observer = NoOpObserver {};
|
2023-01-20 14:18:06 +01:00
|
|
|
let mut vm = VM::new(
|
|
|
|
Default::default(),
|
|
|
|
Box::new(crate::DummyIO),
|
|
|
|
&mut observer,
|
|
|
|
Default::default(),
|
|
|
|
);
|
2022-09-18 21:13:20 +02:00
|
|
|
|
|
|
|
if x.nix_eq(&y, &mut vm).unwrap() && y.nix_eq(&z, &mut vm).unwrap() {
|
|
|
|
assert!(x.nix_eq(&z, &mut vm).unwrap())
|
2022-09-18 20:04:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn list_int_float_fungibility() {
|
2022-09-18 21:13:20 +02:00
|
|
|
let mut observer = NoOpObserver {};
|
2023-01-20 14:18:06 +01:00
|
|
|
let mut vm = VM::new(
|
|
|
|
Default::default(),
|
|
|
|
Box::new(crate::DummyIO),
|
|
|
|
&mut observer,
|
|
|
|
Default::default(),
|
|
|
|
);
|
2022-09-18 21:13:20 +02:00
|
|
|
|
2022-12-29 13:50:19 +01:00
|
|
|
let v1 = Value::List(NixList::from(vector![Value::Integer(1)]));
|
|
|
|
let v2 = Value::List(NixList::from(vector![Value::Float(1.0)]));
|
2022-09-18 20:04:40 +02:00
|
|
|
|
2022-09-18 21:13:20 +02:00
|
|
|
assert!(v1.nix_eq(&v2, &mut vm).unwrap())
|
2022-09-18 19:22:02 +02:00
|
|
|
}
|
2022-09-18 20:04:40 +02:00
|
|
|
}
|
2022-09-18 19:22:02 +02:00
|
|
|
}
|