pklr 5.2.0

Pure Rust pkl configuration language parser and evaluator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
use rustc_hash::FxHashSet as HashSet;
use std::sync::{
    Arc,
    atomic::{AtomicU64, Ordering},
};

use indexmap::IndexMap;
use serde_json::json;

use crate::parser::{Expr, TypeExpr};

/// The members of an evaluated object, in declaration order. Keys are shared
/// names so copying members between objects and scopes does not allocate.
pub type ObjectMap = IndexMap<Arc<str>, Value, rustc_hash::FxBuildHasher>;

// `ObjectMap` is also the backing store for Pkl Mappings.  Keep non-string
// mapping keys disjoint from property names and from string keys that render
// alike (for example `1` and `"1"`).  The final component preserves the
// user-facing spelling for JSON/object rendering.
pub(crate) const MAPPING_KEY_PREFIX: &str = "\0pklr:mapping-key:";

// NaN does not equal itself, so each occurrence must be a different map key.
// This ID is internal-only: the stored key still renders from `display`.
static NEXT_NAN_MAPPING_KEY: AtomicU64 = AtomicU64::new(0);

pub(crate) fn mapping_storage_key(value: &Value) -> Option<Arc<str>> {
    let (kind, identity, display) = match value {
        Value::String(_) => return None,
        Value::Null => ("null", "0000000000000000".to_string(), "null".to_string()),
        Value::Bool(value) => (
            "bool",
            format!("{:016x}", u64::from(*value)),
            value.to_string(),
        ),
        Value::Int(value) => ("int", format!("{:016x}", *value as u64), value.to_string()),
        Value::Float(value) => {
            let identity = if *value == 0.0 { 0.0 } else { *value };
            (
                "float",
                format!("{:016x}", identity.to_bits()),
                value.to_string(),
            )
        }
        // Units compare in their smallest units. Keep that normalized amount
        // as identity, but retain the inserted spelling for `keys` and
        // converters.
        Value::Duration(value) => {
            let identity = value.value_in(DurationUnit::Nanos);
            let identity = if identity == 0.0 { 0.0 } else { identity };
            let identity = if identity.is_nan() {
                // Keep NaNs in a namespace which cannot collide with a finite
                // normalized amount.  Do not XOR the unit into the bits: that
                // can turn a NaN payload into a finite amount.
                format!(
                    "nan-{:02x}-{:016x}-{:016x}",
                    value.unit as u8,
                    value.value.to_bits(),
                    value.nan_identity,
                )
            } else {
                format!("finite-{:016x}", identity.to_bits())
            };
            (
                "duration",
                identity,
                format!("{}.{}", value.value, value.unit.symbol()),
            )
        }
        Value::DataSize(value) => {
            let identity = value.value_in(DataSizeUnit::Bytes);
            let identity = if identity == 0.0 { 0.0 } else { identity };
            let identity = if identity.is_nan() {
                format!(
                    "nan-{:02x}-{:016x}-{:016x}",
                    value.unit as u8,
                    value.value.to_bits(),
                    value.nan_identity,
                )
            } else {
                format!("finite-{:016x}", identity.to_bits())
            };
            (
                "dataSize",
                identity,
                format!("{}.{}", value.value, value.unit.symbol()),
            )
        }
        // Do not use derived `Debug` for compound keys. Native units carry an
        // internal NaN identity, and Debug would make two equal lists such as
        // `List(1.s)` acquire unrelated mapping identities.
        Value::List(value) => (
            "list",
            mapping_compound_identity(&Value::List(value.clone())),
            Value::List(value.clone()).to_json().to_string(),
        ),
        Value::Object(map, source) => (
            "object",
            mapping_object_identity(map, source.as_deref()),
            Value::Object(map.clone(), source.clone())
                .to_json()
                .to_string(),
        ),
        other => (
            "display",
            "0000000000000000".to_string(),
            format!("{other:?}"),
        ),
    };
    Some(format!("{MAPPING_KEY_PREFIX}{kind}:{identity}:{display}").into())
}

