1use 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::AddContext;
27use crate::errors::{CatchableErrorKind, ErrorKind};
28use crate::opcode::StackIdx;
29use crate::vm::generators::{self, GenCo};
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(NixAttrs),
54 List(NixList),
55
56 #[serde(skip)]
57 Closure(Rc<Closure>), #[serde(skip)]
60 Builtin(Builtin),
61
62 #[serde(skip_deserializing)]
65 Thunk(Thunk),
66
67 #[serde(skip)]
69 AttrNotFound,
70
71 #[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
117macro_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
139macro_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
152macro_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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
167pub struct CoercionKind {
168 pub strong: bool,
178
179 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
213pub enum PointerEquality {
214 ForbidAll,
216
217 AllowNested,
219
220 AllowAll,
222}
223
224impl Value {
225 pub fn attrs(attrs: NixAttrs) -> Self {
227 Self::Attrs(attrs)
228 }
229
230 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 async fn deep_force_(myself: Value, co: GenCo, span: Span) -> Result<Option<Value>, ErrorKind> {
244 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 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 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!("Snix 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 "Snix 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 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 let mut is_list_head = None;
330 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 (Value::String(mut s), _) => {
343 if let Some(ctx) = s.take_context() {
344 context.extend(*ctx);
345 }
346 Ok((*s).into())
347 }
348
349 (
355 Value::Path(p),
356 CoercionKind {
357 import_paths: true, ..
358 },
359 ) => {
360 let imported = generators::request_path_import(co, *p).await;
361 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 (Value::Attrs(attrs), kind) => {
381 if let Some(to_string) = attrs.select("__toString") {
382 let callable = to_string.clone().force(co, span).await?;
383
384 generators::request_stack_push(co, Value::Attrs(attrs.clone())).await;
387
388 let result = generators::request_call(co, callable).await;
390
391 vals.push(result);
395 continue;
396 } else if let Some(out_path) = attrs.select("outPath") {
397 vals.push(out_path.clone());
398 continue;
399 } else {
400 return Err(ErrorKind::NotCoercibleToString { from: "set", kind });
401 }
402 }
403
404 (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 Ok(format!("{f:.6}").into())
414 }
415
416 (Value::List(list), CoercionKind { strong: true, .. }) => {
418 for elem in list.into_iter().rev() {
419 vals.push(elem);
420 }
421 if is_list_head.is_none() {
425 is_list_head = Some(true);
426 }
427 continue;
428 }
429
430 (Value::Thunk(_), _) => panic!("Snix 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!("Snix 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 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 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 return Ok(Value::Bool(true));
504 };
505 let a = match a {
506 Value::Thunk(thunk) => {
507 if ptr_eq == PointerEquality::AllowAll
510 && let Value::Thunk(t1) = &b
511 && t1.ptr_eq(&thunk)
512 {
513 continue;
514 };
515
516 Thunk::force_(thunk, co, span).await?
517 }
518
519 _ => a,
520 };
521
522 let b = b.force(co, span).await?;
523
524 debug_assert!(!matches!(a, Value::Thunk(_)));
525 debug_assert!(!matches!(b, Value::Thunk(_)));
526
527 let result = match (a, b) {
528 (c @ Value::Catchable(_), _) => return Ok(c),
530 (_, c @ Value::Catchable(_)) => return Ok(c),
531 (Value::Null, Value::Null) => true,
532 (Value::Bool(b1), Value::Bool(b2)) => b1 == b2,
533 (Value::String(s1), Value::String(s2)) => s1 == s2,
534 (Value::Path(p1), Value::Path(p2)) => p1 == p2,
535
536 (Value::Integer(i1), Value::Integer(i2)) => i1 == i2,
538 (Value::Integer(i), Value::Float(f)) => i as f64 == f,
539 (Value::Float(f1), Value::Float(f2)) => f1 == f2,
540 (Value::Float(f), Value::Integer(i)) => i as f64 == f,
541
542 (Value::List(l1), Value::List(l2)) => {
544 if ptr_eq >= PointerEquality::AllowNested && l1.ptr_eq(&l2) {
545 continue;
546 }
547
548 if l1.len() != l2.len() {
549 return Ok(Value::Bool(false));
550 }
551
552 vals.extend(l1.into_iter().rev().zip(l2.into_iter().rev()).zip(
553 std::iter::repeat(std::cmp::max(ptr_eq, PointerEquality::AllowNested)),
554 ));
555 continue;
556 }
557
558 (_, Value::List(_)) | (Value::List(_), _) => return Ok(Value::Bool(false)),
559
560 (Value::Attrs(a1), Value::Attrs(a2)) => {
562 if ptr_eq >= PointerEquality::AllowNested && a1.ptr_eq(&a2) {
563 continue;
564 }
565
566 #[allow(clippy::single_match)] match (a1.select("type"), a2.select("type")) {
570 (Some(v1), Some(v2)) => {
571 let s1 = v1.clone().force(co, span).await?;
572 if s1.is_catchable() {
573 return Ok(s1);
574 }
575 let s2 = v2.clone().force(co, span).await?;
576 if s2.is_catchable() {
577 return Ok(s2);
578 }
579 let s1 = s1.to_str();
580 let s2 = s2.to_str();
581
582 if let (Ok(s1), Ok(s2)) = (s1, s2)
583 && s1 == "derivation"
584 && s2 == "derivation"
585 {
586 let out1 = a1
589 .select_required("outPath")
590 .context("comparing derivations")?
591 .clone();
592
593 let out2 = a2
594 .select_required("outPath")
595 .context("comparing derivations")?
596 .clone();
597
598 let out1 = out1.clone().force(co, span).await?;
599 let out2 = out2.clone().force(co, span).await?;
600
601 if out1.is_catchable() {
602 return Ok(out1);
603 }
604
605 if out2.is_catchable() {
606 return Ok(out2);
607 }
608
609 let result =
610 out1.to_contextful_str()? == out2.to_contextful_str()?;
611 if !result {
612 return Ok(Value::Bool(false));
613 } else {
614 continue;
615 }
616 }
617 }
618 _ => {}
619 };
620
621 if a1.len() != a2.len() {
622 return Ok(Value::Bool(false));
623 }
624
625 let iter1 = a1.into_iter_sorted().rev();
629 let iter2 = a2.into_iter_sorted().rev();
630 for ((k1, v1), (k2, v2)) in iter1.zip(iter2) {
631 vals.push((
632 (v1, v2),
633 std::cmp::max(ptr_eq, PointerEquality::AllowNested),
634 ));
635 vals.push((
636 (k1.into(), k2.into()),
637 std::cmp::max(ptr_eq, PointerEquality::AllowNested),
638 ));
639 }
640 continue;
641 }
642
643 (Value::Attrs(_), _) | (_, Value::Attrs(_)) => return Ok(Value::Bool(false)),
644
645 (Value::Closure(c1), Value::Closure(c2))
646 if ptr_eq >= PointerEquality::AllowNested && Rc::ptr_eq(&c1, &c2) =>
647 {
648 continue;
649 }
650
651 _ => return Ok(Value::Bool(false)),
654 };
655 if !result {
656 return Ok(Value::Bool(false));
657 }
658 }
659 }
660
661 pub fn type_of(&self) -> &'static str {
662 match self {
663 Value::Null => "null",
664 Value::Bool(_) => "bool",
665 Value::Integer(_) => "int",
666 Value::Float(_) => "float",
667 Value::String(_) => "string",
668 Value::Path(_) => "path",
669 Value::Attrs(_) => "set",
670 Value::List(_) => "list",
671 Value::Closure(_) | Value::Builtin(_) => "lambda",
672
673 Value::Thunk(_) => "internal[thunk]",
677 Value::AttrNotFound => "internal[attr_not_found]",
678 Value::Blueprint(_) => "internal[blueprint]",
679 Value::DeferredUpvalue(_) => "internal[deferred_upvalue]",
680 Value::UnresolvedPath(_) => "internal[unresolved_path]",
681 Value::FinaliseRequest(_) => "internal[finaliser_sentinel]",
682 Value::Catchable(_) => "internal[catchable]",
683 }
684 }
685
686 gen_cast!(as_bool, bool, "bool", Value::Bool(b), *b);
687 gen_cast!(as_int, i64, "int", Value::Integer(x), *x);
688 gen_cast!(as_float, f64, "float", Value::Float(x), *x);
689
690 pub fn to_str(&self) -> Result<NixString, ErrorKind> {
696 match self {
697 Value::String(s) if !s.has_context() => Ok((*s).clone()),
698 Value::Thunk(thunk) => Self::to_str(&thunk.value()),
699 other => Err(type_error("contextless strings", other)),
700 }
701 }
702
703 gen_cast!(
704 to_contextful_str,
705 NixString,
706 "contextful string",
707 Value::String(s),
708 (*s).clone()
709 );
710 gen_cast!(to_path, Box<PathBuf>, "path", Value::Path(p), p.clone());
711 gen_cast!(to_attrs, NixAttrs, "set", Value::Attrs(a), a.clone());
712 gen_cast!(to_list, NixList, "list", Value::List(l), l.clone());
713 gen_cast!(
714 as_closure,
715 Rc<Closure>,
716 "lambda",
717 Value::Closure(c),
718 c.clone()
719 );
720
721 gen_cast_mut!(as_list_mut, NixList, "list", List);
722
723 gen_is!(is_path, Value::Path(_));
724 gen_is!(is_number, Value::Integer(_) | Value::Float(_));
725 gen_is!(is_bool, Value::Bool(_));
726 gen_is!(is_attrs, Value::Attrs(_));
727 gen_is!(is_catchable, Value::Catchable(_));
728
729 pub fn is_thunk(&self) -> bool {
733 matches!(self, Self::Thunk(..))
734 }
735
736 pub async fn nix_cmp_ordering(
741 self,
742 other: Self,
743 co: GenCo,
744 span: Span,
745 ) -> Result<Result<Ordering, CatchableErrorKind>, ErrorKind> {
746 Self::nix_cmp_ordering_(self, other, co, span).await
747 }
748
749 async fn nix_cmp_ordering_(
750 myself: Self,
751 other: Self,
752 co: GenCo,
753 span: Span,
754 ) -> Result<Result<Ordering, CatchableErrorKind>, ErrorKind> {
755 let mut vals = vec![((myself, other), PointerEquality::ForbidAll)];
759
760 loop {
761 let ((mut a, mut b), ptr_eq) = if let Some(abp) = vals.pop() {
762 abp
763 } else {
764 return Ok(Ok(Ordering::Equal));
766 };
767 if ptr_eq == PointerEquality::AllowAll {
768 if a.clone()
769 .nix_eq(b.clone(), &co, PointerEquality::AllowAll, span)
770 .await?
771 .as_bool()?
772 {
773 continue;
774 }
775 a = a.force(&co, span).await?;
776 b = b.force(&co, span).await?;
777 }
778 let result = match (a, b) {
779 (Value::Catchable(c), _) => return Ok(Err(*c)),
780 (_, Value::Catchable(c)) => return Ok(Err(*c)),
781 (Value::Integer(i1), Value::Integer(i2)) => i1.cmp(&i2),
783 (Value::Float(f1), Value::Float(f2)) => f1.total_cmp(&f2),
784 (Value::String(s1), Value::String(s2)) => s1.cmp(&s2),
785 (Value::List(l1), Value::List(l2)) => {
786 let max = l1.len().max(l2.len());
787 for j in 0..max {
788 let i = max - 1 - j;
789 if i >= l2.len() {
790 vals.push(((1.into(), 0.into()), PointerEquality::ForbidAll));
791 } else if i >= l1.len() {
792 vals.push(((0.into(), 1.into()), PointerEquality::ForbidAll));
793 } else {
794 vals.push(((l1[i].clone(), l2[i].clone()), PointerEquality::AllowAll));
795 }
796 }
797 continue;
798 }
799
800 (Value::Integer(i1), Value::Float(f2)) => (i1 as f64).total_cmp(&f2),
802 (Value::Float(f1), Value::Integer(i2)) => f1.total_cmp(&(i2 as f64)),
803
804 (lhs, rhs) => {
806 return Err(ErrorKind::Incomparable {
807 lhs: lhs.type_of(),
808 rhs: rhs.type_of(),
809 });
810 }
811 };
812 if result != Ordering::Equal {
813 return Ok(Ok(result));
814 }
815 }
816 }
817
818 pub async fn force(self, co: &GenCo, span: Span) -> Result<Value, ErrorKind> {
820 if let Value::Thunk(thunk) = self {
821 return Thunk::force_(thunk, co, span).await;
823 }
824 Ok(self)
825 }
826
827 pub async fn force_owned_genco(self, co: GenCo, span: Span) -> Result<Value, ErrorKind> {
829 if let Value::Thunk(thunk) = self {
830 return Thunk::force_(thunk, &co, span).await;
832 }
833 Ok(self)
834 }
835
836 pub fn explain(&self) -> String {
839 match self {
840 Value::Null => "the 'null' value".into(),
841 Value::Bool(b) => format!("the boolean value '{b}'"),
842 Value::Integer(i) => format!("the integer '{i}'"),
843 Value::Float(f) => format!("the float '{f}'"),
844 Value::String(s) if s.has_context() => format!("the contextful string '{s}'"),
845 Value::String(s) => format!("the contextless string '{s}'"),
846 Value::Path(p) => format!("the path '{}'", p.to_string_lossy()),
847 Value::Attrs(attrs) => format!("a {}-item attribute set", attrs.len()),
848 Value::List(list) => format!("a {}-item list", list.len()),
849
850 Value::Closure(f) => {
851 if let Some(name) = &f.lambda.name {
852 format!("the user-defined Nix function '{name}'")
853 } else {
854 "a user-defined Nix function".to_string()
855 }
856 }
857
858 Value::Builtin(b) => {
859 let mut out = format!("the builtin function '{}'", b.name());
860 if let Some(docs) = b.documentation() {
861 out.push_str("\n\n");
862 out.push_str(docs);
863 }
864 out
865 }
866
867 Value::Thunk(t) => t.value().explain(),
869
870 Value::Catchable(_) => "a catchable failure".into(),
871
872 Value::AttrNotFound
873 | Value::Blueprint(_)
874 | Value::DeferredUpvalue(_)
875 | Value::UnresolvedPath(_)
876 | Value::FinaliseRequest(_) => "an internal Snix evaluator value".into(),
877 }
878 }
879
880 pub fn suspended_native_thunk(native: Box<dyn Fn() -> Result<Value, ErrorKind>>) -> Self {
883 Value::Thunk(Thunk::new_suspended_native(native))
884 }
885}
886
887trait TotalDisplay {
888 fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result;
889}
890
891impl Display for Value {
892 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
893 self.total_fmt(f, &mut Default::default())
894 }
895}
896
897fn total_fmt_float<F: std::fmt::Write>(num: f64, mut f: F) -> std::fmt::Result {
900 let mut buf = [b'0'; lexical_core::BUFFER_SIZE];
901 let mut s = lexical_core::write_with_options::<f64, { CXX_LITERAL }>(
902 num,
903 &mut buf,
904 &WRITE_FLOAT_OPTIONS,
905 );
906
907 let mut new_s = Vec::with_capacity(s.len());
911
912 if s.contains(&b'e') {
913 for (i, c) in s.iter().enumerate() {
914 if c == &b'e' {
916 if s.len() > i && s[i + 1].is_ascii_digit() {
918 new_s.extend_from_slice(&s[0..=i]);
920 new_s.push(b'+');
922 if s.len() == i + 2 {
925 new_s.push(b'0');
926 }
927 new_s.extend_from_slice(&s[i + 1..]);
928 break;
929 }
930 }
931 }
932
933 if !new_s.is_empty() {
935 s = &mut new_s
936 }
937 } else if s.contains(&b'.') {
938 for (i, c) in s.iter().enumerate() {
942 if c == &b'.' {
944 let frac = String::from_utf8_lossy(&s[i + 1..]);
946 let frac_no_trailing_zeroes = frac.trim_end_matches('0');
947
948 if frac.len() != frac_no_trailing_zeroes.len() {
949 if frac_no_trailing_zeroes.is_empty() {
951 new_s.extend_from_slice(&s[0..=i - 1]);
953 } else {
954 new_s.extend_from_slice(&s[0..=i]);
956 new_s.extend_from_slice(frac_no_trailing_zeroes.as_bytes());
957 }
958
959 s = &mut new_s;
961 break;
962 }
963 }
964 }
965 }
966
967 write!(f, "{}", String::from_utf8_lossy(s))
968}
969
970impl TotalDisplay for Value {
971 fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result {
972 match self {
973 Value::Null => f.write_str("null"),
974 Value::Bool(true) => f.write_str("true"),
975 Value::Bool(false) => f.write_str("false"),
976 Value::Integer(num) => write!(f, "{num}"),
977 Value::String(s) => s.fmt(f),
978 Value::Path(p) => p.display().fmt(f),
979 Value::Attrs(attrs) => attrs.total_fmt(f, set),
980 Value::List(list) => list.total_fmt(f, set),
981 Value::Closure(_) => f.write_str("<LAMBDA>"),
983 Value::Builtin(builtin) => builtin.fmt(f),
984
985 Value::Float(num) => total_fmt_float(*num, f),
989
990 Value::AttrNotFound => f.write_str("internal[not found]"),
992 Value::Blueprint(_) => f.write_str("internal[blueprint]"),
993 Value::DeferredUpvalue(_) => f.write_str("internal[deferred_upvalue]"),
994 Value::UnresolvedPath(_) => f.write_str("internal[unresolved_path]"),
995 Value::FinaliseRequest(_) => f.write_str("internal[finaliser_sentinel]"),
996
997 Value::Thunk(t) => t.total_fmt(f, set),
1000 Value::Catchable(_) => panic!("total_fmt() called on a CatchableErrorKind"),
1001 }
1002 }
1003}
1004
1005impl From<bool> for Value {
1006 fn from(b: bool) -> Self {
1007 Value::Bool(b)
1008 }
1009}
1010
1011impl From<i64> for Value {
1012 fn from(i: i64) -> Self {
1013 Self::Integer(i)
1014 }
1015}
1016
1017impl From<f64> for Value {
1018 fn from(i: f64) -> Self {
1019 Self::Float(i)
1020 }
1021}
1022
1023impl From<PathBuf> for Value {
1024 fn from(path: PathBuf) -> Self {
1025 Self::Path(Box::new(path))
1026 }
1027}
1028
1029fn type_error(expected: &'static str, actual: &Value) -> ErrorKind {
1030 ErrorKind::TypeError {
1031 expected,
1032 actual: actual.type_of(),
1033 }
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038 use super::*;
1039 use std::mem::size_of;
1040
1041 #[test]
1042 fn size() {
1043 assert_eq!(size_of::<Value>(), 16);
1044 }
1045
1046 mod floats {
1047 use crate::value::total_fmt_float;
1048
1049 #[test]
1050 fn format_float() {
1051 let ff = [
1052 (0f64, "0"),
1053 (1.0f64, "1"),
1054 (-0.01, "-0.01"),
1055 (5e+22, "5e+22"),
1056 (1e6, "1e+06"),
1057 (-2E-2, "-0.02"),
1058 (6.626e-34, "6.626e-34"),
1059 (9_224_617.445_991_227, "9.22462e+06"),
1060 ];
1061 for (n, expected) in ff.iter() {
1062 let mut buf = String::new();
1063 let res = total_fmt_float(*n, &mut buf);
1064 assert!(res.is_ok());
1065 assert_eq!(
1066 expected, &buf,
1067 "{} should be formatted as {}, but got {}",
1068 n, expected, &buf
1069 );
1070 }
1071 }
1072 }
1073}