yaml-schema 0.9.1

A YAML schema validator
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
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
use std::collections::HashSet;
use std::fmt::Display;
use std::rc::Rc;

use hashlink::LinkedHashMap;
use jsonptr::Token;
use log::debug;
use log::error;
use saphyr::{AnnotatedMapping, MarkedYaml, Scalar, YamlData};

use crate::ConstValue;
use crate::Context;
use crate::Error;
use crate::RefUri;
use crate::Reference;
use crate::Result;
use crate::Validator;
use crate::loader::load_boolean_or_schema_marked;
use crate::loader::load_external_schema;
use crate::loader::marked_yaml_to_string;
use crate::schemas::AllOfSchema;
use crate::schemas::AnyOfSchema;
use crate::schemas::ArraySchema;
use crate::schemas::EnumSchema;
use crate::schemas::IfThenElseSchema;
use crate::schemas::IntegerSchema;
use crate::schemas::NotSchema;
use crate::schemas::NumberSchema;
use crate::schemas::ObjectSchema;
use crate::schemas::OneOfSchema;
use crate::schemas::StringSchema;
use crate::utils::format_annotated_mapping;
use crate::utils::format_linked_hash_map;
use crate::utils::format_marked_yaml;
use crate::utils::format_marker;
use crate::utils::format_scalar;
use crate::utils::format_vec;
use crate::utils::format_yaml_data;
use crate::utils::scalar_to_string;
use crate::validation::ArrayUnevaluatedAnnotations;

/// YamlSchema is the base of the validation model
#[derive(Debug, PartialEq)]
pub enum YamlSchema {
    Empty,                // no value
    Null,                 // `null`
    BooleanLiteral(bool), // `true` or `false`
    Subschema(Box<Subschema>),
}

impl YamlSchema {
    pub fn subschema(subschema: Subschema) -> Self {
        Self::Subschema(Box::new(subschema))
    }

    pub fn ref_str(ref_name: impl Into<String>) -> Self {
        Self::subschema(Subschema {
            r#ref: Some(Reference::new(ref_name)),
            ..Default::default()
        })
    }

    /// Create a YamlSchema with a single type: `boolean`
    pub fn typed_boolean() -> Self {
        Self::subschema(Subschema {
            r#type: SchemaType::new("boolean"),
            ..Default::default()
        })
    }

    /// Create a YamlSchema with a single type: `number`
    pub fn typed_number(number_schema: NumberSchema) -> Self {
        number_schema.into()
    }

    /// Create a YamlSchema with a single type: `string`
    pub fn typed_string(string_schema: StringSchema) -> Self {
        Self::subschema(Subschema {
            r#type: SchemaType::new("string"),
            string_schema: Some(string_schema),
            ..Default::default()
        })
    }

    /// Create a YamlSchema with a single type: `object`
    pub fn typed_object(object_schema: ObjectSchema) -> Self {
        Self::subschema(Subschema {
            r#type: SchemaType::new("object"),
            object_schema: Some(object_schema),
            ..Default::default()
        })
    }

    /// Resolve a portion of a JSON Pointer to an element in the schema.
    pub fn resolve(
        &self,
        key: Option<&Token>,
        components: &[jsonptr::Component],
    ) -> Option<&YamlSchema> {
        debug!("[YamlSchema#resolve] self: {self}, key: {key:?}, components: {components:?}");
        if components.is_empty() {
            return Some(self);
        }
        match self {
            YamlSchema::Subschema(subschema) => subschema.resolve(key, components),
            _ => None,
        }
    }
}

impl<'r> TryFrom<&MarkedYaml<'r>> for YamlSchema {
    type Error = crate::Error;
    fn try_from(marked_yaml: &MarkedYaml<'r>) -> crate::Result<Self> {
        match &marked_yaml.data {
            YamlData::Value(scalar) => match scalar {
                Scalar::Boolean(value) => Ok(YamlSchema::BooleanLiteral(*value)),
                Scalar::Null => Ok(YamlSchema::Null),
                _ => Err(generic_error!(
                    "[YamlSchema#try_from] Expected a boolean or null, but got: {}",
                    format_scalar(scalar)
                )),
            },
            YamlData::Mapping(_) => Subschema::try_from(marked_yaml).map(YamlSchema::subschema),
            _ => Err(generic_error!(
                "[YamlSchema#try_from] Expected a boolean, null, or a mapping, but got: {}",
                format_marked_yaml(marked_yaml)
            )),
        }
    }
}

impl From<NumberSchema> for YamlSchema {
    fn from(number_schema: NumberSchema) -> Self {
        YamlSchema::subschema(Subschema {
            r#type: SchemaType::new("number"),
            number_schema: Some(number_schema),
            ..Default::default()
        })
    }
}

impl From<IntegerSchema> for YamlSchema {
    fn from(integer_schema: IntegerSchema) -> Self {
        YamlSchema::subschema(Subschema {
            r#type: SchemaType::new("integer"),
            integer_schema: Some(integer_schema),
            ..Default::default()
        })
    }
}

impl From<StringSchema> for YamlSchema {
    fn from(string_schema: StringSchema) -> Self {
        YamlSchema::subschema(Subschema {
            r#type: SchemaType::new("string"),
            string_schema: Some(string_schema),
            ..Default::default()
        })
    }
}

