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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
use super::*;

/// Collect `@Deprecated` annotations from a list of entries into a map of
/// property name → optional message. Used to populate `ObjectSource.deprecated`
/// so field access can warn lazily, instead of warning eagerly when a module
/// or object body is evaluated.
pub(super) fn collect_deprecated(entries: &[Entry]) -> IndexMap<String, Option<String>> {
    let mut out: IndexMap<String, Option<String>> = IndexMap::new();
    for entry in entries {
        if let Entry::Property(prop) = entry {
            for ann in &prop.annotations {
                if ann.name != "Deprecated" {
                    continue;
                }
                let mut message = None;
                for e in &ann.body {
                    if let Entry::Property(p) = e
                        && &*p.name == "message"
                        && let Some(Expr::String(s)) = &p.value
                    {
                        message = Some(s.to_string());
                    }
                }
                out.insert(prop.name.to_string(), message);
            }
        }
    }
    out
}

/// Combine a base deprecation map with any `@Deprecated` annotations on a
/// list of overlay entries, with overlay winning on conflict. Used by the
/// amend/merge code paths so an amended object's `ObjectSource.deprecated`
/// reflects deprecations from both the base and the overlay.
pub(super) fn merge_deprecated(
    base: &IndexMap<String, Option<String>>,
    overlay_entries: &[Entry],
) -> IndexMap<String, Option<String>> {
    let mut out = base.clone();
    for (k, v) in collect_deprecated(overlay_entries) {
        out.insert(k, v);
    }
    out
}

/// Resolve return-type aliases while their definition scope is available.
/// Value::Lambda captures values, so type aliases would otherwise be lost at
/// invocation. Keep inference errors lazy until the selected branch is called.
/// Whether [`capture_method_result_types`] would change `expr`.
pub(super) fn needs_method_result_types(expr: &Expr) -> bool {
    match expr {
        Expr::InferredNew(..) => true,
        Expr::If(_, then_expr, else_expr) => {
            needs_method_result_types(then_expr) || needs_method_result_types(else_expr)
        }
        Expr::Let(_, _, body) | Expr::Trace(body, _) => needs_method_result_types(body),
        _ => false,
    }
}

pub(super) fn capture_method_result_types(expr: &mut Expr, scope: &Scope) {
    match expr {
        Expr::InferredNew(ty, entries) => {
            *expr = match inferred_new_type(ty, scope, 0) {
                Ok((name, params)) => Expr::New(Some(name), std::mem::take(entries), params),
                Err(error) => Expr::Throw(Box::new(Expr::String(error.to_string().into()))),
            };
        }
        Expr::If(_, then_expr, else_expr) => {
            capture_method_result_types(then_expr, scope);
            capture_method_result_types(else_expr, scope);
        }
        Expr::Let(_, _, body) | Expr::Trace(body, _) => capture_method_result_types(body, scope),
        _ => {}
    }
}

/// Replace the type aliases a lambda body names with the types they stand for
/// in the scope that defines the lambda. Value::Lambda captures values only,
/// so an alias declared in an enclosing body or module would otherwise be
/// unknown when the lambda is called, and `x is Alias` would check against a
/// class or built-in of the same name instead. Names declared again by a
/// `typealias` or `class` in a body inside the lambda keep their inner meaning.
pub(super) fn capture_type_aliases(expr: &mut Expr, scope: &Scope) {
    AliasResolver {
        scope,
        expanding: Vec::new(),
    }
    .expr(expr, &HashSet::default());
}

struct AliasResolver<'a> {
    scope: &'a Scope,
    /// Aliases whose definitions are being expanded. An alias that names
    /// itself, directly or in a constraint, is left as written there.
    expanding: Vec<String>,
}

