jsonschema 0.46.0

JSON schema validaton library
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
//! Implementation of the `unevaluatedProperties` keyword.
//!
//! This keyword validates properties that were not evaluated by other keywords like
//! `properties`, `additionalProperties`, `patternProperties`, or nested schemas in
//! combinators (`allOf`, `anyOf`, `oneOf`), conditionals, and references.
//!
//! The implementation eagerly compiles a recursive `PropertyValidators` structure during
//! schema compilation, using `Arc<OnceLock>` for circular reference handling.
use ahash::AHashSet;
use fancy_regex::Regex;
use serde_json::{Map, Value};
use std::sync::{Arc, OnceLock};

use crate::{
    compiler, ecma,
    evaluation::ErrorDescription,
    node::SchemaNode,
    paths::{LazyEvaluationPath, LazyLocation, Location, RefTracker},
    validator::{EvaluationResult, Validate, ValidationContext},
    ValidationError,
};

use super::CompilationResult;

/// Lazy property validators that are compiled on first access.
/// Used for $recursiveRef and circular references to handle cycles during compilation.
pub(crate) type PendingPropertyValidators = Arc<OnceLock<PropertyValidators>>;

/// Holds compiled validators for property evaluation in unevaluatedProperties.
/// This structure is built during schema compilation and used during validation.
#[derive(Debug, Clone)]
pub(crate) struct PropertyValidators {
    /// Property names from "properties" keyword for O(1) lookup
    properties: AHashSet<String>,
    /// Validator from "additionalProperties" keyword
    additional: Option<SchemaNode>,
    /// Pattern-based property validators from "patternProperties" keyword
    pattern_properties: Vec<(Regex, SchemaNode)>,
    /// Validator from "unevaluatedProperties" keyword itself
    unevaluated: Option<SchemaNode>,
    /// Validators from "allOf" keyword - both the schema and its property validators
    all_of: Vec<(SchemaNode, PropertyValidators)>,
    /// Validators from "anyOf" keyword
    any_of: Vec<(SchemaNode, PropertyValidators)>,
    /// Validators from "oneOf" keyword
    one_of: Vec<(SchemaNode, PropertyValidators)>,
    /// Conditional validators from "if/then/else" keywords
    conditional: Option<Box<ConditionalValidators>>,
    /// Reference validators from "$ref" keyword (may be circular)
    ref_: Option<RefValidator>,
    /// Reference validators from "$dynamicRef" keyword
    dynamic_ref: Option<Box<PropertyValidators>>,
    /// Validators from "$recursiveRef" keyword (Draft 2019-09 only)
    /// Uses pending pattern to handle circular references
    recursive_ref: Option<PendingPropertyValidators>,
    /// Dependent schema validators from "dependentSchemas" keyword
    dependent: Vec<(String, PropertyValidators)>,
}

/// Reference validator - just wraps `PropertyValidators`
/// Circular references are handled by returning None during compilation
#[derive(Debug, Clone)]
struct RefValidator(Box<PropertyValidators>);

/// Conditional validators from "if/then/else" keywords
#[derive(Debug, Clone)]
struct ConditionalValidators {
    condition: SchemaNode,
    if_: PropertyValidators,
    then_: Option<PropertyValidators>,
    else_: Option<PropertyValidators>,
}