impl Validator for YamlSchema {
    fn validate(&self, context: &Context, value: &saphyr::MarkedYaml) -> Result<()> {
        debug!("[YamlSchema] self: {self}");
        debug!(
            "[YamlSchema] Validating value: {}",
            format_yaml_data(&value.data)
        );
        match self {
            YamlSchema::Empty => Ok(()),
            YamlSchema::Null => {
                if !matches!(&value.data, YamlData::Value(Scalar::Null)) {
                    context.add_error(
                        value,
                        format!("Expected null, but got: {}", format_yaml_data(&value.data)),
                    );
                }
                Ok(())
            }
            YamlSchema::BooleanLiteral(boolean) => {
                if !*boolean {
                    context.add_error(value, "YamlSchema is `false`!");
                }
                Ok(())
            }
            YamlSchema::Subschema(subschema) => {
                debug!("[YamlSchema#validate] Validating subschema: {subschema:?}");
                subschema.validate(context, value)?;
                Ok(())
            }
        }
    }
}

impl From<Subschema> for YamlSchema {
    fn from(subschema: Subschema) -> Self {
        YamlSchema::subschema(subschema)
    }
}

impl Display for YamlSchema {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            YamlSchema::Empty => write!(f, "<empty>"),
            YamlSchema::Null => write!(f, "null"),
            YamlSchema::BooleanLiteral(value) => write!(f, "{value}"),
            YamlSchema::Subschema(subschema) => subschema.fmt(f),
        }
    }
}

/// Represents either a literal boolean value or a YamlSchema
#[derive(Debug, PartialEq)]
pub enum BooleanOrSchema {
    Boolean(bool),
    Schema(YamlSchema),
}

impl BooleanOrSchema {
    pub fn schema(schema: YamlSchema) -> Self {
        BooleanOrSchema::Schema(schema)
    }
}

impl Display for BooleanOrSchema {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BooleanOrSchema::Boolean(value) => write!(f, "{value}"),
            BooleanOrSchema::Schema(schema) => schema.fmt(f),
        }
    }
}

#[derive(Debug, Default, PartialEq)]
pub enum SchemaType {
    #[default]
    /// No `type:` was provided
    None,
    /// A single type
    Single(String),
    /// Multiple types
    Multiple(Vec<String>),
}

impl SchemaType {
    /// Create a new SchemaType with a single value
    pub fn new<S: Into<String>>(value: S) -> Self {
        SchemaType::Single(value.into())
    }

    pub fn is_none(&self) -> bool {
        matches!(self, SchemaType::None)
    }

    pub fn is_single(&self) -> bool {
        matches!(self, SchemaType::Single(_))
    }

    pub fn is_multiple(&self) -> bool {
        matches!(self, SchemaType::Multiple(_))
    }

    /// Checks if this SchemaType matches or contains the given type string.
    ///
    /// Returns `true` if:
    /// - The schema type is `Single` and matches the given type string, or
    /// - The schema type is `Multiple` and contains the given type string
    ///
    /// Returns `false` if:
    /// - The schema type is `None`, or
    /// - The schema type doesn't match/contain the given type string
    ///
    /// # Examples
    ///
    /// ```
    /// use yaml_schema::schemas::SchemaType;
    ///
    /// // Test with a single type
    /// let single = SchemaType::new("string");
    /// assert!(single.is_or_contains("string"));
    /// assert!(!single.is_or_contains("number"));
    ///
    /// // Test with multiple types
    /// let multiple = SchemaType::Multiple(vec!["string".to_string(), "number".to_string()]);
    /// assert!(multiple.is_or_contains("string"));
    /// assert!(multiple.is_or_contains("number"));
    /// assert!(!multiple.is_or_contains("boolean"));
    ///
    /// // Test with None (no type specified)
    /// let none = SchemaType::None;
    /// assert!(!none.is_or_contains("string"));
    /// ```
    pub fn is_or_contains(&self, r#type: &str) -> bool {
        match self {
            SchemaType::None => false,
            SchemaType::Single(s) => s == r#type,
            SchemaType::Multiple(values) => values.contains(&r#type.to_string()),
        }
    }
}

impl Display for SchemaType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SchemaType::None => Ok(()), // No `type:` was provided
            SchemaType::Single(value) => write!(f, "{value}"),
            SchemaType::Multiple(values) => write!(f, "{}", format_vec(values)),
        }
    }
}

/// A Subschema contains the core schema elements and validation
#[derive(Debug, Default, PartialEq)]
pub struct Subschema {
    /// `$id` and `$schema` metadata and `title` and `description` annotations
    pub metadata_and_annotations: MetadataAndAnnotations,
    /// `$anchor` metadata
    pub anchor: Option<String>,
    /// `$ref`
    pub r#ref: Option<Reference>,
    /// `$defs`
    pub defs: Option<LinkedHashMap<String, YamlSchema>>,
    /// `anyOf`
    pub any_of: Option<AnyOfSchema>,
    /// `allOf`
    pub all_of: Option<AllOfSchema>,
    /// `oneOf`
    pub one_of: Option<OneOfSchema>,
    /// `not`
    pub not: Option<NotSchema>,
    /// `if` / `then` / `else`
    pub if_then_else: Option<IfThenElseSchema>,
    /// `type`
    pub r#type: SchemaType,
    /// `const`
    pub r#const: Option<ConstValue>,
    /// `enum`
    pub r#enum: Option<EnumSchema>,

    pub array_schema: Option<ArraySchema>,
    pub integer_schema: Option<IntegerSchema>,
    pub number_schema: Option<NumberSchema>,
    pub object_schema: Option<ObjectSchema>,
    pub string_schema: Option<StringSchema>,
    /// `unevaluatedProperties` (JSON Schema 2020-12 unevaluated vocabulary).
    pub unevaluated_properties: Option<BooleanOrSchema>,
    /// `unevaluatedItems`.
    pub unevaluated_items: Option<BooleanOrSchema>,
}