/// A typed, deterministic identity for a value used inside a compound mapping
/// key. This is intentionally narrower than Pkl's full value equality: the
/// fallback currently represents Lists, whose elements can include native
/// units and regexes that must not inherit implementation-only Debug fields.
fn mapping_compound_identity(value: &Value) -> String {
    match value {
        Value::Null => "null".into(),
        Value::Bool(value) => format!("bool:{value}"),
        Value::Int(value) => format!("int:{value}"),
        Value::Float(value) => format!("float:{:016x}", value.to_bits()),
        Value::String(value) => format!("string:{}:{value}", value.len()),
        Value::Duration(_) | Value::DataSize(_) => mapping_storage_key(value)
            .expect("native units have mapping keys")
            .to_string(),
        Value::Regex(value) => format!("regex:{}:{}", value.pattern().len(), value.pattern()),
        Value::List(items) => {
            let mut identity = format!("list:{:?}:[", items.kind());
            for item in items.iter() {
                let item = mapping_compound_identity(item);
                identity.push_str(&format!("{}:{item}", item.len()));
            }
            identity.push(']');
            identity
        }
        Value::Object(map, source) => mapping_object_identity(map, source.as_deref()),
        // Functions have identity semantics and are not structurally keyable.
        other => format!("debug:{other:?}"),
    }
}

fn mapping_object_identity(map: &ObjectMap, source: Option<&ObjectSource>) -> String {
    let mut members = map
        .iter()
        .map(|(key, value)| {
            let value = mapping_compound_identity(value);
            format!("{}:{key}:{}:{value}", key.len(), value.len())
        })
        .collect::<Vec<_>>();
    // Mapping and Dynamic equality compare members independent of declaration
    // order. Sorting also makes this identity independent of hash/map layout.
    members.sort_unstable();
    let kind = source.map_or_else(
        || "Dynamic".to_string(),
        |source| match source.kind {
            ObjectKind::Mapping => "Mapping".to_string(),
            // A class object and an instance intentionally share the class's
            // definition-site identity, but they are not equal Pkl values and
            // therefore must remain distinct when used as mapping keys.
            ObjectKind::Object => source.type_identity.as_deref().map_or_else(
                || "Dynamic".to_string(),
                |identity| format!("instance:{identity}"),
            ),
            ObjectKind::Class => source.type_identity.as_deref().map_or_else(
                || "Class".to_string(),
                |identity| format!("class:{identity}"),
            ),
        },
    );
    format!("object:{kind}:{}", members.join("|"))
}

/// Whether two storage keys name equal native-unit mapping keys. Their final
/// display component deliberately differs when equivalent units were spelled
/// differently at insertion and lookup time.
pub(crate) fn mapping_storage_keys_equal(a: &str, b: &str) -> bool {
    fn parts(key: &str) -> Option<(&str, &str)> {
        let key = key.strip_prefix(MAPPING_KEY_PREFIX)?;
        let (kind, rest) = key.split_once(':')?;
        let (identity, _) = rest.split_once(':')?;
        matches!(kind, "duration" | "dataSize").then_some((kind, identity))
    }
    parts(a).zip(parts(b)).is_some_and(|(a, b)| a == b)
}

pub(crate) fn display_storage_key(key: &str) -> &str {
    key.strip_prefix(MAPPING_KEY_PREFIX)
        .and_then(|key| key.rsplit_once(':').map(|(_, display)| display))
        .unwrap_or(key)
}

pub(crate) fn mapping_storage_value(key: &str) -> Value {
    let Some(key) = key.strip_prefix(MAPPING_KEY_PREFIX) else {
        return Value::String(key.into());
    };
    let Some((kind, rest)) = key.split_once(':') else {
        return Value::String(key.into());
    };
    let Some((identity, display)) = rest.split_once(':') else {
        return Value::String(key.into());
    };
    match kind {
        "null" => Value::Null,
        "bool" => display
            .parse()
            .map(Value::Bool)
            .unwrap_or_else(|_| Value::String(display.into())),
        "int" => display
            .parse()
            .map(Value::Int)
            .unwrap_or_else(|_| Value::String(display.into())),
        "float" => display
            .parse()
            .map(Value::Float)
            .unwrap_or_else(|_| Value::String(display.into())),
        "duration" => parse_unit_value(display, DurationUnit::parse)
            .map(|(value, unit)| {
                Value::Duration(Duration::with_mapping_identity(value, unit, identity))
            })
            .unwrap_or_else(|| Value::String(display.into())),
        "dataSize" => parse_unit_value(display, DataSizeUnit::parse)
            .map(|(value, unit)| {
                Value::DataSize(DataSize::with_mapping_identity(value, unit, identity))
            })
            .unwrap_or_else(|| Value::String(display.into())),
        _ => Value::String(display.into()),
    }
}