impl PropertyValidators {
    /// Core implementation for marking evaluated properties.
    ///
    /// When `include_unevaluated` is `true` (used by `is_valid`/`validate`), also marks
    /// properties validated by `unevaluatedProperties` itself — needed so nested schemas
    /// can propagate evaluations upward. When `false` (used by `evaluate`), those properties
    /// are left unmarked so `evaluate_instance()` is called on them to collect annotations.
    fn mark_evaluated_properties_impl<'i>(
        &self,
        instance: &'i Value,
        properties: &mut AHashSet<&'i String>,
        ctx: &mut ValidationContext,
        include_unevaluated: bool,
    ) {
        // Handle $ref first
        if let Some(ref_) = &self.ref_ {
            ref_.0.mark_evaluated_properties(instance, properties, ctx);
        }

        // Handle $recursiveRef (Draft 2019-09 only)
        // Skip if not yet initialized (circular reference) - properties will be tracked by parent
        if let Some(recursive_ref) = &self.recursive_ref {
            if let Some(validators) = recursive_ref.get() {
                validators.mark_evaluated_properties(instance, properties, ctx);
            }
        }

        // Handle $dynamicRef (Draft 2020-12+)
        if let Some(dynamic_ref) = &self.dynamic_ref {
            dynamic_ref.mark_evaluated_properties(instance, properties, ctx);
        }

        // Process properties on the instance
        if let Value::Object(obj) = instance {
            // Mark properties from "properties" keyword (O(1) lookup)
            for property in obj.keys() {
                if self.properties.contains(property) {
                    properties.insert(property);
                }
            }

            // Check "patternProperties" keyword - mark if property name matches
            if !self.pattern_properties.is_empty() {
                for property in obj.keys() {
                    if properties.contains(property) {
                        continue; // Already marked by "properties"
                    }
                    for (pattern, _) in &self.pattern_properties {
                        if pattern.is_match(property).unwrap_or(false) {
                            properties.insert(property);
                            break;
                        }
                    }
                }
            }

            // Check "additionalProperties" keyword - applies to properties NOT in properties/patternProperties
            // This must be done after marking all properties/patternProperties to avoid order dependency
            if self.additional.is_some() {
                for property in obj.keys() {
                    // Only mark if not already marked by properties or patternProperties
                    if !properties.contains(property) {
                        properties.insert(property);
                    }
                }
            }

            // Check "unevaluatedProperties" keyword - marks properties that validate successfully.
            // This is crucial for nested unevaluatedProperties: a child schema's unevaluatedProperties
            // can mark properties as evaluated for parent schemas.
            // Skipped when called from evaluate() so evaluate_instance() can collect annotations.
            if include_unevaluated {
                if let Some(unevaluated) = &self.unevaluated {
                    for (property, value) in obj {
                        // Skip if already marked - avoid redundant validation
                        if properties.contains(property) {
                            continue;
                        }
                        if unevaluated.is_valid(value, ctx) {
                            properties.insert(property);
                        }
                    }
                }
            }

            // Check "dependentSchemas" keyword
            for (dep_property, dep_validators) in &self.dependent {
                if obj.contains_key(dep_property) {
                    dep_validators.mark_evaluated_properties(instance, properties, ctx);
                }
            }
        }

        // Handle "if/then/else" keywords
        if let Some(conditional) = &self.conditional {
            conditional.mark_evaluated_properties(instance, properties, ctx);
        }

        // Handle "allOf" keyword
        for (node, validators) in &self.all_of {
            if node.is_valid(instance, ctx) {
                validators.mark_evaluated_properties(instance, properties, ctx);
            }
        }

        // Handle "anyOf" keyword
        for (node, validators) in &self.any_of {
            if node.is_valid(instance, ctx) {
                validators.mark_evaluated_properties(instance, properties, ctx);
            }
        }

        // Handle "oneOf" keyword - only if exactly one matches
        // Short-circuit: stop checking after finding 2 matches
        let mut match_count = 0;
        let mut matched_validators = None;
        for (node, validators) in &self.one_of {
            if node.is_valid(instance, ctx) {
                match_count += 1;
                if match_count > 1 {
                    break; // More than one match, don't mark any properties
                }
                matched_validators = Some(validators);
            }
        }
        if match_count == 1 {
            if let Some(validators) = matched_validators {
                validators.mark_evaluated_properties(instance, properties, ctx);
            }
        }
    }

    /// Mark all properties evaluated by this schema (including by `unevaluatedProperties` itself).
    fn mark_evaluated_properties<'i>(
        &self,
        instance: &'i Value,
        properties: &mut AHashSet<&'i String>,
        ctx: &mut ValidationContext,
    ) {
        self.mark_evaluated_properties_impl(instance, properties, ctx, true);
    }

    /// Mark properties evaluated by all keywords *except* `unevaluatedProperties` itself.
    ///
    /// Used in `evaluate()` so that properties that would be covered by `unevaluatedProperties`
    /// are still visited by `evaluate_instance()`, allowing their annotations to be collected.
    fn mark_evaluated_by_other_keywords<'i>(
        &self,
        instance: &'i Value,
        properties: &mut AHashSet<&'i String>,
        ctx: &mut ValidationContext,
    ) {
        self.mark_evaluated_properties_impl(instance, properties, ctx, false);
    }
}