impl AliasResolver<'_> {
    fn expr(&mut self, expr: &mut Expr, shadowed: &HashSet<Name>) {
        match expr {
            Expr::Is(value, ty) | Expr::As(value, ty) => {
                self.expr(value, shadowed);
                self.ty(ty, shadowed);
            }
            Expr::InferredNew(ty, entries) => {
                self.ty(ty, shadowed);
                self.body(entries, shadowed);
            }
            Expr::New(_, entries, _) | Expr::ObjectBody(entries) => self.body(entries, shadowed),
            Expr::Field(value, _)
            | Expr::NullSafeField(value, _)
            | Expr::Unop(_, value)
            | Expr::Throw(value)
            | Expr::Trace(value, _)
            | Expr::Read(value, _)
            | Expr::ReadOrNull(value, _)
            | Expr::ReadGlob(value, _) => self.expr(value, shadowed),
            Expr::Lambda(_, value) => self.expr(Arc::make_mut(value), shadowed),
            Expr::Index(left, right) | Expr::Binop(_, left, right) | Expr::Let(_, left, right) => {
                self.expr(left, shadowed);
                self.expr(right, shadowed);
            }
            Expr::Call(callee, args) => {
                self.expr(callee, shadowed);
                for arg in args {
                    self.expr(arg, shadowed);
                }
            }
            Expr::If(cond, then_expr, else_expr) => {
                self.expr(cond, shadowed);
                self.expr(then_expr, shadowed);
                self.expr(else_expr, shadowed);
            }
            Expr::StringInterpolation(parts) => {
                for part in parts {
                    if let StringInterpPart::Expr(expr) = part {
                        self.expr(expr, shadowed);
                    }
                }
            }
            Expr::Null
            | Expr::Bool(_)
            | Expr::Int(_)
            | Expr::Float(_)
            | Expr::String(_)
            | Expr::Ident(_)
            | Expr::Import(..)
            | Expr::ImportGlob(..) => {}
        }
    }

    fn body(&mut self, entries: &mut crate::parser::Body, shadowed: &HashSet<Name>) {
        let declared = entries.iter().filter_map(|entry| match entry {
            Entry::TypeAlias(name, _) | Entry::ClassDef(name, ..) => Some(name),
            _ => None,
        });
        let mut inner_shadowed = None::<HashSet<Name>>;
        for name in declared {
            if !shadowed.contains(name.as_str()) {
                inner_shadowed
                    .get_or_insert_with(|| shadowed.clone())
                    .insert(Name::from(name.as_str()));
            }
        }
        let shadowed = inner_shadowed.as_ref().unwrap_or(shadowed);
        for entry in Arc::make_mut(entries) {
            self.entry(entry, shadowed);
        }
    }

    fn entry(&mut self, entry: &mut Entry, shadowed: &HashSet<Name>) {
        match entry {
            Entry::Property(prop) => {
                let prop = Arc::make_mut(prop);
                if let Some(ty) = &mut prop.type_ann {
                    self.ty(ty, shadowed);
                }
                if let Some(value) = &mut prop.value {
                    self.expr(value, shadowed);
                }
                if let Some(body) = &mut prop.body {
                    self.body(body, shadowed);
                }
            }
            Entry::DynProperty(key, value) | Entry::Predicate(key, value) => {
                self.expr(key, shadowed);
                self.expr(value, shadowed);
            }
            Entry::ForGenerator(generator) => {
                self.expr(&mut generator.collection, shadowed);
                self.body(&mut generator.body, shadowed);
            }
            Entry::WhenGenerator(generator) => {
                self.expr(&mut generator.condition, shadowed);
                self.body(&mut generator.body, shadowed);
                if let Some(else_body) = &mut generator.else_body {
                    self.body(else_body, shadowed);
                }
            }
            Entry::Spread(expr) | Entry::Elem(expr) => self.expr(expr, shadowed),
            Entry::ClassDef(_, _, _, body) => self.body(body, shadowed),
            Entry::TypeAlias(_, ty) => self.ty(ty, shadowed),
        }
    }

    /// The alias `name` stands for, fully resolved, unless it is shadowed
    /// where it is used or already being expanded.
    fn resolved_alias(
        &mut self,
        name: &str,
        shadowed: &HashSet<Name>,
    ) -> Option<crate::parser::TypeExpr> {
        if shadowed.contains(name) || self.expanding.iter().any(|n| n == name) {
            return None;
        }
        let mut ty = self.scope.get_type_alias(name)?.clone();
        self.expanding.push(name.to_string());
        // The definition belongs to the defining scope, where names the use
        // site redeclares still mean the enclosing aliases.
        self.ty(&mut ty, &HashSet::default());
        self.expanding.pop();
        Some(ty)
    }

    fn ty(&mut self, ty: &mut crate::parser::TypeExpr, shadowed: &HashSet<Name>) {
        use crate::parser::TypeExpr;
        match ty {
            TypeExpr::Named(name) => {
                let (default_marker, plain) = match name.strip_prefix('*') {
                    Some(plain) => ("*", plain),
                    None => ("", name.as_str()),
                };
                let Some(resolved) = self.resolved_alias(plain, shadowed) else {
                    return;
                };
                *ty = match resolved {
                    TypeExpr::Named(target) => TypeExpr::Named(format!("{default_marker}{target}")),
                    // Only a plain name can carry the union default marker.
                    resolved if default_marker.is_empty() => resolved,
                    _ => return,
                };
            }
            TypeExpr::Nullable(inner) => self.ty(inner, shadowed),
            TypeExpr::Union(types) | TypeExpr::Generic(_, types) => {
                for ty in types {
                    self.ty(ty, shadowed);
                }
            }
            TypeExpr::Constrained(base, constraint) => {
                self.expr(constraint, shadowed);
                let nullable = base.ends_with('?');
                let (default_marker, plain) = match base.trim_end_matches('?').strip_prefix('*') {
                    Some(plain) => ("*", plain),
                    None => ("", base.trim_end_matches('?')),
                };
                let Some(resolved) = self.resolved_alias(plain, shadowed) else {
                    return;
                };
                let (target, constraint_expr) = match resolved {
                    // `A(c)` with `A = B(c2)` checks `B`, then `c2`, then `c`,
                    // all against the same value. A nullable `A?` lets null
                    // skip `c2`, which a single conjunction cannot express.
                    TypeExpr::Constrained(target, inner) if !nullable || target.ends_with('?') => {
                        let outer = std::mem::replace(constraint.as_mut(), Expr::Null);
                        (target, Expr::Binop(BinOp::And, inner, Box::new(outer)))
                    }
                    TypeExpr::Constrained(..) => return,
                    resolved => match runtime_base_name(&resolved) {
                        Some(target) => {
                            (target, std::mem::replace(constraint.as_mut(), Expr::Null))
                        }
                        None => return,
                    },
                };
                let suffix = if nullable && !target.ends_with('?') {
                    "?"
                } else {
                    ""
                };
                *base = format!("{default_marker}{target}{suffix}");
                **constraint = constraint_expr;
            }
        }
    }
}

/// The name a constrained type stores for its base, for a type that has one.
fn runtime_base_name(ty: &crate::parser::TypeExpr) -> Option<String> {
    use crate::parser::TypeExpr;
    match ty {
        TypeExpr::Named(name) => Some(name.clone()),
        TypeExpr::Nullable(inner) => Some(format!("{}?", runtime_base_name(inner)?)),
        TypeExpr::Generic(name, args) => Some(format!(
            "{name}<{}>",
            args.iter()
                .map(runtime_base_name)
                .collect::<Option<Vec<_>>>()?
                .join(", ")
        )),
        TypeExpr::Union(_) | TypeExpr::Constrained(..) => None,
    }
}