fn parse_unit_value<U>(display: &str, unit: impl FnOnce(&str) -> Option<U>) -> Option<(f64, U)> {
    let (value, unit_name) = display.rsplit_once('.')?;
    Some((value.parse().ok()?, unit(unit_name)?))
}

fn mapping_nan_identity(identity: &str) -> Option<(u64, u64)> {
    let mut parts = identity.strip_prefix("nan-")?.split('-');
    let _unit = parts.next()?;
    let bits = u64::from_str_radix(parts.next()?, 16).ok()?;
    let nonce = u64::from_str_radix(parts.next()?, 16).ok()?;
    parts.next().is_none().then_some((bits, nonce))
}

/// Captured lexical bindings. The same type as [`ObjectMap`], so a scope can
/// become an object (and back) without rebuilding it.
pub type ScopeMap = ObjectMap;

/// Type aliases captured with a scope. The types are shared so capturing a
/// scope does not copy every alias's type expression.
pub(crate) type TypeAliasMap = IndexMap<Arc<str>, Arc<TypeExpr>, rustc_hash::FxBuildHasher>;

/// A set of binding names, shared with the scopes they came from.
pub(crate) type NameSet = rustc_hash::FxHashSet<Arc<str>>;

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CapturedScope {
    pub values: ScopeMap,
    /// Names in `values` declared in a lexically enclosing body.
    pub declared: NameSet,
    /// Members declared by the body whose entries are evaluated in this scope,
    /// kept so an amendment that replaces one does not drop it from the body.
    pub body_members: HashSet<Arc<str>>,
    pub module_identities: IndexMap<String, String>,
    pub type_aliases: TypeAliasMap,
    pub type_namespace: Option<String>,
}

/// Captures the original AST entries and scope for an object, enabling
/// late binding: when this object is amended, its entries can be merged
/// with the overlay's entries and re-evaluated so that dependent
/// properties pick up overridden values.
#[derive(Debug, Clone, PartialEq)]
pub struct ObjectSource {
    pub(crate) entries: crate::parser::Body,
    /// The bindings visible where the object was defined (see
    /// [`ObjectSource::scope`]).
    pub(crate) captured: crate::eval::SourceScope,
    /// Members declared by the object's own definition body, including ones an
    /// amendment has since replaced.
    pub(crate) body_members: HashSet<Arc<str>>,
    /// Whether the class was declared `open` (allows adding new properties)
    pub(crate) is_open: bool,
    /// Whether the object is an `abstract` class, which can be extended but
    /// not instantiated.
    pub(crate) is_abstract: bool,
    /// The pkl class name this object was instantiated from (e.g., "Step", "Group").
    /// Used by `output.renderer.converters` to apply type-specific transforms.
    pub(crate) type_name: Option<String>,
    /// Stable definition-site identity used to distinguish same-named classes.
    pub(crate) type_identity: Option<String>,
    /// Parent class names, nearest first. Converters declared for a base class
    /// also apply to instances of its subclasses.
    pub(crate) parent_type_names: Vec<String>,
    /// Stable definition-site identities for parent classes, nearest first.
    pub(crate) parent_type_identities: Vec<String>,
    /// Lexical scopes for entries introduced by earlier amendments. `None`
    /// entries use this object's definition-site `scope`.
    pub(crate) entry_scopes: Vec<Option<Arc<CapturedScope>>>,
    /// Property names that produced values when this object was evaluated.
    /// Kept separate from `scope`, which can contain unrelated same-named
    /// lexical bindings.
    pub(crate) evaluated_properties: Vec<Arc<str>>,
    /// Bare element values of a Dynamic body, in source order. These are
    /// distinct from named properties and are consumed by `xml.Element`.
    pub(crate) elements: Vec<Value>,
    /// Possible value type names for mapping entries, e.g. `Step | Group` from
    /// `Mapping<String, Step | Group>`. Used when amending mappings so bare
    /// entries inherit the right class template.
    pub(crate) mapping_value_types: Vec<String>,
    /// Map of property name → optional deprecation message for properties
    /// annotated with `@Deprecated`. Consulted on field access so the
    /// warning fires when a deprecated property is *used*, not when the
    /// containing module is loaded. Crate-private: only the evaluator
    /// reads/writes this; not part of the public API.
    pub(crate) deprecated: IndexMap<String, Option<String>>,
    /// Members of a module object that failed to evaluate. Reading or
    /// instantiating such a member reports its error instead of treating it
    /// as absent, and rendering the module reports a failed output member.
    pub(crate) poisoned_members: Option<Arc<IndexMap<Arc<str>, PoisonedMember>>>,
    /// Whether this is a `Mapping`, a class, or another object.
    pub(crate) kind: ObjectKind,
    /// Whether this object was materialized from JSON rather than evaluated
    /// from a Pkl body. Such objects retain their evaluated members when
    /// amended, but still render as Dynamics.
    pub(crate) is_parsed_json: bool,
    /// For an instance of a class, the class's default object. An untyped
    /// `new { ... }` assigned to one of the instance's properties amends the
    /// class default of that property, not the receiver's current value.
    pub(crate) prototype: Option<Value>,
}