impl Subschema {
    /// Resolve a portion of a JSON Pointer to an element in the schema.
    pub fn resolve(
        &self,
        token: Option<&Token>,
        components: &[jsonptr::Component],
    ) -> Option<&YamlSchema> {
        debug!("[Subschema#resolve] self: {self}, token: {token:?}, components: {components:?}");
        if let Some(token) = token {
            let s = token.decoded();
            debug!("[Subschema#resolve] key: {s}");
            match s.as_ref() {
                "$defs" => {
                    debug!("[Subschema#resolve] Resolving $defs");
                    if let Some(defs) = self.defs.as_ref() {
                        debug!("[Subschema#resolve] defs: {}", format_linked_hash_map(defs));
                        if let Some(component) = components.first() {
                            debug!("[Subschema#resolve] component: {component:?}");
                            if let jsonptr::Component::Token(next_token) = component {
                                let decoded = next_token.decoded();
                                debug!("[Subschema#resolve] decoded: {decoded}");
                                debug!("[Subschema#resolve] defs: {defs:?}");
                                if let Some(schema) = defs.get(decoded.as_ref()) {
                                    debug!("[Subschema#resolve] schema: {schema:?}");
                                    return schema.resolve(Some(next_token), &components[1..]);
                                }
                            }
                        }
                    }
                }
                "anyOf" => {}
                _ => (),
            }
        }
        None
    }
}

// Try to load a Subschema from a MarkedYaml. Delegate to the TryFrom<&AnnotatedMapping<'_>> for mappings.
// If the MarkedYaml is not a mapping, returns an error.
impl<'r> TryFrom<&MarkedYaml<'r>> for Subschema {
    type Error = crate::Error;
    fn try_from(marked_yaml: &MarkedYaml<'r>) -> crate::Result<Self> {
        if let YamlData::Mapping(mapping) = &marked_yaml.data {
            Self::try_from(mapping)
        } else {
            Err(generic_error!(
                "{} Expected a mapping, but got: {:?}",
                format_marker(&marked_yaml.span.start),
                marked_yaml
            ))
        }
    }
}

fn try_load_defs<'r>(marked_yaml: &MarkedYaml<'r>) -> Result<LinkedHashMap<String, YamlSchema>> {
    debug!(
        "[try_load_defs] marked_yaml: {}",
        format_yaml_data(&marked_yaml.data)
    );
    if let YamlData::Mapping(mapping) = &marked_yaml.data {
        debug!(
            "[try_load_defs] mapping: {}",
            format_annotated_mapping(mapping)
        );
        mapping
            .iter()
            .try_fold(LinkedHashMap::new(), |mut acc, (key, value)| {
                let key = marked_yaml_to_string(key, "key must be a string")?;
                acc.insert(key, value.try_into()?);
                Ok(acc)
            })
    } else {
        Err(expected_mapping!(marked_yaml))
    }
}