/// Resolve an implicit method-result constructor without dropping generic
/// arguments or the default alternative of a union.
pub(super) fn inferred_new_type(
    ty: &crate::parser::TypeExpr,
    scope: &Scope,
    depth: usize,
) -> Result<(String, Vec<String>)> {
    use crate::parser::TypeExpr;
    if depth > 32 {
        return Err(Error::Eval("recursive inferred return type".into()));
    }
    match ty {
        TypeExpr::Nullable(inner) => inferred_new_type(inner, scope, depth + 1),
        TypeExpr::Named(name) => {
            let name = name.trim_start_matches('*');
            if let Some(alias) = scope.get_type_alias(name) {
                return inferred_new_type(alias, scope, depth + 1);
            }
            // Default union alternatives are stored as Named("*Type<...>").
            if name.contains('<') || name.ends_with('?') {
                let ty = crate::parser::parse_type_name(name)?;
                return inferred_new_type(&ty, scope, depth + 1);
            }
            Ok((name.to_string(), Vec::new()))
        }
        TypeExpr::Generic(name, args) => Ok((
            name.trim_start_matches('*').to_string(),
            args.iter()
                .enumerate()
                .flat_map(|(index, arg)| {
                    // The mapping constructor reserves one slot for its key
                    // type, followed by all value-type alternatives.
                    if index == 0 && matches!(name.as_str(), "Mapping" | "Map") {
                        return vec![display_type_expr(arg)];
                    }
                    let mut names = Vec::new();
                    collect_type_expr_class_names(arg, scope, &mut names, 0);
                    names
                })
                .collect(),
        )),
        TypeExpr::Union(types) => {
            let selected = types
                .iter()
                .find(|ty| is_default_type(ty))
                .ok_or_else(|| Error::Eval("Cannot tell which parent to amend".into()))?;
            inferred_new_type(selected, scope, depth + 1)
        }
        TypeExpr::Constrained(name, _) => {
            // Constraints store the underlying type as a runtime name. Parse
            // that name back into a type to retain any generic arguments.
            let ty = crate::parser::parse_type_name(name.trim_start_matches('*'))?;
            inferred_new_type(&ty, scope, depth + 1)
        }
    }
}

pub(super) fn type_default_value(ty: &crate::parser::TypeExpr, scope: &Scope) -> Option<Value> {
    use crate::parser::TypeExpr;
    match ty {
        TypeExpr::Constrained(base, _) if base.ends_with('?') => Some(Value::Null),
        TypeExpr::Constrained(base, _) => type_default_for_name(base, scope),
        TypeExpr::Nullable(_) => Some(Value::Null),
        TypeExpr::Named(name) if name == "Null" => Some(Value::Null),
        TypeExpr::Named(name) => {
            if let Some(value) = string_literal_type_value(name) {
                return Some(Value::String(value.into()));
            }
            if let Some(alias) = scope.get_type_alias(name).cloned() {
                return type_default_value(&alias, scope);
            }
            type_default_for_name(name, scope)
        }
        TypeExpr::Generic(name, _) => match name.as_str() {
            "Collection" | "List" | "Set" | "Listing" => Some(empty_collection(name)),
            "Mapping" => Some(Value::Object(
                Arc::default(),
                Some(Arc::new(mapping_source())),
            )),
            "Map" => Some(Value::Object(Arc::default(), None)),
            _ => resolve_dotted(scope, name).map(as_instance),
        },
        TypeExpr::Union(variants) => variants
            .iter()
            .find(|ty| is_default_type(ty))
            .and_then(|ty| type_default_value(ty, scope)),
    }
}

/// The deferred error of a class requested as an implicit property default.
/// This deliberately follows only the branch [`type_default_value`] selects:
/// nullable and built-in collection defaults remain non-fallible, while a
/// poisoned user class (including through an alias) reports its original
/// error when the property is actually evaluated.
pub(super) fn type_default_error(ty: &crate::parser::TypeExpr, scope: &Scope) -> Option<String> {
    fn named_error(name: &str, scope: &Scope, seen: &mut Vec<String>) -> Option<String> {
        let name = name.trim_start_matches('*').trim_end_matches('?');
        let base = name.split('<').next().unwrap_or(name);
        if let Some(alias) = scope.get_type_alias(base) {
            if seen.iter().any(|seen| seen == base) {
                return None;
            }
            seen.push(base.to_string());
            let error = visit(alias, scope, seen);
            seen.pop();
            return error;
        }
        // A qualified class can be absent from an imported module's rendered
        // map because evaluating its definition failed. Walk the dotted path
        // so its ObjectSource poison is still reported when this default is
        // actually materialized.
        poisoned_member(scope, base)
    }

    fn visit(
        ty: &crate::parser::TypeExpr,
        scope: &Scope,
        seen: &mut Vec<String>,
    ) -> Option<String> {
        use crate::parser::TypeExpr;

        match ty {
            TypeExpr::Constrained(base, _) if !base.ends_with('?') => {
                named_error(base, scope, seen)
            }
            TypeExpr::Constrained(..) | TypeExpr::Nullable(_) => None,
            TypeExpr::Named(name) if name != "Null" => named_error(name, scope, seen),
            TypeExpr::Named(_) => None,
            TypeExpr::Generic(name, _) => match name.as_str() {
                "Collection" | "List" | "Set" | "Listing" | "Mapping" | "Map" => None,
                _ => named_error(name, scope, seen),
            },
            TypeExpr::Union(variants) => variants
                .iter()
                .find(|variant| is_default_type(variant))
                .and_then(|variant| visit(variant, scope, seen)),
        }
    }

    visit(ty, scope, &mut Vec::new())
}

pub(super) fn type_default_for_name(name: &str, scope: &Scope) -> Option<Value> {
    let name = name.trim_start_matches('*').trim_end_matches('?');
    let base_name = name.split('<').next().unwrap_or(name);
    // A class declaration shadows the built-in type with the same name.
    // Check it before the built-in default cases, whose scope bindings are
    // marker strings rather than class objects.
    if let Some(value) = resolve_dotted(scope, base_name)
        && matches!(&value, Value::Object(_, Some(source)) if source.kind == ObjectKind::Class)
    {
        return Some(as_instance(value));
    }
    match base_name {
        "Null" => Some(Value::Null),
        "Collection" | "List" | "Set" | "Listing" => Some(empty_collection(base_name)),
        "Mapping" => Some(Value::Object(
            Arc::default(),
            Some(Arc::new(mapping_source())),
        )),
        "Map" => Some(Value::Object(Arc::default(), None)),
        "String" | "Boolean" | "Bool" | "Int" | "Float" | "Number" | "Any" | "Dynamic"
        | "Duration" | "DataSize" | "Pair" | "Regex" => None,
        other => resolve_dotted(scope, other).map(as_instance),
    }
}

