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
//! Implementation of the `unevaluatedItems` keyword.
//!
//! This keyword validates array items that were not evaluated by other keywords like
//! `items`, `prefixItems`, `contains`, or nested schemas in combinators (`allOf`, `anyOf`, `oneOf`),
//! conditionals, and references.
//!
//! The implementation eagerly compiles a recursive `ItemsValidators` structure during
//! schema compilation, using `Arc<OnceLock>` for circular reference handling.
use referencing::Draft;
use serde_json::{Map, Value};
use std::sync::{Arc, OnceLock};

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

use super::CompilationResult;

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

/// Holds compiled validators for items evaluation in unevaluatedItems.
/// This structure is built during schema compilation and used during validation.
#[derive(Debug, Clone)]
pub(crate) struct ItemsValidators {
    /// Validator from "unevaluatedItems" keyword itself
    unevaluated: Option<SchemaNode>,
    /// Validator from "contains" keyword
    contains: Option<SchemaNode>,
    /// Reference validators from "$ref" keyword
    ref_: Option<RefValidator>,
    /// Reference validators from "$dynamicRef" keyword (Draft 2020-12+)
    dynamic_ref: Option<Box<ItemsValidators>>,
    /// Validators from "$recursiveRef" keyword (Draft 2019-09 only)
    recursive_ref: Option<PendingItemsValidators>,
    /// Items limit - for Draft 2019-09 "items" keyword behavior
    /// If present, marks first N items as evaluated
    items_limit: Option<usize>,
    /// Items schema present - for Draft 2020-12+ "items" keyword
    /// If true, marks ALL items as evaluated
    items_all: bool,
    /// Prefix items count - from "prefixItems" keyword
    prefix_items: Option<usize>,
    /// Conditional validators from "if/then/else" keywords
    conditional: Option<Box<ConditionalValidators>>,
    /// Validators from "allOf" keyword
    all_of: Option<Vec<(SchemaNode, ItemsValidators)>>,
    /// Validators from "anyOf" keyword
    any_of: Option<Vec<(SchemaNode, ItemsValidators)>>,
    /// Validators from "oneOf" keyword
    one_of: Option<Vec<(SchemaNode, ItemsValidators)>>,
}

/// Reference validator - wraps `ItemsValidators`
#[derive(Debug, Clone)]
struct RefValidator(Box<ItemsValidators>);

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