impl<'r> TryFrom<&AnnotatedMapping<'r, MarkedYaml<'r>>> for Subschema {
    type Error = Error;

    fn try_from(mapping: &AnnotatedMapping<'r, MarkedYaml<'r>>) -> crate::Result<Self> {
        debug!(
            "[Subschema#try_from] mapping has {} keys",
            mapping.keys().len()
        );
        for key in mapping.keys() {
            debug!("[Subschema#try_from] key: {:?}", key.data);
        }

        let metadata_and_annotations = MetadataAndAnnotations::try_from(mapping)?;
        debug!("[Subschema#try_from] metadata_and_annotations: {metadata_and_annotations}");

        // $defs
        let defs: Option<LinkedHashMap<String, YamlSchema>> = mapping
            .get(&MarkedYaml::value_from_str("$defs"))
            .map(|x| {
                debug!("[Subschema#try_from] x: {}", format_yaml_data(&x.data));
                debug!("[Subschema#try_from] Trying to load `$defs` as LinkedHashMap<String, YamlSchema>");
                try_load_defs(x)
            })
            .transpose()?;

        // $ref
        let reference: Option<Reference> = mapping
            .get(&MarkedYaml::value_from_str("$ref"))
            .map(|_| {
                debug!("[Subschema#try_from] Trying to load `$ref` as Reference");
                mapping.try_into()
            })
            .transpose()?;

        // anyOf
        let any_of: Option<AnyOfSchema> = mapping
            .get(&MarkedYaml::value_from_str("anyOf"))
            .map(|_| {
                debug!("[Subschema#try_from] Trying to load `anyOf` as AnyOfSchema");
                mapping.try_into()
            })
            .transpose()?;

        // allOf
        let all_of: Option<AllOfSchema> = mapping
            .get(&MarkedYaml::value_from_str("allOf"))
            .map(|_| {
                debug!("[Subschema#try_from] Trying to load `allOf` as AllOfSchema");
                mapping.try_into()
            })
            .transpose()?;

        // oneOf
        let one_of: Option<OneOfSchema> = mapping
            .get(&MarkedYaml::value_from_str("oneOf"))
            .map(|_| {
                debug!("[Subschema#try_from] Trying to load `oneOf` as OneOfSchema");
                mapping.try_into()
            })
            .transpose()?;

        // not
        let not: Option<NotSchema> = mapping
            .get(&MarkedYaml::value_from_str("not"))
            .map(|_| {
                debug!("[Subschema#try_from] Trying to load `not` as NotSchema");
                mapping.try_into()
            })
            .transpose()?;

        // if / then / else (only when `if` is present)
        let if_then_else: Option<IfThenElseSchema> = mapping
            .get(&MarkedYaml::value_from_str("if"))
            .map(|_| {
                debug!(
                    "[Subschema#try_from] Trying to load `if`/`then`/`else` as IfThenElseSchema"
                );
                IfThenElseSchema::try_from(mapping)
            })
            .transpose()?;

        // const
        let mut r#const: Option<ConstValue> = None;
        if let Some(value) = mapping.get(&MarkedYaml::value_from_str("const")) {
            r#const = Some(ConstValue::try_from(value)?);
        }

        // enum
        let mut r#enum: Option<EnumSchema> = None;
        if let Some(value) = mapping.get(&MarkedYaml::value_from_str("enum")) {
            r#enum = Some(value.try_into()?);
        }

        // type
        let mut r#type: SchemaType = SchemaType::None;
        if let Some(type_value) = mapping.get(&MarkedYaml::value_from_str("type")) {
            match &type_value.data {
                YamlData::Value(Scalar::Null) => {
                    r#type = SchemaType::new("null");
                }
                YamlData::Value(Scalar::String(s)) => r#type = SchemaType::new(s.as_ref()),
                YamlData::Sequence(values) => {
                    r#type = SchemaType::Multiple(
                        values
                            .iter()
                            .map(|marked_yaml| {
                                marked_yaml_to_string(marked_yaml, "type must be a string")
                            })
                            .collect::<Result<Vec<String>>>()?,
                    )
                }
                _ => {
                    return Err(schema_loading_error!(
                        "[Subschema#try_from] Expected a string or sequence for `type`, but got: {:?}",
                        type_value.data
                    ));
                }
            }
        }

        // Instantiate the appropriate schema based on the type(s)
        let mut array_schema = None;
        let mut integer_schema = None;
        let mut number_schema = None;
        let mut object_schema = None;
        let mut string_schema = None;

        let types: Vec<&str> = match r#type {
            SchemaType::None => vec![],
            SchemaType::Single(ref s) => vec![s],
            SchemaType::Multiple(ref values) => values.iter().map(|s| s.as_ref()).collect(),
        };

        for s in types {
            match s {
                "array" => {
                    debug!("[Subschema#try_from] Instantiating array schema");
                    array_schema = ArraySchema::try_from(mapping).map(Some)?;
                }
                // No subschema needed for boolean, we handle it in the validate_by_type method
                "boolean" => {}
                "integer" => {
                    debug!("[Subschema#try_from] Instantiating integer schema");
                    integer_schema = IntegerSchema::try_from(mapping).map(Some)?;
                }
                "number" => {
                    debug!("[Subschema#try_from] Instantiating number schema");
                    number_schema = NumberSchema::try_from(mapping).map(Some)?;
                }
                "object" => {
                    debug!("[Subschema#try_from] Instantiating object schema");
                    object_schema = ObjectSchema::try_from(mapping).map(Some)?;
                }
                "string" => {
                    debug!("[Subschema#try_from] Instantiating string schema");
                    string_schema = StringSchema::try_from(mapping).map(Some)?;
                }
                "null" => (),
                _ => {
                    return Err(unsupported_type!(
                        "Expected type: string, number, integer, object, array, boolean, or null, but got: {}",
                        s
                    ));
                }
            }
        }

        // When `type` is omitted but `properties` is present, treat as `type: object` (JSON Schema-style).
        if r#type.is_none() && mapping.contains_key(&MarkedYaml::value_from_str("properties")) {
            r#type = SchemaType::new("object");
            object_schema = ObjectSchema::try_from(mapping).map(Some)?;
        }

        // When `type` is omitted but string validation keywords are present, treat as `type: string`
        // so `pattern` / `minLength` / `maxLength` are not ignored (JSON Schema-style).
        if r#type.is_none()
            && (mapping.contains_key(&MarkedYaml::value_from_str("pattern"))
                || mapping.contains_key(&MarkedYaml::value_from_str("minLength"))
                || mapping.contains_key(&MarkedYaml::value_from_str("maxLength")))
        {
            r#type = SchemaType::new("string");
            string_schema = StringSchema::try_from(mapping).map(Some)?;
        }

        let unevaluated_properties = mapping
            .get(&MarkedYaml::value_from_str("unevaluatedProperties"))
            .map(load_boolean_or_schema_marked)
            .transpose()?;
        let unevaluated_items = mapping
            .get(&MarkedYaml::value_from_str("unevaluatedItems"))
            .map(load_boolean_or_schema_marked)
            .transpose()?;

        debug!("[Subschema#try_from] array_schema: {array_schema:?}");
        debug!("[Subschema#try_from] integer_schema: {integer_schema:?}");
        debug!("[Subschema#try_from] number_schema: {number_schema:?}");
        debug!("[Subschema#try_from] object_schema: {object_schema:?}");
        debug!("[Subschema#try_from] string_schema: {string_schema:?}");

        Ok(Self {
            metadata_and_annotations,
            defs,
            r#ref: reference,
            any_of,
            all_of,
            one_of,
            not,
            if_then_else,
            r#type,
            r#const,
            r#enum,
            array_schema,
            integer_schema,
            number_schema,
            object_schema,
            string_schema,
            unevaluated_properties,
            unevaluated_items,
            anchor: None,
        })
    }
}