/// What an object with an [`ObjectSource`] is, beyond its members. Objects
/// of different kinds never compare equal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum ObjectKind {
    /// A `Dynamic` object, or an instance of the class in `type_name`.
    #[default]
    Object,
    /// A `Mapping`.
    Mapping,
    /// The class named by `type_name` itself, holding its defaults.
    Class,
}

/// A module member that failed to evaluate (see
/// [`ObjectSource::poisoned_members`]).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PoisonedMember {
    pub(crate) message: String,
    /// Whether the member is a property that rendering the module outputs.
    pub(crate) rendered: bool,
}

impl ObjectSource {
    /// The object's original body entries.
    pub fn entries(&self) -> &[crate::parser::Entry] {
        &self.entries
    }

    /// Whether the object's class was declared `open`.
    pub fn is_open(&self) -> bool {
        self.is_open
    }

    /// The pkl class this object was instantiated from, if any.
    pub fn type_name(&self) -> Option<&str> {
        self.type_name.as_deref()
    }

    /// Parent class names, nearest first.
    pub fn parent_type_names(&self) -> &[String] {
        &self.parent_type_names
    }

    /// The bindings visible where the object was defined.
    pub fn scope(&self) -> &ScopeMap {
        &self.captured.parts().values
    }

    /// Names in `scope` declared in a lexically enclosing body, which an
    /// inherited member of an inner object must not shadow.
    pub(crate) fn scope_declared(&self) -> &NameSet {
        &self.captured.parts().declared
    }

    /// Canonical module identities for imports captured in `scope`.
    pub(crate) fn scope_module_identities(&self) -> &IndexMap<String, String> {
        &self.captured.parts().module_identities
    }

    /// Type aliases captured alongside `scope` at the object's definition site.
    pub(crate) fn scope_type_aliases(&self) -> &TypeAliasMap {
        &self.captured.parts().type_aliases
    }

    /// Whether this source only carries metadata (failed module members, an
    /// abstract module marker, or a bare Mapping tag), with no entries to
    /// rebuild the object from on amendment.
    pub(crate) fn is_metadata_only(&self) -> bool {
        (self.poisoned_members.is_some()
            || self.is_abstract
            || (matches!(self.kind, ObjectKind::Mapping) && self.mapping_value_types.is_empty()))
            && self.entries.is_empty()
            && self.evaluated_properties.is_empty()
            && self.type_name.is_none()
    }
}

/// Which Pkl collection a [`Value::List`] is. All three render the same, but
/// they never equal each other, and a `Set` compares without regard to order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum ListKind {
    #[default]
    List,
    Listing,
    Set,
}

/// The items of a [`Value::List`] and which collection they form. Derefs to
/// the items.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ListValue {
    items: Arc<Vec<Value>>,
    kind: ListKind,
}

impl ListValue {
    pub fn new(kind: ListKind, items: impl Into<Arc<Vec<Value>>>) -> Self {
        ListValue {
            items: items.into(),
            kind,
        }
    }

    pub fn kind(&self) -> ListKind {
        self.kind
    }

    /// The same items as a collection of another kind.
    pub fn with_kind(mut self, kind: ListKind) -> Self {
        self.kind = kind;
        self
    }

    /// The address of the shared items, which identifies them while they are
    /// alive.
    pub(crate) fn items_ptr(&self) -> *const Vec<Value> {
        Arc::as_ptr(&self.items)
    }