impl ConditionalValidators {
    fn mark_evaluated_properties<'i>(
        &self,
        instance: &'i Value,
        properties: &mut AHashSet<&'i String>,
        ctx: &mut ValidationContext,
    ) {
        if self.condition.is_valid(instance, ctx) {
            self.if_
                .mark_evaluated_properties(instance, properties, ctx);
            if let Some(then_) = &self.then_ {
                then_.mark_evaluated_properties(instance, properties, ctx);
            }
        } else if let Some(else_) = &self.else_ {
            else_.mark_evaluated_properties(instance, properties, ctx);
        }
    }
}

/// Compile all property validators for a schema.
///
/// Recursively builds the `PropertyValidators` tree by examining all keywords that
/// can evaluate properties. Handles circular references via pending nodes cached
/// by location and schema pointer.
fn compile_property_validators<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<PropertyValidators, ValidationError<'a>> {
    // Create a pending node and cache it before compiling to handle circular refs
    let cache_key = ctx.location_cache_key();
    let pending = Arc::new(OnceLock::new());
    ctx.cache_pending_property_validators(cache_key.clone(), pending.clone());
    ctx.cache_pending_property_validators_for_schema(parent, pending.clone());

    // Compile all parts
    let validators = PropertyValidators {
        properties: compile_properties(ctx, parent)?,
        additional: compile_additional(ctx, parent)?,
        pattern_properties: compile_pattern_properties(ctx, parent)?,
        unevaluated: compile_unevaluated(ctx, parent)?,
        all_of: compile_all_of(ctx, parent)?,
        any_of: compile_any_of(ctx, parent)?,
        one_of: compile_one_of(ctx, parent)?,
        conditional: compile_conditional(ctx, parent)?,
        ref_: compile_ref(ctx, parent).map_err(ValidationError::to_owned)?,
        dynamic_ref: compile_dynamic_ref(ctx, parent).map_err(ValidationError::to_owned)?,
        recursive_ref: compile_recursive_ref(ctx, parent)?,
        dependent: compile_dependent(ctx, parent)?,
    };

    // Initialize the pending node. This should always succeed since we just created it.
    pending
        .set(validators.clone())
        .expect("pending node should not be initialized yet");

    // Remove from pending cache
    ctx.remove_pending_property_validators(&cache_key);
    ctx.remove_pending_property_validators_for_schema(parent);

    Ok(validators)
}

fn compile_properties<'a>(
    _ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<AHashSet<String>, ValidationError<'a>> {
    let Some(Value::Object(map)) = parent.get("properties") else {
        return Ok(AHashSet::new());
    };
    // Only need property names for evaluation tracking, not the validators
    Ok(map.keys().cloned().collect())
}

fn compile_additional<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<SchemaNode>, ValidationError<'a>> {
    let Some(subschema) = parent.get("additionalProperties") else {
        return Ok(None);
    };

    let additional_ctx = ctx.new_at_location("additionalProperties");
    let node = compiler::compile(&additional_ctx, additional_ctx.as_resource_ref(subschema))
        .map_err(ValidationError::to_owned)?;
    Ok(Some(node))
}

fn compile_pattern_properties<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Vec<(Regex, SchemaNode)>, ValidationError<'a>> {
    let Some(Value::Object(patterns)) = parent.get("patternProperties") else {
        return Ok(Vec::new());
    };

    let pat_ctx = ctx.new_at_location("patternProperties");
    let mut result = Vec::with_capacity(patterns.len());

    for (pattern, schema) in patterns {
        let schema_ctx = pat_ctx.new_at_location(pattern.as_str());
        let Ok(regex) = ecma::to_rust_regex(pattern).and_then(|p| Regex::new(&p).map_err(|_| ()))
        else {
            return Err(ValidationError::format(
                schema_ctx.location().clone(),
                LazyEvaluationPath::SameAsSchemaPath,
                Location::new(),
                schema,
                "regex",
            ));
        };
        let node = compiler::compile(&schema_ctx, schema_ctx.as_resource_ref(schema))
            .map_err(ValidationError::to_owned)?;
        result.push((regex, node));
    }

    Ok(result)
}

fn compile_unevaluated<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<SchemaNode>, ValidationError<'a>> {
    let Some(subschema) = parent.get("unevaluatedProperties") else {
        return Ok(None);
    };

    let unevaluated_ctx = ctx.new_at_location("unevaluatedProperties");
    let node = compiler::compile(&unevaluated_ctx, unevaluated_ctx.as_resource_ref(subschema))
        .map_err(ValidationError::to_owned)?;
    Ok(Some(node))
}