impl ItemsValidators {
    /// Core implementation for marking evaluated indexes.
    ///
    /// When `include_unevaluated` is `true` (used by `is_valid`/`validate`), also marks
    /// items validated by `unevaluatedItems` itself — needed so nested schemas can propagate
    /// evaluations upward. When `false` (used by `evaluate`), those items are left unmarked
    /// so `evaluate_instance()` is called on them to collect annotations.
    fn mark_evaluated_indexes_impl(
        &self,
        instance: &Value,
        indexes: &mut Vec<bool>,
        ctx: &mut ValidationContext,
        include_unevaluated: bool,
    ) {
        // Early return optimization: if items marks ALL items, no need to check anything else
        if self.items_all {
            // Draft 2020-12+: items keyword marks ALL items as evaluated
            for idx in indexes.iter_mut() {
                *idx = true;
            }
            return;
        }

        // Handle $ref first
        if let Some(ref_) = &self.ref_ {
            ref_.0.mark_evaluated_indexes(instance, indexes, ctx);
        }

        // Handle $recursiveRef (Draft 2019-09 only)
        if let Some(recursive_ref) = &self.recursive_ref {
            if let Some(validators) = recursive_ref.get() {
                validators.mark_evaluated_indexes(instance, indexes, ctx);
            }
        }

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

        // Mark items based on items/prefixItems keywords
        if let Some(limit) = self.items_limit {
            // Draft 2019-09: items (as array) marks first N items
            for idx in indexes.iter_mut().take(limit) {
                *idx = true;
            }
        }

        if let Some(limit) = self.prefix_items {
            // prefixItems marks first N items
            for idx in indexes.iter_mut().take(limit) {
                *idx = true;
            }
        }

        // Early exit if all items are already evaluated
        if indexes.iter().all(|&evaluated| evaluated) {
            return;
        }

        // Process contains and (optionally) unevaluatedItems
        if let Value::Array(items) = instance {
            for (item, is_evaluated) in items.iter().zip(indexes.iter_mut()) {
                if *is_evaluated {
                    continue;
                }
                // contains marks items that match
                if let Some(validator) = &self.contains {
                    if validator.is_valid(item, ctx) {
                        *is_evaluated = true;
                        continue;
                    }
                }
                // unevaluatedItems itself can mark items.
                // Skipped when called from evaluate() so evaluate_instance() can collect annotations.
                if include_unevaluated {
                    if let Some(validator) = &self.unevaluated {
                        if validator.is_valid(item, ctx) {
                            *is_evaluated = true;
                        }
                    }
                }
            }
        }

        // Handle conditional
        if let Some(conditional) = &self.conditional {
            conditional.mark_evaluated_indexes(instance, indexes, ctx);
        }

        // Handle allOf - each schema that validates successfully marks items
        if let Some(all_of) = &self.all_of {
            for (validator, item_validators) in all_of {
                if validator.is_valid(instance, ctx) {
                    item_validators.mark_evaluated_indexes(instance, indexes, ctx);
                }
            }
        }

        // Handle anyOf - each schema that validates successfully marks items
        if let Some(any_of) = &self.any_of {
            for (validator, item_validators) in any_of {
                if validator.is_valid(instance, ctx) {
                    item_validators.mark_evaluated_indexes(instance, indexes, ctx);
                }
            }
        }

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

    /// Mark all items evaluated by this schema (including by `unevaluatedItems` itself).
    fn mark_evaluated_indexes(
        &self,
        instance: &Value,
        indexes: &mut Vec<bool>,
        ctx: &mut ValidationContext,
    ) {
        self.mark_evaluated_indexes_impl(instance, indexes, ctx, true);
    }

    /// Mark items evaluated by all keywords *except* `unevaluatedItems` itself.
    ///
    /// Used in `evaluate()` so that items that would be covered by `unevaluatedItems`
    /// are still visited by `evaluate_instance()`, allowing their annotations to be collected.
    fn mark_evaluated_indexes_by_other_keywords(
        &self,
        instance: &Value,
        indexes: &mut Vec<bool>,
        ctx: &mut ValidationContext,
    ) {
        self.mark_evaluated_indexes_impl(instance, indexes, ctx, false);
    }
}

impl ConditionalValidators {
    fn mark_evaluated_indexes(
        &self,
        instance: &Value,
        indexes: &mut Vec<bool>,
        ctx: &mut ValidationContext,
    ) {
        if self.condition.is_valid(instance, ctx) {
            self.if_.mark_evaluated_indexes(instance, indexes, ctx);
            if let Some(then_) = &self.then_ {
                then_.mark_evaluated_indexes(instance, indexes, ctx);
            }
        } else if let Some(else_) = &self.else_ {
            else_.mark_evaluated_indexes(instance, indexes, ctx);
        }
    }
}

/// Compile all items validators for a schema.
///
/// Recursively builds the `ItemsValidators` tree by examining all keywords that
/// can evaluate items. Handles circular references via pending nodes cached
/// by location and schema pointer.
fn compile_items_validators<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<ItemsValidators, ValidationError<'a>> {
    let unevaluated = compile_unevaluated(ctx, parent)?;
    let contains = compile_contains(ctx, parent)?;
    let ref_ = compile_ref(ctx, parent)?;
    let dynamic_ref = compile_dynamic_ref(ctx, parent)?;
    let recursive_ref = compile_recursive_ref(ctx, parent)?;

    // Determine items behavior based on draft
    let (items_limit, items_all) = compile_items(ctx, parent)?;
    let prefix_items = compile_prefix_items(ctx, parent)?;