    /// Mutable access to the items, copying them first if they are shared.
    pub fn make_mut(&mut self) -> &mut Vec<Value> {
        Arc::make_mut(&mut self.items)
    }
}

impl std::ops::Deref for ListValue {
    type Target = Vec<Value>;

    fn deref(&self) -> &Vec<Value> {
        &self.items
    }
}

/// A `List` of the given items.
impl From<Vec<Value>> for ListValue {
    fn from(items: Vec<Value>) -> Self {
        ListValue::new(ListKind::List, items)
    }
}

/// A `List` of the given items.
impl From<Arc<Vec<Value>>> for ListValue {
    fn from(items: Arc<Vec<Value>>) -> Self {
        ListValue::new(ListKind::List, items)
    }
}

/// A pkl runtime value.
///
/// Pkl's `Mapping` type (arbitrary key→value) is represented as `Object` when
/// keys are strings — which is the only case supported by JSON output. All
/// `new Mapping { ["key"] = ... }` expressions therefore produce `Object`.
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub enum Value {
    #[default]
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    /// Strings are shared so copying a string value does not allocate.
    String(Arc<str>),
    /// Object (ordered string-keyed map). Represents both pkl objects and
    /// string-keyed Mappings.  The optional [`ObjectSource`] stores the
    /// original entry definitions so late binding works on amendment.
    /// The map is Arc-wrapped so cloning a Value::Object is O(1).
    Object(Arc<ObjectMap>, Option<Arc<ObjectSource>>),
    /// A `List`, `Listing` or `Set` (see [`ListKind`]). The items are
    /// Arc-wrapped so cloning is O(1).
    List(ListValue),
    /// Lambda function: params, body and captured scope.
    /// The shared fields are Arc-wrapped so cloning a Lambda is O(1): lambdas are
    /// copied whenever a scope holding them is captured, and deep-copying the
    /// body each time dominated evaluation.
    Lambda(Arc<[String]>, Arc<Expr>, Arc<ScopeMap>),
    /// A compiled regular expression (`Regex(pattern)`).
    Regex(Arc<Regex>),
    /// A quantity of time (`5.min`).
    Duration(Duration),
    /// A quantity of digital information (`5.mb`).
    DataSize(DataSize),
}

/// The unit of a [`Duration`], smallest first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DurationUnit {
    Nanos,
    Micros,
    Millis,
    Seconds,
    Minutes,
    Hours,
    Days,
}

impl DurationUnit {
    pub const ALL: [DurationUnit; 7] = [
        DurationUnit::Nanos,
        DurationUnit::Micros,
        DurationUnit::Millis,
        DurationUnit::Seconds,
        DurationUnit::Minutes,
        DurationUnit::Hours,
        DurationUnit::Days,
    ];

    /// The unit's pkl name, as in `5.min`.
    pub fn symbol(self) -> &'static str {
        match self {
            DurationUnit::Nanos => "ns",
            DurationUnit::Micros => "us",
            DurationUnit::Millis => "ms",
            DurationUnit::Seconds => "s",
            DurationUnit::Minutes => "min",
            DurationUnit::Hours => "h",
            DurationUnit::Days => "d",
        }
    }

    /// The unit named `symbol`, if any.
    pub fn parse(symbol: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|unit| unit.symbol() == symbol)
    }

    /// Nanoseconds per unit.
    pub fn nanos(self) -> f64 {
        match self {
            DurationUnit::Nanos => 1.0,
            DurationUnit::Micros => 1e3,
            DurationUnit::Millis => 1e6,
            DurationUnit::Seconds => 1e9,
            DurationUnit::Minutes => 60e9,
            DurationUnit::Hours => 3600e9,
            DurationUnit::Days => 86400e9,
        }
    }
}

/// A pkl `Duration`. Like pkl, the value is kept as a float in its unit.
#[derive(Debug, Clone, Copy)]
pub struct Duration {
    pub value: f64,
    pub unit: DurationUnit,
    nan_identity: u64,
}

impl Duration {
    pub(crate) fn new(value: f64, unit: DurationUnit) -> Self {
        Self {
            value,
            unit,
            nan_identity: NEXT_NAN_MAPPING_KEY.fetch_add(1, Ordering::Relaxed),
        }
    }