fn compile_all_of<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Vec<(SchemaNode, PropertyValidators)>, ValidationError<'a>> {
    let Some(Some(subschemas)) = parent.get("allOf").map(Value::as_array) else {
        return Ok(Vec::new());
    };

    let all_of_ctx = ctx.new_at_location("allOf");
    let mut result = Vec::with_capacity(subschemas.len());

    for (idx, subschema) in subschemas.iter().enumerate() {
        let subschema_ctx = all_of_ctx.new_at_location(idx);
        let node = compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema))
            .map_err(ValidationError::to_owned)?;

        if let Value::Object(obj) = subschema {
            let validators = compile_property_validators(&subschema_ctx, obj)?;
            result.push((node, validators));
        }
    }

    Ok(result)
}

fn compile_any_of<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Vec<(SchemaNode, PropertyValidators)>, ValidationError<'a>> {
    let Some(Some(subschemas)) = parent.get("anyOf").map(Value::as_array) else {
        return Ok(Vec::new());
    };

    let any_of_ctx = ctx.new_at_location("anyOf");
    let mut result = Vec::with_capacity(subschemas.len());

    for (idx, subschema) in subschemas.iter().enumerate() {
        let subschema_ctx = any_of_ctx.new_at_location(idx);
        let node = compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema))
            .map_err(ValidationError::to_owned)?;

        if let Value::Object(obj) = subschema {
            let validators = compile_property_validators(&subschema_ctx, obj)?;
            result.push((node, validators));
        }
    }

    Ok(result)
}

fn compile_one_of<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Vec<(SchemaNode, PropertyValidators)>, ValidationError<'a>> {
    let Some(Some(subschemas)) = parent.get("oneOf").map(Value::as_array) else {
        return Ok(Vec::new());
    };

    let one_of_ctx = ctx.new_at_location("oneOf");
    let mut result = Vec::with_capacity(subschemas.len());

    for (idx, subschema) in subschemas.iter().enumerate() {
        let subschema_ctx = one_of_ctx.new_at_location(idx);
        let node = compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema))
            .map_err(ValidationError::to_owned)?;

        if let Value::Object(obj) = subschema {
            let validators = compile_property_validators(&subschema_ctx, obj)?;
            result.push((node, validators));
        }
    }

    Ok(result)
}

fn compile_conditional<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<Box<ConditionalValidators>>, ValidationError<'a>> {
    let Some(Value::Object(if_schema)) = parent.get("if") else {
        return Ok(None);
    };

    let if_ctx = ctx.new_at_location("if");
    let condition = compiler::compile(
        &if_ctx,
        if_ctx.as_resource_ref(&Value::Object(if_schema.clone())),
    )
    .map_err(ValidationError::to_owned)?;
    let if_ = compile_property_validators(&if_ctx, if_schema)?;

    let then_ = if let Some(Value::Object(then_schema)) = parent.get("then") {
        let then_ctx = ctx.new_at_location("then");
        Some(compile_property_validators(&then_ctx, then_schema)?)
    } else {
        None
    };

    let else_ = if let Some(Value::Object(else_schema)) = parent.get("else") {
        let else_ctx = ctx.new_at_location("else");
        Some(compile_property_validators(&else_ctx, else_schema)?)
    } else {
        None
    };

    Ok(Some(Box::new(ConditionalValidators {
        condition,
        if_,
        then_,
        else_,
    })))
}

fn compile_ref<'a>(
    ctx: &compiler::Context<'_>,
    parent: &Map<String, Value>,
) -> Result<Option<RefValidator>, ValidationError<'a>> {
    let Some(Value::String(reference)) = parent.get("$ref") else {
        return Ok(None);
    };

    let resolved = ctx.lookup(reference).map_err(ValidationError::from)?;

    let (contents, resolver, draft) = resolved.into_inner();
    if let Value::Object(subschema) = &contents {
        let vocabularies = ctx.find_vocabularies(draft, contents);
        let ref_ctx =
            ctx.with_resolver_and_draft(resolver, draft, vocabularies, ctx.location().clone());
        let validators =
            compile_property_validators(&ref_ctx, subschema).map_err(ValidationError::to_owned)?;
        Ok(Some(RefValidator(Box::new(validators))))
    } else {
        Ok(None)
    }
}