/// An empty value of the collection type `name`.
fn empty_collection(name: &str) -> Value {
    let kind = match name {
        "Listing" => ListKind::Listing,
        "Set" => ListKind::Set,
        _ => ListKind::List,
    };
    Value::List(ListValue::new(kind, Vec::new()))
}

pub(super) fn nullable_inner_default(ty: &crate::parser::TypeExpr, scope: &Scope) -> Option<Value> {
    use crate::parser::TypeExpr;
    match ty {
        TypeExpr::Nullable(inner) => type_default_value(inner, scope),
        TypeExpr::Constrained(name, _) if name.ends_with('?') => {
            type_default_for_name(name.trim_end_matches('?'), scope)
        }
        _ => None,
    }
}

pub(super) fn type_is_listing(ty: &crate::parser::TypeExpr) -> bool {
    use crate::parser::TypeExpr;
    match ty {
        TypeExpr::Named(name) | TypeExpr::Generic(name, _) => name == "Listing",
        TypeExpr::Nullable(inner) => type_is_listing(inner),
        TypeExpr::Constrained(name, _) => {
            name.trim_end_matches('?') == "Listing" || name.starts_with("Listing<")
        }
        TypeExpr::Union(variants) => variants.iter().any(type_is_listing),
    }
}

/// `Any` (optionally nullable) gives an untyped `new` no parent to infer.
pub(super) fn type_is_any(ty: &crate::parser::TypeExpr) -> bool {
    use crate::parser::TypeExpr;
    match ty {
        TypeExpr::Named(name) => name == "Any",
        TypeExpr::Nullable(inner) => type_is_any(inner),
        _ => false,
    }
}

/// Whether `entries`, including generator bodies, define a named member.
pub(super) fn entries_define_members(entries: &[Entry]) -> bool {
    entries.iter().any(|entry| match entry {
        Entry::Property(prop) => !has_modifier(&prop.modifiers, crate::parser::Modifier::Local),
        Entry::DynProperty(..) => true,
        Entry::ForGenerator(generator) => entries_define_members(&generator.body),
        Entry::WhenGenerator(generator) => {
            entries_define_members(&generator.body)
                || generator
                    .else_body
                    .as_deref()
                    .is_some_and(|body| entries_define_members(body))
        }
        _ => false,
    })
}

pub(super) fn entries_are_listing_amendment(entries: &[Entry]) -> bool {
    entries.iter().any(|entry| match entry {
        Entry::Elem(_) => true,
        Entry::ForGenerator(generator) => entries_are_listing_amendment(&generator.body),
        Entry::WhenGenerator(generator) => {
            entries_are_listing_amendment(&generator.body)
                || generator
                    .else_body
                    .as_deref()
                    .is_some_and(|body| entries_are_listing_amendment(body))
        }
        _ => false,
    })
}

pub(super) fn resolve_dotted(scope: &Scope, name: &str) -> Option<Value> {
    let parts: Vec<&str> = name.split('.').collect();
    let mut val = scope.get(parts[0])?.clone();
    for part in &parts[1..] {
        val = match val {
            Value::Object(ref map, _) => map.get(*part)?.clone(),
            _ => return None,
        };
    }
    Some(val)
}

pub(super) fn has_modifier(mods: &[Modifier], target: Modifier) -> bool {
    mods.contains(&target)
}

/// The error for assigning or amending an inherited `const` or `fixed`
/// property without redeclaring that modifier.
pub(super) fn immutable_member_error(prop: &Property, inherited: &Property) -> Option<String> {
    if prop.value.is_none() && prop.body.is_none() {
        return None;
    }
    let verb = if prop.value.is_some() {
        "assign to"
    } else {
        "amend"
    };
    [(Modifier::Const, "const"), (Modifier::Fixed, "fixed")]
        .into_iter()
        .find(|(modifier, _)| {
            has_modifier(&inherited.modifiers, modifier.clone())
                && !has_modifier(&prop.modifiers, modifier.clone())
        })
        .map(|(_, kind)| format!("Cannot {verb} {kind} property `{}`.", prop.name))
}

pub(super) fn should_render_property_value(prop: &Property, value: &Value) -> bool {
    prop.value.is_some() || prop.body.is_some() || !matches!(value, Value::Null)
}

pub(super) fn module_is_abstract(module: &Module) -> bool {
    module
        .annotations
        .iter()
        .any(|annotation| annotation.name == "pklr:module:Abstract")
}

pub(super) fn is_unresolved_template_error(message: &str) -> bool {
    message.contains("undefined variable")
        || message.contains("field not found")
        || message.starts_with("Cannot find property")
}

/// Pkl's error for reading `name` from an object that has no such member:
/// the object `obj_expr` evaluated to, described by `source`.
/// `module_names` maps module identities to the names the modules declare.
pub(super) fn missing_property_message(
    source: &Option<Arc<ObjectSource>>,
    obj_expr: &Expr,
    name: &str,
    scope: &Scope,
    module_names: &HashMap<String, String>,
) -> String {
    if let Expr::Ident(root) = obj_expr
        && let Some(identity) = scope.module_identity(root)
    {
        return format!(
            "Cannot find property `{name}` in module `{}`.",
            module_name_of(identity, module_names)
        );
    }
    format!(
        "Cannot find property `{name}` in object of type `{}`.",
        object_class_name(source.as_deref(), Some(module_names))
    )
}

