| 1 | //! Implementation of the `unevaluatedItems` keyword. |
| 2 | //! |
| 3 | //! This keyword validates array items that were not evaluated by other keywords like |
| 4 | //! `items`, `prefixItems`, `contains`, or nested schemas in combinators (`allOf`, `anyOf`, `oneOf`), |
| 5 | //! conditionals, and references. |
| 6 | //! |
| 7 | //! The implementation eagerly compiles a recursive `ItemsValidators` structure during |
| 8 | //! schema compilation, using `Shared<OnceLock>` for circular reference handling. |
| 9 | use referencing::Draft; |
| 10 | use serde_json::{Map, Value}; |
| 11 | use std::sync::OnceLock; |
| 12 | |
| 13 | use crate::{ |
| 14 | compiler, |
| 15 | evaluation::ErrorDescription, |
| 16 | node::SchemaNode, |
| 17 | paths::{LazyLocation, Location}, |
| 18 | thread::Shared, |
| 19 | validator::{EvaluationResult, Validate, ValidationContext}, |
| 20 | ValidationError, |
| 21 | }; |
| 22 | |
| 23 | use super::CompilationResult; |
| 24 | |
| 25 | /// Lazy items validators that are compiled on first access. |
| 26 | /// Used for $recursiveRef and circular references to handle cycles during compilation. |
| 27 | pub(crate) type PendingItemsValidators = Shared<OnceLock<ItemsValidators>>; |
| 28 | |
| 29 | /// Holds compiled validators for items evaluation in unevaluatedItems. |
| 30 | /// This structure is built during schema compilation and used during validation. |
| 31 | #[derive(Debug, Clone)] |
| 32 | pub(crate) struct ItemsValidators { |
| 33 | /// Validator from "unevaluatedItems" keyword itself |
| 34 | unevaluated: Option<SchemaNode>, |
| 35 | /// Validator from "contains" keyword |
| 36 | contains: Option<SchemaNode>, |
| 37 | /// Reference validators from "$ref" keyword |
| 38 | ref_: Option<RefValidator>, |
| 39 | /// Reference validators from "$dynamicRef" keyword (Draft 2020-12+) |
| 40 | dynamic_ref: Option<Box<ItemsValidators>>, |
| 41 | /// Validators from "$recursiveRef" keyword (Draft 2019-09 only) |
| 42 | recursive_ref: Option<PendingItemsValidators>, |
| 43 | /// Items limit - for Draft 2019-09 "items" keyword behavior |
| 44 | /// If present, marks first N items as evaluated |
| 45 | items_limit: Option<usize>, |
| 46 | /// Items schema present - for Draft 2020-12+ "items" keyword |
| 47 | /// If true, marks ALL items as evaluated |
| 48 | items_all: bool, |
| 49 | /// Prefix items count - from "prefixItems" keyword |
| 50 | prefix_items: Option<usize>, |
| 51 | /// Conditional validators from "if/then/else" keywords |
| 52 | conditional: Option<Box<ConditionalValidators>>, |
| 53 | /// Validators from "allOf" keyword |
| 54 | all_of: Option<Vec<(SchemaNode, ItemsValidators)>>, |
| 55 | /// Validators from "anyOf" keyword |
| 56 | any_of: Option<Vec<(SchemaNode, ItemsValidators)>>, |
| 57 | /// Validators from "oneOf" keyword |
| 58 | one_of: Option<Vec<(SchemaNode, ItemsValidators)>>, |
| 59 | } |
| 60 | |
| 61 | /// Reference validator - wraps `ItemsValidators` |
| 62 | #[derive(Debug, Clone)] |
| 63 | struct RefValidator(Box<ItemsValidators>); |
| 64 | |
| 65 | /// Conditional validators from "if/then/else" keywords |
| 66 | #[derive(Debug, Clone)] |
| 67 | struct ConditionalValidators { |
| 68 | condition: SchemaNode, |
| 69 | if_: ItemsValidators, |
| 70 | then_: Option<ItemsValidators>, |
| 71 | else_: Option<ItemsValidators>, |
| 72 | } |
| 73 | |
| 74 | impl ItemsValidators { |
| 75 | /// Mark all items that are evaluated by this schema. |
| 76 | fn mark_evaluated_indexes( |
| 77 | &self, |
| 78 | instance: &Value, |
| 79 | indexes: &mut Vec<bool>, |
| 80 | ctx: &mut ValidationContext, |
| 81 | ) { |
| 82 | // Early return optimization: if items marks ALL items, no need to check anything else |
| 83 | if self.items_all { |
| 84 | // Draft 2020-12+: items keyword marks ALL items as evaluated |
| 85 | for idx in indexes.iter_mut() { |
| 86 | *idx = true; |
| 87 | } |
| 88 | return; |
| 89 | } |
| 90 | |
| 91 | // Handle $ref first |
| 92 | if let Some(ref_) = &self.ref_ { |
| 93 | ref_.0.mark_evaluated_indexes(instance, indexes, ctx); |
| 94 | } |
| 95 | |
| 96 | // Handle $recursiveRef (Draft 2019-09 only) |
| 97 | if let Some(recursive_ref) = &self.recursive_ref { |
| 98 | if let Some(validators) = recursive_ref.get() { |
| 99 | validators.mark_evaluated_indexes(instance, indexes, ctx); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | // Handle $dynamicRef (Draft 2020-12+) |
| 104 | if let Some(dynamic_ref) = &self.dynamic_ref { |
| 105 | dynamic_ref.mark_evaluated_indexes(instance, indexes, ctx); |
| 106 | } |
| 107 | |
| 108 | // Mark items based on items/prefixItems keywords |
| 109 | if let Some(limit) = self.items_limit { |
| 110 | // Draft 2019-09: items (as array) marks first N items |
| 111 | for idx in indexes.iter_mut().take(limit) { |
| 112 | *idx = true; |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | if let Some(limit) = self.prefix_items { |
| 117 | // prefixItems marks first N items |
| 118 | for idx in indexes.iter_mut().take(limit) { |
| 119 | *idx = true; |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // Early exit if all items are already evaluated |
| 124 | if indexes.iter().all(|&evaluated| evaluated) { |
| 125 | return; |
| 126 | } |
| 127 | |
| 128 | // Process contains and unevaluatedItems |
| 129 | if let Value::Array(items) = instance { |
| 130 | for (item, is_evaluated) in items.iter().zip(indexes.iter_mut()) { |
| 131 | if *is_evaluated { |
| 132 | continue; |
| 133 | } |
| 134 | // contains marks items that match |
| 135 | if let Some(validator) = &self.contains { |
| 136 | if validator.is_valid(item, ctx) { |
| 137 | *is_evaluated = true; |
| 138 | continue; |
| 139 | } |
| 140 | } |
| 141 | // unevaluatedItems itself can mark items |
| 142 | if let Some(validator) = &self.unevaluated { |
| 143 | if validator.is_valid(item, ctx) { |
| 144 | *is_evaluated = true; |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // Handle conditional |
| 151 | if let Some(conditional) = &self.conditional { |
| 152 | conditional.mark_evaluated_indexes(instance, indexes, ctx); |
| 153 | } |
| 154 | |
| 155 | // Handle allOf - each schema that validates successfully marks items |
| 156 | if let Some(all_of) = &self.all_of { |
| 157 | for (validator, item_validators) in all_of { |
| 158 | if validator.is_valid(instance, ctx) { |
| 159 | item_validators.mark_evaluated_indexes(instance, indexes, ctx); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | // Handle anyOf - each schema that validates successfully marks items |
| 165 | if let Some(any_of) = &self.any_of { |
| 166 | for (validator, item_validators) in any_of { |
| 167 | if validator.is_valid(instance, ctx) { |
| 168 | item_validators.mark_evaluated_indexes(instance, indexes, ctx); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | // Handle oneOf - only mark if exactly one schema validates |
| 174 | // Optimization: cache validation results to avoid double validation |
| 175 | if let Some(one_of) = &self.one_of { |
| 176 | let results: Vec<_> = one_of |
| 177 | .iter() |
| 178 | .map(|(v, _)| v.is_valid(instance, ctx)) |
| 179 | .collect(); |
| 180 | |
| 181 | if results.iter().filter(|&&valid| valid).count() == 1 { |
| 182 | for ((_, validators), &is_valid) in one_of.iter().zip(&results) { |
| 183 | if is_valid { |
| 184 | validators.mark_evaluated_indexes(instance, indexes, ctx); |
| 185 | break; |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | impl ConditionalValidators { |
| 194 | fn mark_evaluated_indexes( |
| 195 | &self, |
| 196 | instance: &Value, |
| 197 | indexes: &mut Vec<bool>, |
| 198 | ctx: &mut ValidationContext, |
| 199 | ) { |
| 200 | if self.condition.is_valid(instance, ctx) { |
| 201 | self.if_.mark_evaluated_indexes(instance, indexes, ctx); |
| 202 | if let Some(then_) = &self.then_ { |
| 203 | then_.mark_evaluated_indexes(instance, indexes, ctx); |
| 204 | } |
| 205 | } else if let Some(else_) = &self.else_ { |
| 206 | else_.mark_evaluated_indexes(instance, indexes, ctx); |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | /// Compile all items validators for a schema. |
| 212 | /// |
| 213 | /// Recursively builds the `ItemsValidators` tree by examining all keywords that |
| 214 | /// can evaluate items. Handles circular references via pending nodes cached |
| 215 | /// by location and schema pointer. |
| 216 | fn compile_items_validators<'a>( |
| 217 | ctx: &compiler::Context<'_>, |
| 218 | parent: &'a Map<String, Value>, |
| 219 | ) -> Result<ItemsValidators, ValidationError<'a>> { |
| 220 | let unevaluated = compile_unevaluated(ctx, parent)?; |
| 221 | let contains = compile_contains(ctx, parent)?; |
| 222 | let ref_ = compile_ref(ctx, parent)?; |
| 223 | let dynamic_ref = compile_dynamic_ref(ctx, parent)?; |
| 224 | let recursive_ref = compile_recursive_ref(ctx, parent)?; |
| 225 | |
| 226 | // Determine items behavior based on draft |
| 227 | let (items_limit, items_all) = compile_items(ctx, parent)?; |
| 228 | let prefix_items = compile_prefix_items(ctx, parent)?; |
| 229 | |
| 230 | let conditional = compile_conditional(ctx, parent)?; |
| 231 | let all_of = compile_all_of(ctx, parent)?; |
| 232 | let any_of = compile_any_of(ctx, parent)?; |
| 233 | let one_of = compile_one_of(ctx, parent)?; |
| 234 | |
| 235 | Ok(ItemsValidators { |
| 236 | unevaluated, |
| 237 | contains, |
| 238 | ref_, |
| 239 | dynamic_ref, |
| 240 | recursive_ref, |
| 241 | items_limit, |
| 242 | items_all, |
| 243 | prefix_items, |
| 244 | conditional, |
| 245 | all_of, |
| 246 | any_of, |
| 247 | one_of, |
| 248 | }) |
| 249 | } |
| 250 | |
| 251 | fn compile_unevaluated<'a>( |
| 252 | ctx: &compiler::Context<'_>, |
| 253 | parent: &'a Map<String, Value>, |
| 254 | ) -> Result<Option<SchemaNode>, ValidationError<'a>> { |
| 255 | if let Some(subschema) = parent.get("unevaluatedItems") { |
| 256 | let unevaluated_ctx = ctx.new_at_location("unevaluatedItems"); |
| 257 | Ok(Some( |
| 258 | compiler::compile(&unevaluated_ctx, unevaluated_ctx.as_resource_ref(subschema)) |
| 259 | .map_err(ValidationError::to_owned)?, |
| 260 | )) |
| 261 | } else { |
| 262 | Ok(None) |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | fn compile_contains<'a>( |
| 267 | ctx: &compiler::Context<'_>, |
| 268 | parent: &'a Map<String, Value>, |
| 269 | ) -> Result<Option<SchemaNode>, ValidationError<'a>> { |
| 270 | if let Some(subschema) = parent.get("contains") { |
| 271 | let contains_ctx = ctx.new_at_location("contains"); |
| 272 | Ok(Some( |
| 273 | compiler::compile(&contains_ctx, contains_ctx.as_resource_ref(subschema)) |
| 274 | .map_err(ValidationError::to_owned)?, |
| 275 | )) |
| 276 | } else { |
| 277 | Ok(None) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | fn compile_ref<'a>( |
| 282 | ctx: &compiler::Context<'_>, |
| 283 | parent: &'a Map<String, Value>, |
| 284 | ) -> Result<Option<RefValidator>, ValidationError<'a>> { |
| 285 | if let Some(Value::String(reference)) = parent.get("$ref") { |
| 286 | let resolved = ctx.lookup(reference)?; |
| 287 | if let Value::Object(subschema) = resolved.contents() { |
| 288 | let validators = |
| 289 | compile_items_validators(ctx, subschema).map_err(ValidationError::to_owned)?; |
| 290 | return Ok(Some(RefValidator(Box::new(validators)))); |
| 291 | } |
| 292 | } |
| 293 | Ok(None) |
| 294 | } |
| 295 | |
| 296 | fn compile_dynamic_ref<'a>( |
| 297 | ctx: &compiler::Context<'_>, |
| 298 | parent: &'a Map<String, Value>, |
| 299 | ) -> Result<Option<Box<ItemsValidators>>, ValidationError<'a>> { |
| 300 | if let Some(Value::String(reference)) = parent.get("$dynamicRef") { |
| 301 | let resolved = ctx.lookup(reference)?; |
| 302 | if let Value::Object(subschema) = resolved.contents() { |
| 303 | let validators = |
| 304 | compile_items_validators(ctx, subschema).map_err(ValidationError::to_owned)?; |
| 305 | return Ok(Some(Box::new(validators))); |
| 306 | } |
| 307 | } |
| 308 | Ok(None) |
| 309 | } |
| 310 | |
| 311 | fn compile_recursive_ref<'a>( |
| 312 | ctx: &compiler::Context<'_>, |
| 313 | parent: &Map<String, Value>, |
| 314 | ) -> Result<Option<PendingItemsValidators>, ValidationError<'a>> { |
| 315 | if !parent.contains_key("$recursiveRef") { |
| 316 | return Ok(None); |
| 317 | } |
| 318 | |
| 319 | // For $recursiveRef, we need to resolve the reference and check if it's already being compiled |
| 320 | let resolved = ctx |
| 321 | .lookup_recursive_reference() |
| 322 | .map_err(ValidationError::from)?; |
| 323 | |
| 324 | // Create context for the resolved reference and check its cache key |
| 325 | let (contents, resolver, draft) = resolved.into_inner(); |
| 326 | if let Value::Object(subschema) = &contents { |
| 327 | let vocabularies = ctx.registry.find_vocabularies(draft, contents); |
| 328 | let ref_ctx = |
| 329 | ctx.with_resolver_and_draft(resolver, draft, vocabularies, ctx.location().clone()); |
| 330 | |
| 331 | // Check if we're already compiling this schema (circular reference) |
| 332 | if let Some(pending) = ref_ctx.get_pending_items_validators_for_schema(subschema) { |
| 333 | return Ok(Some(pending)); |
| 334 | } |
| 335 | |
| 336 | let cache_key = ref_ctx.location_cache_key(); |
| 337 | if let Some(pending) = ref_ctx.get_pending_items_validators(&cache_key) { |
| 338 | // Circular reference detected - return the pending node |
| 339 | return Ok(Some(pending)); |
| 340 | } |
| 341 | |
| 342 | // Not circular, compile normally |
| 343 | let validators = |
| 344 | compile_items_validators(&ref_ctx, subschema).map_err(ValidationError::to_owned)?; |
| 345 | let pending = Shared::new(OnceLock::new()); |
| 346 | let _ = pending.set(validators); |
| 347 | Ok(Some(pending)) |
| 348 | } else { |
| 349 | Ok(None) |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | fn compile_items<'a>( |
| 354 | ctx: &compiler::Context<'_>, |
| 355 | parent: &'a Map<String, Value>, |
| 356 | ) -> Result<(Option<usize>, bool), ValidationError<'a>> { |
| 357 | if let Some(subschema) = parent.get("items") { |
| 358 | if ctx.draft() == Draft::Draft201909 |
| 359 | || ctx.draft() == Draft::Draft7 |
| 360 | || ctx.draft() == Draft::Draft6 |
| 361 | || ctx.draft() == Draft::Draft4 |
| 362 | { |
| 363 | // Older drafts: items can be array or object |
| 364 | let limit = if parent.contains_key("additionalItems") || subschema.is_object() { |
| 365 | usize::MAX |
| 366 | } else { |
| 367 | subschema.as_array().map_or(usize::MAX, std::vec::Vec::len) |
| 368 | }; |
| 369 | Ok((Some(limit), false)) |
| 370 | } else { |
| 371 | // Draft 2020-12+: items is always a schema that applies to all items |
| 372 | Ok((None, true)) |
| 373 | } |
| 374 | } else { |
| 375 | Ok((None, false)) |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | fn compile_prefix_items<'a>( |
| 380 | _ctx: &compiler::Context<'_>, |
| 381 | parent: &'a Map<String, Value>, |
| 382 | ) -> Result<Option<usize>, ValidationError<'a>> { |
| 383 | if let Some(Some(items)) = parent.get("prefixItems").map(Value::as_array) { |
| 384 | Ok(Some(items.len())) |
| 385 | } else { |
| 386 | Ok(None) |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | fn compile_conditional<'a>( |
| 391 | ctx: &compiler::Context<'_>, |
| 392 | parent: &'a Map<String, Value>, |
| 393 | ) -> Result<Option<Box<ConditionalValidators>>, ValidationError<'a>> { |
| 394 | if let Some(subschema) = parent.get("if") { |
| 395 | if let Value::Object(if_parent) = subschema { |
| 396 | let if_ctx = ctx.new_at_location("if"); |
| 397 | |
| 398 | let mut then_ = None; |
| 399 | if let Some(Value::Object(subschema)) = parent.get("then") { |
| 400 | let then_ctx = ctx.new_at_location("then"); |
| 401 | then_ = Some( |
| 402 | compile_items_validators(&then_ctx, subschema) |
| 403 | .map_err(ValidationError::to_owned)?, |
| 404 | ); |
| 405 | } |
| 406 | |
| 407 | let mut else_ = None; |
| 408 | if let Some(Value::Object(subschema)) = parent.get("else") { |
| 409 | let else_ctx = ctx.new_at_location("else"); |
| 410 | else_ = Some( |
| 411 | compile_items_validators(&else_ctx, subschema) |
| 412 | .map_err(ValidationError::to_owned)?, |
| 413 | ); |
| 414 | } |
| 415 | |
| 416 | return Ok(Some(Box::new(ConditionalValidators { |
| 417 | condition: compiler::compile(&if_ctx, if_ctx.as_resource_ref(subschema)) |
| 418 | .map_err(ValidationError::to_owned)?, |
| 419 | if_: compile_items_validators(&if_ctx, if_parent) |
| 420 | .map_err(ValidationError::to_owned)?, |
| 421 | then_, |
| 422 | else_, |
| 423 | }))); |
| 424 | } |
| 425 | } |
| 426 | Ok(None) |
| 427 | } |
| 428 | |
| 429 | fn compile_all_of<'a>( |
| 430 | ctx: &compiler::Context<'_>, |
| 431 | parent: &'a Map<String, Value>, |
| 432 | ) -> Result<Option<Vec<(SchemaNode, ItemsValidators)>>, ValidationError<'a>> { |
| 433 | if let Some(Some(subschemas)) = parent.get("allOf").map(Value::as_array) { |
| 434 | let all_of_ctx = ctx.new_at_location("allOf"); |
| 435 | let mut result = Vec::with_capacity(subschemas.len()); |
| 436 | |
| 437 | for (idx, subschema) in subschemas.iter().enumerate() { |
| 438 | if let Value::Object(parent) = subschema { |
| 439 | let subschema_ctx = all_of_ctx.new_at_location(idx); |
| 440 | result.push(( |
| 441 | compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema)) |
| 442 | .map_err(ValidationError::to_owned)?, |
| 443 | compile_items_validators(&subschema_ctx, parent) |
| 444 | .map_err(ValidationError::to_owned)?, |
| 445 | )); |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | Ok(Some(result)) |
| 450 | } else { |
| 451 | Ok(None) |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | fn compile_any_of<'a>( |
| 456 | ctx: &compiler::Context<'_>, |
| 457 | parent: &'a Map<String, Value>, |
| 458 | ) -> Result<Option<Vec<(SchemaNode, ItemsValidators)>>, ValidationError<'a>> { |
| 459 | if let Some(Some(subschemas)) = parent.get("anyOf").map(Value::as_array) { |
| 460 | let any_of_ctx = ctx.new_at_location("anyOf"); |
| 461 | let mut result = Vec::with_capacity(subschemas.len()); |
| 462 | |
| 463 | for (idx, subschema) in subschemas.iter().enumerate() { |
| 464 | if let Value::Object(parent) = subschema { |
| 465 | let subschema_ctx = any_of_ctx.new_at_location(idx); |
| 466 | result.push(( |
| 467 | compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema)) |
| 468 | .map_err(ValidationError::to_owned)?, |
| 469 | compile_items_validators(&subschema_ctx, parent) |
| 470 | .map_err(ValidationError::to_owned)?, |
| 471 | )); |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | Ok(Some(result)) |
| 476 | } else { |
| 477 | Ok(None) |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | fn compile_one_of<'a>( |
| 482 | ctx: &compiler::Context<'_>, |
| 483 | parent: &'a Map<String, Value>, |
| 484 | ) -> Result<Option<Vec<(SchemaNode, ItemsValidators)>>, ValidationError<'a>> { |
| 485 | if let Some(Some(subschemas)) = parent.get("oneOf").map(Value::as_array) { |
| 486 | let one_of_ctx = ctx.new_at_location("oneOf"); |
| 487 | let mut result = Vec::with_capacity(subschemas.len()); |
| 488 | |
| 489 | for (idx, subschema) in subschemas.iter().enumerate() { |
| 490 | if let Value::Object(parent) = subschema { |
| 491 | let subschema_ctx = one_of_ctx.new_at_location(idx); |
| 492 | result.push(( |
| 493 | compiler::compile(&subschema_ctx, subschema_ctx.as_resource_ref(subschema)) |
| 494 | .map_err(ValidationError::to_owned)?, |
| 495 | compile_items_validators(&subschema_ctx, parent) |
| 496 | .map_err(ValidationError::to_owned)?, |
| 497 | )); |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | Ok(Some(result)) |
| 502 | } else { |
| 503 | Ok(None) |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | /// Validator for the `unevaluatedItems` keyword. |
| 508 | pub(crate) struct UnevaluatedItemsValidator { |
| 509 | location: Location, |
| 510 | validators: ItemsValidators, |
| 511 | } |
| 512 | |
| 513 | impl UnevaluatedItemsValidator { |
| 514 | pub(crate) fn compile<'a>( |
| 515 | ctx: &'a compiler::Context, |
| 516 | parent: &'a Map<String, Value>, |
| 517 | ) -> CompilationResult<'a> { |
| 518 | let validators = |
| 519 | compile_items_validators(ctx, parent).map_err(ValidationError::to_owned)?; |
| 520 | |
| 521 | Ok(Box::new(UnevaluatedItemsValidator { |
| 522 | location: ctx.location().join("unevaluatedItems"), |
| 523 | validators, |
| 524 | })) |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | impl Validate for UnevaluatedItemsValidator { |
| 529 | fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool { |
| 530 | if let Value::Array(items) = instance { |
| 531 | let mut indexes = vec![false; items.len()]; |
| 532 | self.validators |
| 533 | .mark_evaluated_indexes(instance, &mut indexes, ctx); |
| 534 | |
| 535 | for (item, is_evaluated) in items.iter().zip(indexes) { |
| 536 | if !is_evaluated { |
| 537 | if let Some(validator) = &self.validators.unevaluated { |
| 538 | if !validator.is_valid(item, ctx) { |
| 539 | return false; |
| 540 | } |
| 541 | } else { |
| 542 | // unevaluatedItems: false and item not evaluated |
| 543 | return false; |
| 544 | } |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | true |
| 549 | } |
| 550 | |
| 551 | fn validate<'i>( |
| 552 | &self, |
| 553 | instance: &'i Value, |
| 554 | location: &LazyLocation, |
| 555 | ctx: &mut ValidationContext, |
| 556 | ) -> Result<(), ValidationError<'i>> { |
| 557 | if let Value::Array(items) = instance { |
| 558 | let mut indexes = vec![false; items.len()]; |
| 559 | self.validators |
| 560 | .mark_evaluated_indexes(instance, &mut indexes, ctx); |
| 561 | let mut unevaluated = vec![]; |
| 562 | |
| 563 | for (item, is_evaluated) in items.iter().zip(indexes) { |
| 564 | if !is_evaluated { |
| 565 | let is_valid = if let Some(validator) = &self.validators.unevaluated { |
| 566 | validator.is_valid(item, ctx) |
| 567 | } else { |
| 568 | false |
| 569 | }; |
| 570 | |
| 571 | if !is_valid { |
| 572 | unevaluated.push(item.to_string()); |
| 573 | } |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | if !unevaluated.is_empty() { |
| 578 | return Err(ValidationError::unevaluated_items( |
| 579 | self.location.clone(), |
| 580 | location.into(), |
| 581 | instance, |
| 582 | unevaluated, |
| 583 | )); |
| 584 | } |
| 585 | } |
| 586 | Ok(()) |
| 587 | } |
| 588 | |
| 589 | fn evaluate( |
| 590 | &self, |
| 591 | instance: &Value, |
| 592 | location: &LazyLocation, |
| 593 | ctx: &mut ValidationContext, |
| 594 | ) -> EvaluationResult { |
| 595 | if let Value::Array(items) = instance { |
| 596 | let mut indexes = vec![false; items.len()]; |
| 597 | self.validators |
| 598 | .mark_evaluated_indexes(instance, &mut indexes, ctx); |
| 599 | let mut children = Vec::new(); |
| 600 | let mut unevaluated = Vec::new(); |
| 601 | let mut invalid = false; |
| 602 | |
| 603 | for (idx, (item, is_evaluated)) in items.iter().zip(indexes.iter()).enumerate() { |
| 604 | if *is_evaluated { |
| 605 | continue; |
| 606 | } |
| 607 | if let Some(validator) = &self.validators.unevaluated { |
| 608 | let child = validator.evaluate_instance(item, &location.push(idx), ctx); |
| 609 | if !child.valid { |
| 610 | invalid = true; |
| 611 | unevaluated.push(item.to_string()); |
| 612 | } |
| 613 | children.push(child); |
| 614 | } else { |
| 615 | invalid = true; |
| 616 | unevaluated.push(item.to_string()); |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | let mut errors = Vec::new(); |
| 621 | if !unevaluated.is_empty() { |
| 622 | errors.push(ErrorDescription::from_validation_error( |
| 623 | &ValidationError::unevaluated_items( |
| 624 | self.location.clone(), |
| 625 | location.into(), |
| 626 | instance, |
| 627 | unevaluated, |
| 628 | ), |
| 629 | )); |
| 630 | } |
| 631 | |
| 632 | if invalid { |
| 633 | EvaluationResult::Invalid { |
| 634 | errors, |
| 635 | children, |
| 636 | annotations: None, |
| 637 | } |
| 638 | } else { |
| 639 | EvaluationResult::Valid { |
| 640 | annotations: None, |
| 641 | children, |
| 642 | } |
| 643 | } |
| 644 | } else { |
| 645 | EvaluationResult::valid_empty() |
| 646 | } |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | pub(crate) fn compile<'a>( |
| 651 | ctx: &'a compiler::Context, |
| 652 | parent: &'a Map<String, Value>, |
| 653 | schema: &'a Value, |
| 654 | ) -> Option<CompilationResult<'a>> { |
| 655 | match schema.as_bool() { |
| 656 | Some(true) => None, |
| 657 | _ => Some(UnevaluatedItemsValidator::compile(ctx, parent)), |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | #[cfg(test)] |
| 662 | mod tests { |
| 663 | use serde_json::json; |
| 664 | |
| 665 | #[test] |
| 666 | fn test_unevaluated_items_with_recursion() { |
| 667 | let schema = json!({ |
| 668 | "$schema": "https://json-schema.org/draft/2020-12/schema", |
| 669 | "allOf": [ |
| 670 | { |
| 671 | "$ref": "#/$defs/array_1" |
| 672 | } |
| 673 | ], |
| 674 | "unevaluatedItems": false, |
| 675 | "$defs": { |
| 676 | "array_1": { |
| 677 | "type": "array", |
| 678 | "prefixItems": [ |
| 679 | { |
| 680 | "type": "string" |
| 681 | }, |
| 682 | { |
| 683 | "allOf": [ |
| 684 | { |
| 685 | "$ref": "#/$defs/array_2" |
| 686 | } |
| 687 | ], |
| 688 | "type": "array", |
| 689 | "unevaluatedItems": false |
| 690 | } |
| 691 | ] |
| 692 | }, |
| 693 | "array_2": { |
| 694 | "type": "array", |
| 695 | "prefixItems": [ |
| 696 | { |
| 697 | "type": "number" |
| 698 | }, |
| 699 | { |
| 700 | "allOf": [ |
| 701 | { |
| 702 | "$ref": "#/$defs/array_1" |
| 703 | } |
| 704 | ], |
| 705 | "type": "array", |
| 706 | "unevaluatedItems": false |
| 707 | } |
| 708 | ] |
| 709 | } |
| 710 | } |
| 711 | }); |
| 712 | |
| 713 | let validator = crate::validator_for(&schema).expect("Schema should compile"); |
| 714 | |
| 715 | // This instance should fail validation because the nested array has an unevaluated item |
| 716 | let instance = json!([ |
| 717 | "string", |
| 718 | [ |
| 719 | 42, |
| 720 | [ |
| 721 | "string", |
| 722 | [ |
| 723 | 42, |
| 724 | "unexpected" // This item should cause validation to fail |
| 725 | ] |
| 726 | ] |
| 727 | ] |
| 728 | ]); |
| 729 | |
| 730 | assert!(!validator.is_valid(&instance)); |
| 731 | assert!(validator.validate(&instance).is_err()); |
| 732 | |
| 733 | // This instance should pass validation as all items are evaluated |
| 734 | let valid_instance = json!(["string", [42, ["string", [42]]]]); |
| 735 | |
| 736 | assert!(validator.is_valid(&valid_instance)); |
| 737 | assert!(validator.validate(&valid_instance).is_ok()); |
| 738 | } |
| 739 | } |