fn compile_dynamic_ref<'a>(
    ctx: &compiler::Context<'_>,
    parent: &Map<String, Value>,
) -> Result<Option<Box<PropertyValidators>>, ValidationError<'a>> {
    let Some(Value::String(reference)) = parent.get("$dynamicRef") else {
        return Ok(None);
    };

    let resolved = ctx.lookup(reference).map_err(ValidationError::from)?;

    let (contents, resolver, draft) = resolved.into_inner();
    if let Value::Object(subschema) = &contents {
        let vocabularies = ctx.find_vocabularies(draft, contents);
        let ref_ctx =
            ctx.with_resolver_and_draft(resolver, draft, vocabularies, ctx.location().clone());
        let validators =
            compile_property_validators(&ref_ctx, subschema).map_err(ValidationError::to_owned)?;
        Ok(Some(Box::new(validators)))
    } else {
        Ok(None)
    }
}

fn compile_recursive_ref<'a>(
    ctx: &compiler::Context<'_>,
    parent: &Map<String, Value>,
) -> Result<Option<PendingPropertyValidators>, ValidationError<'a>> {
    if !parent.contains_key("$recursiveRef") {
        return Ok(None);
    }

    // For $recursiveRef, we need to resolve the reference and check if it's already being compiled
    let resolved = ctx
        .lookup_recursive_reference()
        .map_err(ValidationError::from)?;

    // Create context for the resolved reference and check its cache key
    let (contents, resolver, draft) = resolved.into_inner();
    if let Value::Object(subschema) = &contents {
        let vocabularies = ctx.find_vocabularies(draft, contents);
        let ref_ctx =
            ctx.with_resolver_and_draft(resolver, draft, vocabularies, ctx.location().clone());

        // Check if we're already compiling this schema (circular reference)
        if let Some(pending) = ref_ctx.get_pending_property_validators_for_schema(subschema) {
            return Ok(Some(pending));
        }

        let cache_key = ref_ctx.location_cache_key();
        if let Some(pending) = ref_ctx.get_pending_property_validators(&cache_key) {
            // Circular reference detected - return the pending node
            return Ok(Some(pending));
        }

        // Not circular, compile normally
        let validators =
            compile_property_validators(&ref_ctx, subschema).map_err(ValidationError::to_owned)?;
        let pending = Arc::new(OnceLock::new());
        let _ = pending.set(validators);
        Ok(Some(pending))
    } else {
        Ok(None)
    }
}

fn compile_dependent<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Vec<(String, PropertyValidators)>, ValidationError<'a>> {
    let Some(Value::Object(map)) = parent.get("dependentSchemas") else {
        return Ok(Vec::new());
    };

    let dependent_ctx = ctx.new_at_location("dependentSchemas");
    let mut result = Vec::with_capacity(map.len());

    for (property, subschema) in map {
        if let Value::Object(obj) = subschema {
            let property_ctx = dependent_ctx.new_at_location(property.as_str());
            let validators = compile_property_validators(&property_ctx, obj)?;
            result.push((property.clone(), validators));
        }
    }

    Ok(result)
}

/// Validator for the `unevaluatedProperties` keyword.
pub(crate) struct UnevaluatedPropertiesValidator {
    location: Location,
    validators: PropertyValidators,
}

impl UnevaluatedPropertiesValidator {
    pub(crate) fn compile<'a>(
        ctx: &'a compiler::Context,
        parent: &'a Map<String, Value>,
    ) -> CompilationResult<'a> {
        let validators =
            compile_property_validators(ctx, parent).map_err(ValidationError::to_owned)?;

        Ok(Box::new(UnevaluatedPropertiesValidator {
            location: ctx.location().join("unevaluatedProperties"),
            validators,
        }))
    }
}