/// The name Pkl gives the class of an object `source` describes: `Dynamic`,
/// or `module#Class` for an instance of a class.
fn object_class_name(
    source: Option<&ObjectSource>,
    module_names: Option<&HashMap<String, String>>,
) -> String {
    match source {
        Some(ObjectSource {
            type_name: Some(class),
            type_identity,
            ..
        }) => match type_identity
            .as_deref()
            .and_then(|identity| identity.strip_suffix(class.as_str())?.strip_suffix('.'))
        {
            Some(module) => {
                let module = module_names
                    .and_then(|names| names.get(module).map(String::as_str))
                    .unwrap_or_else(|| {
                        let file = module.rsplit(['/', '\\']).next().unwrap_or(module);
                        file.strip_suffix(".pkl").unwrap_or(file)
                    });
                format!("{module}#{class}")
            }
            None => class.clone(),
        },
        _ => "Dynamic".to_string(),
    }
}

/// The name of `value`'s class as Pkl writes it in error messages.
pub(super) fn pkl_class_name(value: &Value) -> String {
    match value {
        Value::Object(_, source) => object_class_name(source.as_deref(), None),
        Value::List(items) => match items.kind() {
            ListKind::List => "List".to_string(),
            ListKind::Listing => "Listing".to_string(),
            ListKind::Set => "Set".to_string(),
        },
        Value::Lambda(params, ..) => format!("Function{}", params.len()),
        Value::Bool(_) => "Boolean".to_string(),
        value => value_type_name(value).to_string(),
    }
}

/// `value` written on one line as Pkl writes values in error messages.
pub(super) fn pkl_value_text(value: &Value) -> String {
    match value {
        Value::String(s) => format!("{s:?}"),
        Value::List(items) => format!(
            "List({})",
            items
                .iter()
                .map(pkl_value_text)
                .collect::<Vec<_>>()
                .join(", ")
        ),
        Value::Object(map, source) => {
            let class = object_class_name(source.as_deref(), None);
            let class = class.rsplit('#').next().unwrap_or(&class);
            if map.is_empty() {
                return format!("new {class} {{}}");
            }
            let members = map
                .iter()
                .map(|(name, value)| {
                    format!(
                        "{} = {}",
                        crate::value::display_storage_key(name),
                        pkl_value_text(value)
                    )
                })
                .collect::<Vec<_>>();
            format!("new {class} {{ {} }}", members.join("; "))
        }
        Value::Lambda(params, ..) => format!("new Function{} {{}}", params.len()),
        value => value_to_display(value),
    }
}

/// The name of the module with identity `uri`: the one it declares, or else
/// its file name without the extension.
fn module_name_of<'a>(uri: &'a str, module_names: &'a HashMap<String, String>) -> &'a str {
    if let Some(name) = module_names.get(uri) {
        return name;
    }
    let file = uri.rsplit(['/', '\\']).next().unwrap_or(uri);
    file.strip_suffix(".pkl").unwrap_or(file)
}

/// Which body the entry at `index` of a (possibly merged) object body was
/// written in: entries of one amendment share their captured scope.
pub(super) fn entry_layer(
    entry_scopes: Option<&[Option<Arc<CapturedScope>>]>,
    index: usize,
) -> usize {
    entry_scopes
        .and_then(|scopes| scopes.get(index)?.as_ref())
        .map_or(0, |scope| Arc::as_ptr(scope) as usize)
}

/// Record the members a generator produced in body `layer`. A body may
/// define each member only once, so a member its generators already
/// produced is an error. `body` is the generator's body, which tells
/// properties from entries for the message.
pub(super) fn record_generated_members(
    seen: &mut HashSet<(usize, Arc<str>)>,
    layer: usize,
    members: &ObjectMap,
    body: &[Entry],
    mapping_entries: bool,
) -> Result<()> {
    for name in members.keys() {
        let duplicate = mapping_entries
            && seen.iter().any(|(seen_layer, seen_name)| {
                *seen_layer == layer && crate::value::mapping_storage_keys_equal(seen_name, name)
            });
        if duplicate || !seen.insert((layer, name.clone())) {
            let is_property = body
                .iter()
                .any(|entry| matches!(entry, Entry::Property(prop) if *prop.name == **name));
            let name = if is_property {
                name.to_string()
            } else {
                format!("{:?}", crate::value::display_storage_key(name))
            };
            return Err(Error::Eval(format!(
                "Duplicate definition of member `{name}`."
            )));
        }
    }
    Ok(())
}

pub(super) fn require_str_arg<'a>(args: &'a [Value], idx: usize, method: &str) -> Result<&'a str> {
    match args.get(idx) {
        Some(Value::String(s)) => Ok(&**s),
        Some(other) => Err(Error::Eval(format!(
            "{method}() requires a String argument, got {}",
            value_type_name(other)
        ))),
        None => Err(Error::Eval(format!(
            "{method}() requires {} argument(s)",
            idx + 1
        ))),
    }
}

pub(super) fn value_type_name(v: &Value) -> &'static str {
    match v {
        Value::Null => "Null",
        Value::Bool(_) => "Boolean",
        Value::Int(_) => "Int",
        Value::Float(_) => "Float",
        Value::String(_) => "String",
        Value::Regex(_) => "Regex",
        Value::Object(..) => "Object",
        Value::List(_) => "List",
        Value::Lambda(..) => "Function",
        Value::Duration(_) => "Duration",
        Value::DataSize(_) => "DataSize",
    }
}

pub(super) fn value_to_key(v: &Value) -> Result<Arc<str>> {
    // Render directives need their text-preserving representation for
    // renderer dispatch. Other compound keys keep main's typed storage so
    // List kind and class identity remain distinct.
    if super::render::kind_of(v) == super::render::Kind::RenderDirective {
        return Ok(super::render::object_key(v));
    }
    if let Some(key) = crate::value::mapping_storage_key(v) {
        return Ok(key);
    }
    match v {
        Value::String(s) => Ok(Arc::clone(s)),
        Value::Int(_) | Value::Bool(_) | Value::Float(_) => unreachable!(),
        Value::Object(_, _)
        | Value::List(_)
        | Value::Lambda(..)
        | Value::Regex(_)
        | Value::Duration(_)
        | Value::DataSize(_)
        | Value::Null => Ok(value_to_display(v).into()),
    }
}