    let conditional = compile_conditional(ctx, parent)?;
    let all_of = compile_all_of(ctx, parent)?;
    let any_of = compile_any_of(ctx, parent)?;
    let one_of = compile_one_of(ctx, parent)?;

    Ok(ItemsValidators {
        unevaluated,
        contains,
        ref_,
        dynamic_ref,
        recursive_ref,
        items_limit,
        items_all,
        prefix_items,
        conditional,
        all_of,
        any_of,
        one_of,
    })
}

fn compile_unevaluated<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<SchemaNode>, ValidationError<'a>> {
    if let Some(subschema) = parent.get("unevaluatedItems") {
        let unevaluated_ctx = ctx.new_at_location("unevaluatedItems");
        Ok(Some(
            compiler::compile(&unevaluated_ctx, unevaluated_ctx.as_resource_ref(subschema))
                .map_err(ValidationError::to_owned)?,
        ))
    } else {
        Ok(None)
    }
}

fn compile_contains<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<SchemaNode>, ValidationError<'a>> {
    if let Some(subschema) = parent.get("contains") {
        let contains_ctx = ctx.new_at_location("contains");
        Ok(Some(
            compiler::compile(&contains_ctx, contains_ctx.as_resource_ref(subschema))
                .map_err(ValidationError::to_owned)?,
        ))
    } else {
        Ok(None)
    }
}

fn compile_ref<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<RefValidator>, ValidationError<'a>> {
    if let Some(Value::String(reference)) = parent.get("$ref") {
        let resolved = ctx.lookup(reference)?;
        if let Value::Object(subschema) = resolved.contents() {
            let validators =
                compile_items_validators(ctx, subschema).map_err(ValidationError::to_owned)?;
            return Ok(Some(RefValidator(Box::new(validators))));
        }
    }
    Ok(None)
}

fn compile_dynamic_ref<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<Box<ItemsValidators>>, ValidationError<'a>> {
    if let Some(Value::String(reference)) = parent.get("$dynamicRef") {
        let resolved = ctx.lookup(reference)?;
        if let Value::Object(subschema) = resolved.contents() {
            let validators =
                compile_items_validators(ctx, subschema).map_err(ValidationError::to_owned)?;
            return Ok(Some(Box::new(validators)));
        }
    }
    Ok(None)
}

fn compile_recursive_ref<'a>(
    ctx: &compiler::Context<'_>,
    parent: &Map<String, Value>,
) -> Result<Option<PendingItemsValidators>, 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_items_validators_for_schema(subschema) {
            return Ok(Some(pending));
        }

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

        // Not circular, compile normally
        let validators =
            compile_items_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_items<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<(Option<usize>, bool), ValidationError<'a>> {
    if let Some(subschema) = parent.get("items") {
        if ctx.draft() == Draft::Draft201909
            || ctx.draft() == Draft::Draft7
            || ctx.draft() == Draft::Draft6
            || ctx.draft() == Draft::Draft4
        {
            // Older drafts: items can be array or object
            let limit = if parent.contains_key("additionalItems") || subschema.is_object() {
                usize::MAX
            } else {
                subschema.as_array().map_or(usize::MAX, std::vec::Vec::len)
            };
            Ok((Some(limit), false))
        } else {
            // Draft 2020-12+: items is always a schema that applies to all items
            Ok((None, true))
        }
    } else {
        Ok((None, false))
    }
}

fn compile_prefix_items<'a>(
    _ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<usize>, ValidationError<'a>> {
    if let Some(Some(items)) = parent.get("prefixItems").map(Value::as_array) {
        Ok(Some(items.len()))
    } else {
        Ok(None)
    }
}