impl Validate for UnevaluatedPropertiesValidator {
    fn validate<'i>(
        &self,
        instance: &'i Value,
        location: &LazyLocation,
        tracker: Option<&RefTracker>,
        ctx: &mut ValidationContext,
    ) -> Result<(), ValidationError<'i>> {
        if let Value::Object(properties) = instance {
            let mut evaluated = AHashSet::with_capacity(properties.len());

            // Mark all evaluated properties
            self.validators
                .mark_evaluated_properties(instance, &mut evaluated, ctx);

            // Early return if all properties are evaluated
            if evaluated.len() == properties.len() {
                return Ok(());
            }

            // Check for unevaluated properties
            let mut unevaluated = Vec::new();
            for (property, value) in properties {
                if evaluated.contains(property) {
                    continue;
                }
                // Check against unevaluatedProperties schema
                if let Some(unevaluated_schema) = &self.validators.unevaluated {
                    if !unevaluated_schema.is_valid(value, ctx) {
                        unevaluated.push(property.clone());
                    }
                } else {
                    // No unevaluatedProperties schema means false (reject all)
                    unevaluated.push(property.clone());
                }
            }

            if !unevaluated.is_empty() {
                return Err(ValidationError::unevaluated_properties(
                    self.location.clone(),
                    crate::paths::capture_evaluation_path(tracker, &self.location),
                    location.into(),
                    instance,
                    unevaluated,
                ));
            }
        }
        Ok(())
    }

    fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool {
        if let Value::Object(properties) = instance {
            let mut evaluated = AHashSet::with_capacity(properties.len());
            self.validators
                .mark_evaluated_properties(instance, &mut evaluated, ctx);

            // Early return if all properties are evaluated
            if evaluated.len() == properties.len() {
                return true;
            }

            for (property, value) in properties {
                if evaluated.contains(property) {
                    continue;
                }
                if let Some(unevaluated_schema) = &self.validators.unevaluated {
                    if !unevaluated_schema.is_valid(value, ctx) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
        true
    }

    fn evaluate(
        &self,
        instance: &Value,
        location: &LazyLocation,
        tracker: Option<&RefTracker>,
        ctx: &mut ValidationContext,
    ) -> EvaluationResult {
        if let Value::Object(properties) = instance {
            let mut evaluated = AHashSet::with_capacity(properties.len());
            self.validators
                .mark_evaluated_by_other_keywords(instance, &mut evaluated, ctx);
            let mut children = Vec::new();
            let mut unevaluated = Vec::new();
            let mut invalid = false;

            for (property, value) in properties {
                if evaluated.contains(property) {
                    continue;
                }
                if let Some(validator) = &self.validators.unevaluated {
                    let child =
                        validator.evaluate_instance(value, &location.push(property), tracker, ctx);
                    if !child.valid {
                        invalid = true;
                        unevaluated.push(property.clone());
                    }
                    children.push(child);
                } else {
                    invalid = true;
                    unevaluated.push(property.clone());
                }
            }

            let mut errors = Vec::new();
            if !unevaluated.is_empty() {
                errors.push(ErrorDescription::from_validation_error(
                    &ValidationError::unevaluated_properties(
                        self.location.clone(),
                        crate::paths::capture_evaluation_path(tracker, &self.location),
                        location.into(),
                        instance,
                        unevaluated,
                    ),
                ));
            }

            if invalid {
                EvaluationResult::Invalid {
                    errors,
                    children,
                    annotations: None,
                }
            } else {
                EvaluationResult::Valid {
                    annotations: None,
                    children,
                }
            }
        } else {
            EvaluationResult::valid_empty()
        }
    }
}

pub(crate) fn compile<'a>(
    ctx: &'a compiler::Context,
    parent: &'a Map<String, Value>,
    schema: &'a Value,
) -> Option<CompilationResult<'a>> {
    match schema.as_bool() {
        Some(true) => None, // unevaluatedProperties: true is a no-op
        _ => Some(UnevaluatedPropertiesValidator::compile(ctx, parent)),
    }
}

#[cfg(test)]
mod tests {
    use crate::error::ValidationErrorKind;
    use serde_json::json;

    #[test]
    fn recursive_ref_preserves_unevaluated_properties() {
        let schema = json!({
            "$schema": "https://json-schema.org/draft/2019-09/schema",
            "$id": "https://example.com/root",
            "$recursiveAnchor": true,
            "type": "object",
            "properties": {
                "child": {
                    "type": "object",
                    "properties": {
                        "child": { "$recursiveRef": "#" }
                    },
                    "unevaluatedProperties": false
                }
            },
            "unevaluatedProperties": false
        });

        let validator = crate::options().build(&schema).expect("schema compiles");

        let valid = json!({"child": {"child": {}}});
        assert!(
            validator.is_valid(&valid),
            "expected recursive schema without extras to be valid"
        );

        let invalid = json!({"child": {"child": {"unexpected": 1}}});
        assert!(
            !validator.is_valid(&invalid),
            "unexpected properties should be rejected"
        );

        let errors: Vec<_> = validator.iter_errors(&invalid).collect();
        assert!(
            errors.iter().any(|err| matches!(
                err.kind(),
                ValidationErrorKind::UnevaluatedProperties { .. }
            )),
            "expected unevaluatedProperties error, got {errors:?}"
        );
    }
}