pub(super) fn value_to_display(v: &Value) -> String {
    match v {
        Value::String(s) => s.to_string(),
        Value::Object(map, Some(source))
            if source.type_identity.as_deref() == Some("pkl:base#RegexMatch") =>
        {
            map.get("value").map(value_to_display).unwrap_or_default()
        }
        _ => super::stdlib::render_value(v),
    }
}

pub(super) fn string_literal_type_value(name: &str) -> Option<&str> {
    name.strip_prefix('*')
        .unwrap_or(name)
        .strip_prefix('"')?
        .strip_suffix('"')
}

pub(super) fn is_default_type(ty: &crate::parser::TypeExpr) -> bool {
    matches!(ty, crate::parser::TypeExpr::Named(name) if name.starts_with('*'))
}

/// Format a TypeExpr for user-facing error messages.
pub(super) fn display_type_expr(ty: &crate::parser::TypeExpr) -> String {
    use crate::parser::TypeExpr;
    match ty {
        TypeExpr::Named(name) => name.clone(),
        TypeExpr::Nullable(inner) => format!("{}?", display_type_expr(inner)),
        TypeExpr::Union(variants) => variants
            .iter()
            .map(display_type_expr)
            .collect::<Vec<_>>()
            .join("|"),
        TypeExpr::Generic(name, args) => {
            let args_str: Vec<_> = args.iter().map(display_type_expr).collect();
            format!("{}<{}>", name, args_str.join(", "))
        }
        TypeExpr::Constrained(base, _) => format!("{base}(... )"),
    }
}

/// Check if a value matches a Pkl type expression (non-constrained types only).
/// For constrained types, use `Evaluator::eval_type_check` instead.
pub(super) fn value_is_type(val: &Value, ty: &crate::parser::TypeExpr) -> bool {
    use crate::parser::TypeExpr;
    match ty {
        TypeExpr::Named(name) if string_literal_type_value(name).is_some() => {
            matches!(val, Value::String(actual) if Some(&**actual) == string_literal_type_value(name))
        }
        TypeExpr::Named(name) => match name.strip_prefix('*').unwrap_or(name) {
            "Null" => is_null_value(val),
            "Boolean" | "Bool" => matches!(val, Value::Bool(_)),
            "Int" => matches!(val, Value::Int(_)),
            "Float" => matches!(val, Value::Float(_)),
            "Number" => matches!(val, Value::Int(_) | Value::Float(_)),
            "String" => matches!(val, Value::String(_)),
            "Regex" => matches!(val, Value::Regex(_)),
            "List" | "Listing" | "Set" => matches!(val, Value::List(_)),
            "Map" | "Mapping" | "Object" | "Dynamic" => matches!(val, Value::Object(..)),
            "Function" => matches!(val, Value::Lambda(..)),
            "Duration" => matches!(val, Value::Duration(_)),
            "DataSize" => matches!(val, Value::DataSize(_)),
            "Any" => true,
            _ => {
                // Unknown type name -- could be a class; treat objects as matching
                matches!(val, Value::Object(..))
            }
        },
        TypeExpr::Nullable(inner) => is_null_value(val) || value_is_type(val, inner),
        TypeExpr::Union(variants) => variants.iter().any(|v| value_is_type(val, v)),
        TypeExpr::Generic(name, _) => {
            // Check the base type, ignore type parameters
            match name.as_str() {
                "List" | "Listing" | "Set" => matches!(val, Value::List(_)),
                "Map" | "Mapping" => matches!(val, Value::Object(..)),
                "Regex" => matches!(val, Value::Regex(_)),
                "Function" | "Function0" | "Function1" | "Function2" | "Function3"
                | "Function4" | "Function5" => matches!(val, Value::Lambda(..)),
                _ => matches!(val, Value::Object(..)),
            }
        }
        TypeExpr::Constrained(base, _) => {
            // Just check the base type; constraint requires async eval
            value_is_named_type(val, base)
        }
    }
}

pub(super) fn value_is_named_type(val: &Value, name: &str) -> bool {
    if name.ends_with('?') && is_null_value(val) {
        return true;
    }
    value_is_type(
        val,
        &crate::parser::TypeExpr::Named(
            name.trim_end_matches('?')
                .split('<')
                .next()
                .unwrap_or(name)
                .to_string(),
        ),
    )
}

/// Check a value against a user-defined class that is available in scope.
///
/// Class defaults and instances carry their concrete class and parent class
/// names in `ObjectSource`. Resolve the requested name first so unresolved
/// built-in object types can continue through `value_is_type`.
pub(super) fn value_is_class_type(val: &Value, name: &str, scope: &Scope) -> Option<bool> {
    let expected_name = name.strip_prefix('*').unwrap_or(name);
    let Some(Value::Object(_, Some(expected_source))) = resolve_dotted(scope, expected_name) else {
        return None;
    };
    let expected_type_identity = expected_source.type_identity.as_ref()?;

    let Value::Object(_, Some(source)) = val else {
        return Some(false);
    };
    let Some(actual_type_identity) = source.type_identity.as_ref() else {
        return Some(false);
    };

    Some(
        actual_type_identity == expected_type_identity
            || source
                .parent_type_identities
                .iter()
                .any(|parent| parent == expected_type_identity),
    )
}