fn compile_conditional<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<Box<ConditionalValidators>>, ValidationError<'a>> {
    if let Some(subschema) = parent.get("if") {
        if let Value::Object(if_parent) = subschema {
            let if_ctx = ctx.new_at_location("if");

            let mut then_ = None;
            if let Some(Value::Object(subschema)) = parent.get("then") {
                let then_ctx = ctx.new_at_location("then");
                then_ = Some(
                    compile_items_validators(&then_ctx, subschema)
                        .map_err(ValidationError::to_owned)?,
                );
            }

            let mut else_ = None;
            if let Some(Value::Object(subschema)) = parent.get("else") {
                let else_ctx = ctx.new_at_location("else");
                else_ = Some(
                    compile_items_validators(&else_ctx, subschema)
                        .map_err(ValidationError::to_owned)?,
                );
            }

            return Ok(Some(Box::new(ConditionalValidators {
                condition: compiler::compile(&if_ctx, if_ctx.as_resource_ref(subschema))
                    .map_err(ValidationError::to_owned)?,
                if_: compile_items_validators(&if_ctx, if_parent)
                    .map_err(ValidationError::to_owned)?,
                then_,
                else_,
            })));
        }
    }
    Ok(None)
}

fn compile_all_of<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<Vec<(SchemaNode, ItemsValidators)>>, ValidationError<'a>> {
    if let Some(Some(subschemas)) = parent.get("allOf").map(Value::as_array) {
        let all_of_ctx = ctx.new_at_location("allOf");
        let mut result = Vec::with_capacity(subschemas.len());

        for (idx, subschema) in subschemas.iter().enumerate() {
            if let Value::Object(parent) = subschema {
                let subschema_ctx = all_of_ctx.new_at_location(idx);
                result.push((
                    compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema))
                        .map_err(ValidationError::to_owned)?,
                    compile_items_validators(&subschema_ctx, parent)
                        .map_err(ValidationError::to_owned)?,
                ));
            }
        }

        Ok(Some(result))
    } else {
        Ok(None)
    }
}

fn compile_any_of<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<Vec<(SchemaNode, ItemsValidators)>>, ValidationError<'a>> {
    if let Some(Some(subschemas)) = parent.get("anyOf").map(Value::as_array) {
        let any_of_ctx = ctx.new_at_location("anyOf");
        let mut result = Vec::with_capacity(subschemas.len());

        for (idx, subschema) in subschemas.iter().enumerate() {
            if let Value::Object(parent) = subschema {
                let subschema_ctx = any_of_ctx.new_at_location(idx);
                result.push((
                    compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema))
                        .map_err(ValidationError::to_owned)?,
                    compile_items_validators(&subschema_ctx, parent)
                        .map_err(ValidationError::to_owned)?,
                ));
            }
        }

        Ok(Some(result))
    } else {
        Ok(None)
    }
}

fn compile_one_of<'a>(
    ctx: &compiler::Context<'_>,
    parent: &'a Map<String, Value>,
) -> Result<Option<Vec<(SchemaNode, ItemsValidators)>>, ValidationError<'a>> {
    if let Some(Some(subschemas)) = parent.get("oneOf").map(Value::as_array) {
        let one_of_ctx = ctx.new_at_location("oneOf");
        let mut result = Vec::with_capacity(subschemas.len());

        for (idx, subschema) in subschemas.iter().enumerate() {
            if let Value::Object(parent) = subschema {
                let subschema_ctx = one_of_ctx.new_at_location(idx);
                result.push((
                    compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema))
                        .map_err(ValidationError::to_owned)?,
                    compile_items_validators(&subschema_ctx, parent)
                        .map_err(ValidationError::to_owned)?,
                ));
            }
        }

        Ok(Some(result))
    } else {
        Ok(None)
    }
}

/// Validator for the `unevaluatedItems` keyword.
pub(crate) struct UnevaluatedItemsValidator {
    location: Location,
    validators: ItemsValidators,
}

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

        Ok(Box::new(UnevaluatedItemsValidator {
            location: ctx.location().join("unevaluatedItems"),
            validators,
        }))
    }
}