impl Display for Subschema {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{{")?;
        if !self.metadata_and_annotations.is_empty() {
            write!(f, " ")?;
            self.metadata_and_annotations.fmt(f)?;
            write!(f, " ")?;
        }
        if !self.r#type.is_none() {
            write!(f, "type: ")?;
            self.r#type.fmt(f)?;
        }
        if let Some(r#ref) = &self.r#ref {
            write!(f, "$ref: ")?;
            r#ref.fmt(f)?;
        }
        if let Some(defs) = &self.defs {
            write!(f, "$defs: {}", format_linked_hash_map(defs))?;
        }
        if let Some(any_of) = &self.any_of {
            write!(f, "anyOf: ")?;
            any_of.fmt(f)?;
        }
        if let Some(all_of) = &self.all_of {
            write!(f, "allOf: ")?;
            all_of.fmt(f)?;
        }
        if let Some(one_of) = &self.one_of {
            write!(f, "oneOf: ")?;
            one_of.fmt(f)?;
        }
        if let Some(not) = &self.not {
            write!(f, "not: ")?;
            not.fmt(f)?;
        }
        if let Some(ite) = &self.if_then_else {
            write!(f, "if/then/else: {ite}")?;
        }
        write!(f, "}}")?;
        Ok(())
    }
}

impl Validator for Subschema {
    fn validate(&self, context: &Context, value: &saphyr::MarkedYaml) -> crate::Result<()> {
        debug!("[Subschema] self: {self}");
        debug!(
            "[Subschema] Validating value: {}",
            format_yaml_data(&value.data)
        );

        if let Some(reference) = &self.r#ref {
            debug!("[Subschema] Reference found: {reference}");
            let ref_name = &reference.ref_name;
            if let Some(root_schema) = context.root_schema {
                if let Some(ref_path) = ref_name.strip_prefix("#") {
                    if context.is_resolving_ref(ref_name, value) {
                        context.add_error(value, format!("Circular $ref detected: {ref_name}"));
                        return Ok(());
                    }
                    let pointer = jsonptr::Pointer::parse(ref_path)?;
                    debug!("[Subschema] Pointer: {pointer}");
                    let schema = root_schema.resolve(pointer);
                    if let Some(schema) = schema {
                        debug!("[Subschema] Found {ref_path}: {schema}");
                        context.begin_resolving_ref(ref_name, value);
                        let result = schema.validate(context, value);
                        context.end_resolving_ref(ref_name, value);
                        result?;
                    } else {
                        error!("[Subschema] Cannot find definition: {ref_path}");
                        context.add_error(value, format!("Schema {ref_path} not found"));
                    }
                } else {
                    // External ref: resolve, load schema if needed, resolve fragment
                    let ref_uri = RefUri::parse(ref_name);
                    let resolved_url = if ref_uri.is_absolute() {
                        let mut url = url::Url::parse(ref_uri.base_ref()).map_err(|e| {
                            generic_error!("Failed to parse absolute $ref URI {}: {}", ref_name, e)
                        })?;
                        if let Some(frag) = ref_uri.fragment() {
                            url.set_fragment(Some(frag));
                        }
                        url
                    } else {
                        let base = root_schema.base_uri.as_ref().ok_or_else(|| {
                            generic_error!(
                                "Relative $ref requires schema to be loaded from a file or URL. Found: {}",
                                ref_name
                            )
                        })?;
                        ref_uri.resolve_against(base)?
                    };
                    let ref_key = resolved_url.to_string();
                    if context.is_resolving_ref(&ref_key, value) {
                        context.add_error(value, format!("Circular $ref detected: {ref_name}"));
                        return Ok(());
                    }
                    let doc_url = {
                        let mut u = resolved_url.clone();
                        u.set_fragment(None);
                        u.to_string()
                    };
                    let fragment = resolved_url.fragment().and_then(|f| {
                        let s = if f.starts_with('/') {
                            f.to_string()
                        } else {
                            format!("/{f}")
                        };
                        if s.is_empty() || s == "/" {
                            None
                        } else {
                            Some(s)
                        }
                    });
                    {
                        let mut schemas = context.schemas.borrow_mut();
                        if !schemas.contains_key(&doc_url) {
                            let loaded = load_external_schema(&doc_url)?;
                            let schema_rc = Rc::new(loaded);
                            let key = schema_rc.cache_key(&doc_url);
                            schemas.insert(key.clone(), Rc::clone(&schema_rc));
                            if key != doc_url {
                                schemas.insert(doc_url.clone(), schema_rc);
                            }
                        }
                    }
                    let schemas = context.schemas.borrow();
                    let schema = schemas.get(&doc_url).ok_or_else(|| {
                        generic_error!("Schema {doc_url} not in cache after load")
                    })?;
                    let pointer_opt = fragment
                        .as_ref()
                        .map(|frag| jsonptr::Pointer::parse(frag))
                        .transpose()?;
                    let target = match &pointer_opt {
                        Some(pointer) => schema.resolve(pointer),
                        None => Some(&schema.schema),
                    };
                    if let Some(target) = target {
                        context.begin_resolving_ref(&ref_key, value);
                        let result = target.validate(context, value);
                        context.end_resolving_ref(&ref_key, value);
                        result?;
                    } else {
                        error!("[Subschema] Cannot find definition: {:?}", fragment);
                        context.add_error(
                            value,
                            format!("Schema {:?} not found in {doc_url}", fragment),
                        );
                    }
                }
                return Ok(());
            } else {
                return Err(generic_error!(
                    "Subschema has a reference, but no root schema was provided!"
                ));
            }
        }