    fn with_mapping_identity(value: f64, unit: DurationUnit, identity: &str) -> Self {
        let (value, nan_identity) = mapping_nan_identity(identity)
            .map(|(bits, nonce)| (f64::from_bits(bits), nonce))
            .unwrap_or_else(|| (value, NEXT_NAN_MAPPING_KEY.fetch_add(1, Ordering::Relaxed)));
        Self {
            value,
            unit,
            nan_identity,
        }
    }

    /// The value converted to `unit`.
    pub fn value_in(&self, unit: DurationUnit) -> f64 {
        self.value * self.unit.nanos() / unit.nanos()
    }
}

impl PartialEq for Duration {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value && self.unit == other.unit
    }
}

/// The unit of a [`DataSize`], smallest first, decimal before binary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DataSizeUnit {
    Bytes,
    Kilobytes,
    Kibibytes,
    Megabytes,
    Mebibytes,
    Gigabytes,
    Gibibytes,
    Terabytes,
    Tebibytes,
    Petabytes,
    Pebibytes,
}

impl DataSizeUnit {
    pub const ALL: [DataSizeUnit; 11] = [
        DataSizeUnit::Bytes,
        DataSizeUnit::Kilobytes,
        DataSizeUnit::Kibibytes,
        DataSizeUnit::Megabytes,
        DataSizeUnit::Mebibytes,
        DataSizeUnit::Gigabytes,
        DataSizeUnit::Gibibytes,
        DataSizeUnit::Terabytes,
        DataSizeUnit::Tebibytes,
        DataSizeUnit::Petabytes,
        DataSizeUnit::Pebibytes,
    ];

    /// The unit's pkl name, as in `5.mb`.
    pub fn symbol(self) -> &'static str {
        match self {
            DataSizeUnit::Bytes => "b",
            DataSizeUnit::Kilobytes => "kb",
            DataSizeUnit::Kibibytes => "kib",
            DataSizeUnit::Megabytes => "mb",
            DataSizeUnit::Mebibytes => "mib",
            DataSizeUnit::Gigabytes => "gb",
            DataSizeUnit::Gibibytes => "gib",
            DataSizeUnit::Terabytes => "tb",
            DataSizeUnit::Tebibytes => "tib",
            DataSizeUnit::Petabytes => "pb",
            DataSizeUnit::Pebibytes => "pib",
        }
    }

    /// The unit named `symbol`, if any.
    pub fn parse(symbol: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|unit| unit.symbol() == symbol)
    }

    /// Bytes per unit.
    pub fn bytes(self) -> i64 {
        match self {
            DataSizeUnit::Bytes => 1,
            DataSizeUnit::Kilobytes => 1000,
            DataSizeUnit::Kibibytes => 1024,
            DataSizeUnit::Megabytes => 1000_i64.pow(2),
            DataSizeUnit::Mebibytes => 1024_i64.pow(2),
            DataSizeUnit::Gigabytes => 1000_i64.pow(3),
            DataSizeUnit::Gibibytes => 1024_i64.pow(3),
            DataSizeUnit::Terabytes => 1000_i64.pow(4),
            DataSizeUnit::Tebibytes => 1024_i64.pow(4),
            DataSizeUnit::Petabytes => 1000_i64.pow(5),
            DataSizeUnit::Pebibytes => 1024_i64.pow(5),
        }
    }
}

/// A pkl `DataSize`. Like pkl, the value is kept as a float in its unit.
#[derive(Debug, Clone, Copy)]
pub struct DataSize {
    pub value: f64,
    pub unit: DataSizeUnit,
    nan_identity: u64,
}

impl DataSize {
    pub(crate) fn new(value: f64, unit: DataSizeUnit) -> Self {
        Self {
            value,
            unit,
            nan_identity: NEXT_NAN_MAPPING_KEY.fetch_add(1, Ordering::Relaxed),
        }
    }

    fn with_mapping_identity(value: f64, unit: DataSizeUnit, identity: &str) -> Self {
        let (value, nan_identity) = mapping_nan_identity(identity)
            .map(|(bits, nonce)| (f64::from_bits(bits), nonce))
            .unwrap_or_else(|| (value, NEXT_NAN_MAPPING_KEY.fetch_add(1, Ordering::Relaxed)));
        Self {
            value,
            unit,
            nan_identity,
        }
    }

    /// The value converted to `unit`.
    pub fn value_in(&self, unit: DataSizeUnit) -> f64 {
        self.value * self.unit.bytes() as f64 / unit.bytes() as f64
    }
}