pub(super) fn type_is_runtime_checkable(ty: &crate::parser::TypeExpr, scope: &Scope) -> bool {
    use crate::parser::TypeExpr;
    match ty {
        TypeExpr::Named(name) => {
            let runtime_name = name.strip_prefix('*').unwrap_or(name);
            string_literal_type_value(name).is_some()
                || matches!(
                    runtime_name,
                    "Null"
                        | "Boolean"
                        | "Bool"
                        | "Int"
                        | "Float"
                        | "Number"
                        | "String"
                        | "List"
                        | "Listing"
                        | "Set"
                        | "Map"
                        | "Mapping"
                        | "Object"
                        | "Dynamic"
                        | "Function"
                        | "Regex"
                        | "Duration"
                        | "DataSize"
                        | "Any"
                )
                || scope.get_type_alias(runtime_name).is_some()
                || resolve_dotted(scope, runtime_name).is_some()
        }
        TypeExpr::Nullable(inner) => type_is_runtime_checkable(inner, scope),
        TypeExpr::Union(variants) => variants
            .iter()
            .all(|variant| type_is_runtime_checkable(variant, scope)),
        TypeExpr::Generic(_, _) => true,
        TypeExpr::Constrained(base, _) => {
            let runtime_name = base
                .trim_start_matches('*')
                .trim_end_matches('?')
                .split('<')
                .next()
                .unwrap_or(base);
            type_is_runtime_checkable(&TypeExpr::Named(runtime_name.into()), scope)
        }
    }
}

pub(super) fn is_truthy(v: &Value) -> bool {
    match v {
        Value::Null => false,
        Value::Bool(b) => *b,
        Value::Int(n) => *n != 0,
        Value::Float(f) => *f != 0.0,
        Value::String(s) => !s.is_empty(),
        _ => true,
    }
}

pub(super) fn is_null_value(value: &Value) -> bool {
    matches!(value, Value::Null)
}

/// Pkl's `==`. Collections and objects compare by kind and members (see
/// [`ListKind`] and [`ObjectKind`]), sets and mappings without regard to
/// order, classes by identity, and functions only equal themselves.
pub(super) fn values_eq(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (left, right) if is_null_value(left) && is_null_value(right) => true,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Int(a), Value::Int(b)) => a == b,
        (Value::Float(a), Value::Float(b)) => a == b,
        (Value::Int(a), Value::Float(b)) => (*a as f64) == *b,
        (Value::Float(a), Value::Int(b)) => *a == (*b as f64),
        (Value::String(a), Value::String(b)) => a == b,
        // Regexes are equal when their patterns are.
        (Value::Regex(a), Value::Regex(b)) => a == b,
        (Value::List(a), Value::List(b)) => {
            a.kind() == b.kind()
                && a.len() == b.len()
                && if a.kind() == ListKind::Set {
                    a.iter().all(|item| set_contains(b, item))
                } else {
                    a.iter().zip(b.iter()).all(|(a, b)| values_eq(a, b))
                }
        }
        (Value::Object(a_map, a_src), Value::Object(b_map, b_src)) => {
            if Arc::ptr_eq(a_map, b_map) && a_src == b_src {
                return true;
            }
            match object_kinds_match(a_src.as_deref(), b_src.as_deref()) {
                Some(true) => true,
                Some(false) => false,
                None => {
                    // Methods are not members, so they take no part.
                    members(a_map, a_src).count() == members(b_map, b_src).count()
                        && members(a_map, a_src).all(|(key, a)| {
                            b_map
                                .get(key)
                                .or_else(|| {
                                    b_map.iter().find_map(|(stored, value)| {
                                        crate::value::mapping_storage_keys_equal(stored, key)
                                            .then_some(value)
                                    })
                                })
                                .is_some_and(|b| values_eq(a, b))
                        })
                }
            }
        }
        (Value::Lambda(_, a_body, a_captured), Value::Lambda(_, b_body, b_captured)) => {
            Arc::ptr_eq(a_body, b_body) && Arc::ptr_eq(a_captured, b_captured)
        }
        (a, b) => super::stdlib::units_equal(a, b).unwrap_or(false),
    }
}

/// The members of an object: its map without its methods.
fn members<'a>(
    map: &'a ObjectMap,
    src: &'a Option<Arc<ObjectSource>>,
) -> impl Iterator<Item = (&'a Arc<str>, &'a Value)> {
    map.iter().filter(move |(key, value)| {
        !(matches!(value, Value::Lambda(..))
            && src.as_deref().is_some_and(|src| is_method(src, key)))
    })
}

/// Whether `name` is a method of the object `src` describes.
fn is_method(src: &ObjectSource, name: &str) -> bool {
    src.entries.iter().any(
        |entry| matches!(entry, Entry::Property(prop) if prop.is_method && &*prop.name == name),
    )
}

/// The result of a `map`, `flatMap` or `filter` on a collection of `kind`:
/// a `Set` stays a set (keeping one of equal elements), anything else gives
/// a `List`, as `Listing` has no such methods.
pub(super) fn collection_result(kind: ListKind, items: Vec<Value>) -> Value {
    if kind != ListKind::Set {
        return Value::List(items.into());
    }
    let mut set = Vec::with_capacity(items.len());
    for item in items {
        if !set_contains(&set, &item) {
            set.push(item);
        }
    }
    Value::List(ListValue::new(ListKind::Set, set))
}

/// Whether `set` has an element equal to `item`.
pub(super) fn set_contains(set: &[Value], item: &Value) -> bool {
    set.iter().any(|element| values_eq(element, item))
}

/// Compares what two objects are. `Some(false)` when they are of different
/// kinds or classes, `Some(true)` when both are the same class (which compare
/// by identity), and `None` when their members decide. An object without a
/// source (a module, a `Map`, or a `Dynamic` built by a method) is not told
/// apart from a `Dynamic` or a `Mapping`.
fn object_kinds_match(a: Option<&ObjectSource>, b: Option<&ObjectSource>) -> Option<bool> {
    fn class(src: Option<&ObjectSource>) -> Option<(&String, bool)> {
        let src = src?;
        let name = src.type_name.as_ref()?;
        Some((
            src.type_identity.as_ref().unwrap_or(name),
            src.kind == ObjectKind::Class,
        ))
    }
    match (class(a), class(b)) {
        (Some((a, a_is_class)), Some((b, b_is_class))) => {
            if a != b || a_is_class != b_is_class {
                Some(false)
            } else if a_is_class {
                Some(true)
            } else {
                None
            }
        }
        (Some(_), None) | (None, Some(_)) => Some(false),
        (None, None) => match (a.map(|src| src.kind), b.map(|src| src.kind)) {
            (Some(a), Some(b)) if a != b => Some(false),
            _ => None,
        },
    }
}