        // `unevaluated*` on the same mapping as `$ref` are not applied when `$ref` is present
        // (validation returns above). See gap #1 / `$ref` sibling behavior.
        let ctx = Self::validation_context_for_instance(context, value);

        if let Some(any_of) = &self.any_of {
            debug!("[Subschema] Validating anyOf schema: {any_of:?}");
            any_of.validate(&ctx, value)?;
        }

        if let Some(all_of) = &self.all_of {
            debug!("[Subschema] Validating allOf schema: {all_of:?}");
            all_of.validate(&ctx, value)?;
        }

        if let Some(one_of) = &self.one_of {
            debug!("[Subschema] Validating oneOf schema: {one_of:?}");
            one_of.validate(&ctx, value)?;
        }

        if let Some(not) = &self.not {
            debug!("[Subschema] Validating not schema: {not:?}");
            not.validate(&ctx, value)?;
        }

        if let Some(if_then_else) = &self.if_then_else {
            debug!("[Subschema] Validating if/then/else: {if_then_else:?}");
            if_then_else.validate(&ctx, value)?;
        }

        match &self.r#type {
            SchemaType::None => (),
            SchemaType::Single(s) => self.validate_by_type(&ctx, s.as_ref(), value)?,
            SchemaType::Multiple(values) => {
                debug!(
                    "[Subschema] Validating multiple types: {}",
                    values.join(", ")
                );
                let mut any_matched = false;
                for s in values {
                    let sub_context = ctx.get_sub_context();
                    self.validate_by_type(&sub_context, s.as_ref(), value)?;
                    if !sub_context.has_errors() {
                        any_matched = true;
                        break;
                    }
                }
                if !any_matched {
                    ctx.add_error(
                        value,
                        format!("None of type: [{}] matched", values.join(", ")),
                    );
                }
            }
        }

        if let Some(r#const) = &self.r#const
            && !r#const.accepts(value)
        {
            ctx.add_error(
                value,
                format!(
                    "Expected const: {:#?}, but got: {}",
                    r#const,
                    format_yaml_data(&value.data)
                ),
            );
        }

        if let Some(r#enum) = &self.r#enum {
            debug!("[Subschema] Validating enum schema: {}", r#enum);
            r#enum.validate(&ctx, value)?;
        }

        self.apply_unevaluated(&ctx, value)?;

        Ok(())
    }
}