impl PartialEq for DataSize {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value && self.unit == other.unit
    }
}

/// A pkl `Regex`: the pattern as written and its compiled form.
pub struct Regex {
    pattern: String,
    compiled: fancy_regex::Regex,
}

impl Regex {
    /// Compile `pattern`, returning the regex engine's message on a syntax error.
    pub fn new(pattern: &str) -> Result<Self, String> {
        let compiled = fancy_regex::RegexBuilder::new(&expand_quotes(pattern))
            .build()
            .map_err(|e| e.to_string())?;
        Ok(Self {
            pattern: pattern.to_string(),
            compiled,
        })
    }

    /// The pattern this regex was compiled from.
    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    pub(crate) fn compiled(&self) -> &fancy_regex::Regex {
        &self.compiled
    }
}

/// `pattern` with Java's `\Q...\E` quoted sections replaced by escaped
/// literals, which the Rust engine has no syntax for.
fn expand_quotes(pattern: &str) -> std::borrow::Cow<'_, str> {
    if !pattern.contains("\\Q") {
        return pattern.into();
    }
    let mut out = String::with_capacity(pattern.len());
    let mut rest = pattern;
    while let Some(i) = rest.find('\\') {
        out.push_str(&rest[..i]);
        let escaped = &rest[i + 1..];
        match escaped.chars().next() {
            Some('Q') => {
                let quoted = &escaped[1..];
                let (literal, after) = match quoted.find("\\E") {
                    Some(end) => (&quoted[..end], &quoted[end + 2..]),
                    None => (quoted, ""),
                };
                out.push_str(&fancy_regex::escape(literal));
                rest = after;
            }
            Some(c) => {
                out.push('\\');
                out.push(c);
                rest = &escaped[c.len_utf8()..];
            }
            None => {
                out.push('\\');
                rest = "";
            }
        }
    }
    out.push_str(rest);
    out.into()
}

impl std::fmt::Debug for Regex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Regex").field(&self.pattern).finish()
    }
}

/// Regexes are equal when their patterns are, as in pkl.
impl PartialEq for Regex {
    fn eq(&self, other: &Self) -> bool {
        self.pattern == other.pattern
    }
}