pub(super) fn add_values(l: Value, r: Value) -> Result<Value> {
    match (l, r) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a + b)),
        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a + b)),
        (Value::Int(a), Value::Float(b)) => Ok(Value::Float(a as f64 + b)),
        (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a + b as f64)),
        (Value::String(a), Value::String(b)) => Ok(Value::String(format!("{a}{b}").into())),
        // `+` takes a `List` or `Set` on each side; the result has the left
        // side's kind. Listings can't be added.
        (Value::List(a), Value::List(b))
            if a.kind() == ListKind::Listing || b.kind() == ListKind::Listing =>
        {
            let name = |kind| match kind {
                ListKind::Listing => "Listing",
                ListKind::Set => "Set",
                _ => "List",
            };
            Err(Error::Eval(format!(
                "Operator `+` is not defined for operand types `{}` and `{}`.",
                name(a.kind()),
                name(b.kind())
            )))
        }
        (Value::List(mut a), Value::List(b)) => {
            let set = a.kind() == ListKind::Set;
            let items = a.make_mut();
            for item in b.iter() {
                // A set's union keeps one of each element.
                if !set || !items.iter().any(|existing| values_eq(existing, item)) {
                    items.push(item.clone());
                }
            }
            Ok(Value::List(a))
        }
        (Value::Object(mut a, _), Value::Object(b, _)) => {
            Arc::make_mut(&mut a).extend(b.iter().map(|(k, v)| (k.clone(), v.clone())));
            Ok(Value::Object(a, None))
        }
        (l, r) => Err(Error::Eval(format!("cannot add {l:?} and {r:?}"))),
    }
}

pub(super) fn arithmetic(
    l: Value,
    r: Value,
    fi: impl Fn(i64, i64) -> Result<i64>,
    ff: impl Fn(f64, f64) -> Result<f64>,
) -> Result<Value> {
    match (l, r) {
        (Value::Int(a), Value::Int(b)) => Ok(Value::Int(fi(a, b)?)),
        (Value::Float(a), Value::Float(b)) => Ok(Value::Float(ff(a, b)?)),
        (Value::Int(a), Value::Float(b)) => Ok(Value::Float(ff(a as f64, b)?)),
        (Value::Float(a), Value::Int(b)) => Ok(Value::Float(ff(a, b as f64)?)),
        (l, r) => Err(Error::Eval(format!(
            "arithmetic type mismatch: {l:?} vs {r:?}"
        ))),
    }
}

pub(super) fn compare(l: Value, r: Value, ord: std::cmp::Ordering) -> Result<Value> {
    Ok(Value::Bool(value_cmp(&l, &r)? == ord))
}

pub(super) fn compare_or_eq(l: Value, r: Value, ord: std::cmp::Ordering) -> Result<Value> {
    let c = value_cmp(&l, &r)?;
    Ok(Value::Bool(c == ord || c == std::cmp::Ordering::Equal))
}

pub(super) fn value_cmp(a: &Value, b: &Value) -> Result<std::cmp::Ordering> {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => Ok(x.cmp(y)),
        (Value::Float(x), Value::Float(y)) => {
            Ok(x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal))
        }
        (Value::Int(x), Value::Float(y)) => Ok((*x as f64)
            .partial_cmp(y)
            .unwrap_or(std::cmp::Ordering::Equal)),
        (Value::Float(x), Value::Int(y)) => Ok(x
            .partial_cmp(&(*y as f64))
            .unwrap_or(std::cmp::Ordering::Equal)),
        (Value::String(x), Value::String(y)) => Ok(x.cmp(y)),
        _ => Err(Error::Eval(format!("cannot compare {a:?} and {b:?}"))),
    }
}

/// `value`, or an instance of it if it is a class. A class used as a default
/// or template stands for an instance with the class's defaults.
pub(super) fn as_instance(value: Value) -> Value {
    match value {
        Value::Object(map, Some(src)) if src.kind == ObjectKind::Class => {
            let mut src = Arc::unwrap_or_clone(src);
            src.kind = ObjectKind::Object;
            Value::Object(map, Some(Arc::new(src)))
        }
        value => value,
    }
}

pub(super) fn merge_values(base: Value, overlay: Value) -> Value {
    match (base, overlay) {
        (Value::Object(mut b, base_src), Value::Object(o, overlay_src)) => {
            let b_map = Arc::make_mut(&mut b);
            for (k, v) in o.iter() {
                let storage_key = b_map
                    .get_key_value(k)
                    .map(|(key, _)| key.clone())
                    .or_else(|| {
                        b_map
                            .keys()
                            .find(|stored| crate::value::mapping_storage_keys_equal(stored, k))
                            .cloned()
                    })
                    .unwrap_or_else(|| k.clone());
                if let Some(existing) = b_map.shift_remove(&storage_key) {
                    b_map.insert(storage_key, merge_values(existing, v.clone()));
                } else {
                    b_map.insert(storage_key, v.clone());
                }
            }
            // Keep the base's source (entries/scope for late binding), but when it
            // carries no class identity, inherit the overlay's. This preserves a
            // concrete value's type when it is merged onto a typeless default
            // template (e.g. a union-typed Mapping value).
            let src = match (base_src, overlay_src) {
                (Some(b), Some(o)) if b.type_name.is_none() && o.type_name.is_some() => {
                    let mut nb = (*b).clone();
                    nb.type_name = o.type_name.clone();
                    nb.type_identity = o.type_identity.clone();
                    nb.parent_type_names = o.parent_type_names.clone();
                    nb.parent_type_identities = o.parent_type_identities.clone();
                    Some(Arc::new(nb))
                }
                (Some(b), _) => Some(b),
                (None, o) => o,
            };
            as_instance(Value::Object(b, src))
        }
        (_, overlay) => overlay,
    }
}