impl Validate for UnevaluatedItemsValidator {
    fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool {
        if let Value::Array(items) = instance {
            let mut indexes = vec![false; items.len()];
            self.validators
                .mark_evaluated_indexes(instance, &mut indexes, ctx);

            for (item, is_evaluated) in items.iter().zip(indexes) {
                if !is_evaluated {
                    if let Some(validator) = &self.validators.unevaluated {
                        if !validator.is_valid(item, ctx) {
                            return false;
                        }
                    } else {
                        // unevaluatedItems: false and item not evaluated
                        return false;
                    }
                }
            }
        }
        true
    }

    fn validate<'i>(
        &self,
        instance: &'i Value,
        location: &LazyLocation,
        tracker: Option<&RefTracker>,
        ctx: &mut ValidationContext,
    ) -> Result<(), ValidationError<'i>> {
        if let Value::Array(items) = instance {
            let mut indexes = vec![false; items.len()];
            self.validators
                .mark_evaluated_indexes(instance, &mut indexes, ctx);
            let mut unevaluated = vec![];

            for (item, is_evaluated) in items.iter().zip(indexes) {
                if !is_evaluated {
                    let is_valid = if let Some(validator) = &self.validators.unevaluated {
                        validator.is_valid(item, ctx)
                    } else {
                        false
                    };

                    if !is_valid {
                        unevaluated.push(item.to_string());
                    }
                }
            }

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

    fn evaluate(
        &self,
        instance: &Value,
        location: &LazyLocation,
        tracker: Option<&RefTracker>,
        ctx: &mut ValidationContext,
    ) -> EvaluationResult {
        if let Value::Array(items) = instance {
            let mut indexes = vec![false; items.len()];
            self.validators
                .mark_evaluated_indexes_by_other_keywords(instance, &mut indexes, ctx);
            let mut children = Vec::new();
            let mut unevaluated = Vec::new();
            let mut invalid = false;

            for (idx, (item, is_evaluated)) in items.iter().zip(indexes.iter()).enumerate() {
                if *is_evaluated {
                    continue;
                }
                if let Some(validator) = &self.validators.unevaluated {
                    let child =
                        validator.evaluate_instance(item, &location.push(idx), tracker, ctx);
                    if !child.valid {
                        invalid = true;
                        unevaluated.push(item.to_string());
                    }
                    children.push(child);
                } else {
                    invalid = true;
                    unevaluated.push(item.to_string());
                }
            }

            let mut errors = Vec::new();
            if !unevaluated.is_empty() {
                errors.push(ErrorDescription::from_validation_error(
                    &ValidationError::unevaluated_items(
                        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,
        _ => Some(UnevaluatedItemsValidator::compile(ctx, parent)),
    }
}

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

    #[test]
    fn test_unevaluated_items_with_recursion() {
        let schema = json!({
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "allOf": [
                {
                    "$ref": "#/$defs/array_1"
                }
            ],
            "unevaluatedItems": false,
            "$defs": {
                "array_1": {
                    "type": "array",
                    "prefixItems": [
                        {
                            "type": "string"
                        },
                        {
                            "allOf": [
                                {
                                    "$ref": "#/$defs/array_2"
                                }
                            ],
                            "type": "array",
                            "unevaluatedItems": false
                        }
                    ]
                },
                "array_2": {
                    "type": "array",
                    "prefixItems": [
                        {
                            "type": "number"
                        },
                        {
                            "allOf": [
                                {
                                    "$ref": "#/$defs/array_1"
                                }
                            ],
                            "type": "array",
                            "unevaluatedItems": false
                        }
                    ]
                }
            }
        });

        let validator = crate::validator_for(&schema).expect("Schema should compile");

        // This instance should fail validation because the nested array has an unevaluated item
        let instance = json!([
            "string",
            [
                42,
                [
                    "string",
                    [
                        42,
                        "unexpected" // This item should cause validation to fail
                    ]
                ]
            ]
        ]);

        assert!(!validator.is_valid(&instance));
        assert!(validator.validate(&instance).is_err());

        // This instance should pass validation as all items are evaluated
        let valid_instance = json!(["string", [42, ["string", [42]]]]);

        assert!(validator.is_valid(&valid_instance));
        assert!(validator.validate(&valid_instance).is_ok());
    }
}