impl Value {
    /// The pkl class name of this value's type, as pkl reports it in errors.
    pub fn type_name(&self) -> &'static str {
        match self {
            Value::Null => "Null",
            Value::Bool(_) => "Boolean",
            Value::Int(_) => "Int",
            Value::Float(_) => "Float",
            Value::String(_) => "String",
            Value::Object(..) => "Dynamic",
            Value::List(_) => "List",
            Value::Lambda(params, ..) => match params.len() {
                0 => "Function0",
                1 => "Function1",
                2 => "Function2",
                3 => "Function3",
                4 => "Function4",
                _ => "Function5",
            },
            Value::Regex(_) => "Regex",
            Value::Duration(_) => "Duration",
            Value::DataSize(_) => "DataSize",
        }
    }

    /// Convert to JSON, failing like `pkl eval -f json` does on values JSON
    /// cannot represent.
    pub fn try_to_json(&self) -> Result<serde_json::Value, crate::Error> {
        let mut unrenderable = None;
        let json = self.json_checked(&mut unrenderable);
        match unrenderable {
            None => Ok(json),
            Some(value) => Err(value.json_render_error()),
        }
    }

    /// [`Value::to_json`], noting in `unrenderable` the first value inside
    /// that JSON cannot represent.
    fn json_checked<'a>(&'a self, unrenderable: &mut Option<&'a Value>) -> serde_json::Value {
        match self {
            Value::Float(f) if !f.is_finite() => {
                unrenderable.get_or_insert(self);
                serde_json::Value::Null
            }
            Value::Regex(_) | Value::Duration(_) | Value::DataSize(_) => {
                unrenderable.get_or_insert(self);
                serde_json::Value::Null
            }
            Value::Object(map, _) => {
                let mut obj = serde_json::Map::new();
                for (k, v) in map.iter() {
                    // The result is discarded once a value fails.
                    if unrenderable.is_some() {
                        break;
                    }
                    obj.insert(
                        display_storage_key(k).to_string(),
                        v.json_checked(unrenderable),
                    );
                }
                serde_json::Value::Object(obj)
            }
            Value::List(items) => {
                let mut array = Vec::with_capacity(items.len());
                for item in items.iter() {
                    if unrenderable.is_some() {
                        break;
                    }
                    array.push(item.json_checked(unrenderable));
                }
                serde_json::Value::Array(array)
            }
            _ => self.to_json(),
        }
    }

    /// pkl's error for rendering this value as JSON.
    fn json_render_error(&self) -> crate::Error {
        if let Value::Float(f) = self {
            return crate::Error::Eval(format!(
                "Cannot render value `{}` as JSON.",
                if f.is_nan() {
                    "NaN"
                } else if *f > 0.0 {
                    "∞"
                } else {
                    "-∞"
                }
            ));
        }
        crate::Error::Eval(format!(
            "Cannot render value of type `{}` as JSON.\nValue: {}",
            self.type_name(),
            crate::eval::stdlib::render_value(self)
        ))
    }

    /// Convert to JSON. Values JSON cannot represent become a tagged object
    /// (a `Regex` is `{"_type": "regex", "pattern": ...}`); see
    /// [`Value::try_to_json`] to reject them as `pkl eval -f json` does.
    pub fn to_json(&self) -> serde_json::Value {
        match self {
            Value::Null => serde_json::Value::Null,
            Value::Bool(b) => json!(b),
            Value::Int(n) => json!(n),
            Value::Float(f) => json!(f),
            Value::String(s) => serde_json::Value::String(s.to_string()),
            Value::Object(map, source) => {
                let mut obj = serde_json::Map::new();
                // Methods are stored as function-valued members, but are not
                // members of the object Pkl renders.
                let is_method = |name: &str| {
                    source.as_ref().is_some_and(|source| {
                        source.entries.iter().any(|entry| {
                            matches!(entry, crate::parser::Entry::Property(prop)
                                if prop.is_method && &*prop.name == name)
                        })
                    })
                };
                for (k, v) in map.iter() {
                    if matches!(v, Value::Lambda(..)) && is_method(k) {
                        continue;
                    }
                    obj.insert(display_storage_key(k).to_string(), v.to_json());
                }
                serde_json::Value::Object(obj)
            }
            Value::List(items) => {
                serde_json::Value::Array(items.iter().map(|v| v.to_json()).collect())
            }
            Value::Lambda(..) => json!("<lambda>"),
            Value::Regex(regex) => json!({ "_type": "regex", "pattern": regex.pattern() }),
            Value::Duration(_) | Value::DataSize(_) => {
                json!(crate::eval::stdlib::render_value(self))
            }
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        if let Value::String(s) = self {
            Some(s)
        } else {
            None
        }
    }

    pub fn as_object_mut(&mut self) -> Option<&mut ObjectMap> {
        if let Value::Object(m, _) = self {
            Some(Arc::make_mut(m))
        } else {
            None
        }
    }

    /// Merge `other` into `self`. For objects, other's keys win.
    pub fn merge(&mut self, other: Value) {
        match (self, other) {
            (Value::Object(base, _), Value::Object(overlay, _)) => {
                let base_map = Arc::make_mut(base);
                for (k, v) in overlay.iter() {
                    let storage_key = base_map
                        .get_key_value(k)
                        .map(|(key, _)| key.clone())
                        .or_else(|| {
                            base_map
                                .keys()
                                .find(|stored| mapping_storage_keys_equal(stored, k))
                                .cloned()
                        })
                        .unwrap_or_else(|| k.clone());
                    base_map.insert(storage_key, v.clone());
                }
            }
            (s, other) => *s = other,
        }
    }
}

impl From<serde_json::Value> for Value {
    fn from(v: serde_json::Value) -> Self {
        match v {
            serde_json::Value::Null => Value::Null,
            serde_json::Value::Bool(b) => Value::Bool(b),
            serde_json::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    Value::Int(i)
                } else {
                    Value::Float(n.as_f64().unwrap_or(f64::NAN))
                }
            }
            serde_json::Value::String(s) => Value::String(s.into()),
            serde_json::Value::Array(a) => {
                let items: Vec<Value> = a.into_iter().map(Value::from).collect();
                Value::List(ListValue::new(ListKind::Listing, items))
            }
            serde_json::Value::Object(o) => {
                let mut map = ObjectMap::default();
                for (k, v) in o {
                    map.insert(k.into(), Value::from(v));
                }
                Value::Object(Arc::new(map), None)
            }
        }
    }
}