impl Subschema {
    fn validation_context_for_instance<'r>(base: &Context<'r>, value: &MarkedYaml) -> Context<'r> {
        match &value.data {
            YamlData::Mapping(_) => {
                let oe = base.object_evaluated.clone().unwrap_or_default();
                base.with_object_evaluated(Some(oe))
            }
            YamlData::Sequence(_) => {
                let arr = base
                    .array_unevaluated
                    .clone()
                    .unwrap_or_else(ArrayUnevaluatedAnnotations::new_shared);
                base.with_array_unevaluated(Some(arr))
            }
            _ => base
                .with_object_evaluated(base.object_evaluated.clone())
                .with_array_unevaluated(base.array_unevaluated.clone()),
        }
    }

    fn apply_unevaluated(&self, ctx: &Context, value: &MarkedYaml) -> Result<()> {
        if let YamlData::Mapping(mapping) = &value.data
            && let Some(u) = &self.unevaluated_properties
        {
            let evaluated: HashSet<String> = ctx
                .object_evaluated
                .as_ref()
                .map(|o| o.snapshot())
                .unwrap_or_default();
            for (k, v) in mapping.iter() {
                let key_string = match &k.data {
                    YamlData::Value(scalar) => scalar_to_string(scalar),
                    _ => {
                        return Err(expected_scalar!(
                            "[{}] Expected a scalar object key, got: {:?}",
                            format_marker(&k.span.start),
                            k.data
                        ));
                    }
                };
                if key_string == "$schema" {
                    continue;
                }
                if evaluated.contains(&key_string) {
                    continue;
                }
                let prop_ctx = ctx.append_path(&key_string);
                match u {
                    BooleanOrSchema::Boolean(false) => {
                        ctx.add_error(
                            v,
                            format!("Unevaluated property '{key_string}' is not allowed!"),
                        );
                    }
                    BooleanOrSchema::Boolean(true) => {}
                    BooleanOrSchema::Schema(s) => {
                        s.validate(&prop_ctx, v)?;
                    }
                }
            }
        }

        if let YamlData::Sequence(seq) = &value.data
            && let Some(u) = &self.unevaluated_items
        {
            let ann = ctx
                .array_unevaluated
                .as_ref()
                .map(|c| c.borrow().clone())
                .unwrap_or_default();
            if ann.full_coverage {
                return Ok(());
            }
            let indices = ann.indices_requiring_unevaluated(seq.len());
            let err_before = ctx.errors.borrow().len();
            for i in indices.iter().copied() {
                let item = &seq[i];
                let item_ctx = ctx.append_path(i.to_string());
                match u {
                    BooleanOrSchema::Boolean(false) => {
                        ctx.add_error(
                            item,
                            format!("Unevaluated array item at index {i} is not allowed!"),
                        );
                    }
                    BooleanOrSchema::Boolean(true) => {}
                    BooleanOrSchema::Schema(s) => {
                        s.validate(&item_ctx, item)?;
                    }
                }
            }
            if ctx.errors.borrow().len() == err_before
                && !indices.is_empty()
                && let Some(cell) = &ctx.array_unevaluated
            {
                let mut a = cell.borrow_mut();
                a.saw_relevant = true;
                a.full_coverage = true;
            }
        }

        Ok(())
    }

    fn validate_by_type(
        &self,
        context: &Context,
        r#type: &str,
        value: &saphyr::MarkedYaml,
    ) -> Result<()> {
        debug!("[Subschema#validate_by_type] r#type: {}", r#type);
        match r#type {
            "array" => {
                if let Some(array_schema) = &self.array_schema {
                    debug!("[Subschema] Validating array schema: {array_schema:?}");
                    array_schema.validate(context, value)?;
                } else {
                    error!("[Subschema#validate_by_type] No array schema found");
                    context.add_error(value, format!("No array schema found for type: {}", r#type));
                }
            }
            "boolean" => {
                if !matches!(&value.data, YamlData::Value(Scalar::Boolean(_))) {
                    context.add_error(
                        value,
                        format!(
                            "Expected boolean, but got: {}",
                            format_yaml_data(&value.data)
                        ),
                    );
                }
            }
            "null" => {
                if !matches!(&value.data, YamlData::Value(Scalar::Null)) {
                    context.add_error(
                        value,
                        format!("Expected null, but got: {}", format_yaml_data(&value.data)),
                    );
                }
            }
            "string" => {
                if let Some(string_schema) = &self.string_schema {
                    debug!("[Subschema] Validating string schema: {string_schema:?}");
                    string_schema.validate(context, value)?;
                } else {
                    error!("[Subschema#validate_by_type] No string schema found");
                    context.add_error(
                        value,
                        format!("No string schema found for type: {}", r#type),
                    );
                }
            }
            "number" => {
                if let Some(number_schema) = &self.number_schema {
                    debug!("[Subschema] Validating number schema: {number_schema:?}");
                    number_schema.validate(context, value)?;
                } else {
                    error!("[Subschema#validate_by_type] No number schema found");
                    context.add_error(
                        value,
                        format!("No number schema found for type: {}", r#type),
                    );
                }
            }
            "integer" => {
                if let Some(integer_schema) = &self.integer_schema {
                    debug!("[Subschema] Validating integer schema: {integer_schema:?}");
                    integer_schema.validate(context, value)?;
                } else {
                    error!("[Subschema#validate_by_type] No integer schema found");
                    context.add_error(
                        value,
                        format!("No integer schema found for type: {}", r#type),
                    );
                }
            }
            "object" => {
                if let Some(object_schema) = &self.object_schema {
                    debug!("[Subschema] Validating object schema: {object_schema:?}");
                    object_schema.validate(context, value)?;
                } else {
                    error!("[Subschema#validate_by_type] No object schema found");
                    context.add_error(
                        value,
                        format!("No object schema found for type: {}", r#type),
                    );
                }
            }
            _ => {
                error!("[Subschema#validate_by_type] Unsupported type: {}", r#type);
                context.add_error(value, format!("Unsupported type: {}", r#type));
            }
        }
        Ok(())
    }
}

/// The `$id` and `$schema` metadata
#[derive(Debug, Default, PartialEq)]
pub struct MetadataAndAnnotations {
    /// `$id` metadata
    pub id: Option<String>,
    /// `$schema` metadata
    pub schema: Option<String>,
    /// `title` annotation
    pub title: Option<String>,
    /// `description` annotation
    pub description: Option<String>,
}

impl MetadataAndAnnotations {
    pub fn is_empty(&self) -> bool {
        self.id.is_none()
            && self.schema.is_none()
            && self.title.is_none()
            && self.description.is_none()
    }
}

impl std::fmt::Display for MetadataAndAnnotations {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{{")?;
        if !self.is_empty() {
            write!(f, " ")?;
            if let Some(id) = &self.id {
                write!(f, "id: {id}, ")?;
            }
            if let Some(schema) = &self.schema {
                write!(f, "schema: {schema}, ")?;
            }
            if let Some(title) = &self.title {
                write!(f, "title: {title}, ")?;
            }
            if let Some(description) = &self.description {
                write!(f, "description: {description}, ")?;
            }
            write!(f, " ")?;
        }
        write!(f, "}}")?;
        Ok(())
    }
}

impl TryFrom<&AnnotatedMapping<'_, MarkedYaml<'_>>> for MetadataAndAnnotations {
    type Error = Error;

    fn try_from(mapping: &AnnotatedMapping<'_, MarkedYaml<'_>>) -> crate::Result<Self> {
        let mut metadata_and_annotations = MetadataAndAnnotations::default();
        for (key, value) in mapping.iter() {
            match &key.data {
                YamlData::Value(Scalar::String(s)) => match s.as_ref() {
                    "$id" => {
                        metadata_and_annotations.id =
                            Some(marked_yaml_to_string(value, "$id must be a string")?);
                    }
                    "$schema" => {
                        metadata_and_annotations.schema =
                            Some(marked_yaml_to_string(value, "$schema must be a string")?);
                    }
                    "title" => {
                        metadata_and_annotations.title =
                            Some(marked_yaml_to_string(value, "title must be a string")?);
                    }
                    "description" => {
                        metadata_and_annotations.description = Some(marked_yaml_to_string(
                            value,
                            "description must be a string",
                        )?);
                    }
                    _ => {
                        debug!("[MetadataAndAnnotations#try_from] Unknown key: {s}");
                    }
                },
                _ => {
                    debug!("[MetadataAndAnnotations#try_from] Unsupported key data: {key:?}");
                }
            }
        }
        Ok(metadata_and_annotations)
    }
}

#[cfg(test)]
mod tests {
    use saphyr::LoadableYamlNode;

    use crate::engine;
    use crate::loader;

    use super::*;

    #[test]
    fn test_type_boolean() {
        let yaml = r#"
        type: boolean
        "#;
        let doc = MarkedYaml::load_from_str(yaml).expect("Failed to load YAML");
        let marked_yaml = doc.first().unwrap();
        let yaml_schema = YamlSchema::try_from(marked_yaml).unwrap();
        let YamlSchema::Subschema(subschema) = yaml_schema else {
            panic!("Expected a subschema");
        };
        assert!(!subschema.r#type.is_none());
        assert!(subschema.r#type.is_single());
        let SchemaType::Single(type_value) = subschema.r#type else {
            panic!("Expected a single type");
        };
        assert_eq!(type_value, "boolean");
    }

    #[test]
    fn test_metadata_and_annotations_try_from() {
        let yaml = r#"
        $id: http://example.com/schema
        $schema: http://example.com/schema
        title: Example Schema
        description: This is an example schema
        "#;
        let doc = MarkedYaml::load_from_str(yaml).expect("Failed to load YAML");
        let marked_yaml = doc.first().unwrap();
        assert!(marked_yaml.data.is_mapping());
        let YamlData::Mapping(mapping) = &marked_yaml.data else {
            panic!("Expected a mapping");
        };
        let metadata_and_annotations = MetadataAndAnnotations::try_from(mapping).unwrap();
        assert_eq!(
            metadata_and_annotations.id,
            Some("http://example.com/schema".to_string())
        );
        assert_eq!(
            metadata_and_annotations.schema,
            Some("http://example.com/schema".to_string())
        );
        assert_eq!(
            metadata_and_annotations.title,
            Some("Example Schema".to_string())
        );
        assert_eq!(
            metadata_and_annotations.description,
            Some("This is an example schema".to_string())
        );
    }

    #[test]
    fn test_yaml_schema_with_multiple_types() {
        let yaml = r#"
        type:
          - boolean
          - number
          - integer
          - string
        "#;
        let doc = MarkedYaml::load_from_str(yaml).expect("Failed to load YAML");
        let marked_yaml = doc.first().unwrap();
        let yaml_schema = YamlSchema::try_from(marked_yaml).unwrap();
        let YamlSchema::Subschema(subschema) = yaml_schema else {
            panic!("Expected a subschema");
        };
        assert!(!subschema.r#type.is_none());
        assert!(subschema.r#type.is_multiple());
        let SchemaType::Multiple(type_values) = subschema.r#type else {
            panic!("Expected a multiple type");
        };
        assert_eq!(type_values, vec!["boolean", "number", "integer", "string"]);
    }

    #[test]
    fn test_multiple_types() {
        let schema = r#"
        type:
          - string
          - number
        "#;
        let schema = loader::load_from_str(schema).unwrap();

        let s = "I'm a string";
        let docs = MarkedYaml::load_from_str(s).unwrap();
        let value = docs.first().unwrap();
        let context = Context::default();
        let result = schema.validate(&context, value);
        assert!(result.is_ok());
        assert!(!context.has_errors());

        let s = "42";
        let docs = MarkedYaml::load_from_str(s).unwrap();
        let value = docs.first().unwrap();
        let context = Context::default();
        let result = schema.validate(&context, value);
        assert!(result.is_ok());
        assert!(!context.has_errors());

        let s = "null";
        let docs = MarkedYaml::load_from_str(s).unwrap();
        let value = docs.first().unwrap();
        let context = Context::default();
        let result = schema.validate(&context, value);
        assert!(result.is_ok());
        assert!(context.has_errors());
        let errors = context.errors.borrow();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].error, "None of type: [string, number] matched");
    }

    #[test]
    fn properties_without_type_infers_object_and_validates() {
        let yaml = r#"
        properties:
          foo:
            type: string
        required:
          - foo
        "#;
        let root = loader::load_from_str(yaml).unwrap();
        let YamlSchema::Subschema(sub) = &root.schema else {
            panic!("expected subschema");
        };
        assert!(
            sub.r#type.is_or_contains("object"),
            "expected inferred type object"
        );
        assert!(sub.object_schema.is_some());

        let ok = engine::Engine::evaluate(&root, "foo: bar", false).unwrap();
        assert!(!ok.has_errors());

        let bad = engine::Engine::evaluate(&root, "other: x", false).unwrap();
        assert!(bad.has_errors());
    }

    #[test]
    fn test_object_schema_with_const_property() {
        let schema = r#"
        type: object
        properties:
          const:
            description: A scalar value that must match the value
            type:
              - string
              - integer
              - number
              - boolean
        "#;
        let schema = loader::load_from_str(schema).expect("Failed to load schema");

        let docs = MarkedYaml::load_from_str(
            r#"
        const: "I'm a string"
        "#,
        )
        .unwrap();
        let value = docs.first().unwrap();
        let context = Context::default();
        let result = schema.validate(&context, value);
        assert!(result.is_ok());
        assert!(!context.has_errors());
    }

    #[test]
    fn unevaluated_properties_all_of_extra_key_rejected() {
        let root = loader::load_from_str(
            r#"
            allOf:
              - properties:
                  a:
                    type: string
              - unevaluatedProperties: false
            "#,
        )
        .unwrap();
        let ok = engine::Engine::evaluate(&root, "a: ok", false).unwrap();
        assert!(!ok.has_errors());
        let bad = engine::Engine::evaluate(&root, "a: ok\nb: no", false).unwrap();
        assert!(bad.has_errors());
    }
}