| 1 | use crate::{ |
| 2 | compiler::Context, |
| 3 | error::ErrorIterator, |
| 4 | evaluation::{format_schema_location, Annotations, EvaluationNode}, |
| 5 | keywords::{BoxedValidator, Keyword}, |
| 6 | paths::{LazyLocation, Location}, |
| 7 | thread::{Shared, SharedWeak}, |
| 8 | validator::{EvaluationResult, Validate, ValidationContext}, |
| 9 | ValidationError, |
| 10 | }; |
| 11 | use referencing::Uri; |
| 12 | use serde_json::Value; |
| 13 | use std::{ |
| 14 | cell::OnceCell, |
| 15 | fmt, |
| 16 | sync::{Arc, OnceLock}, |
| 17 | }; |
| 18 | |
| 19 | /// A node in the schema tree, returned by `compiler::compile` |
| 20 | #[derive(Clone, Debug)] |
| 21 | pub(crate) struct SchemaNode { |
| 22 | validators: Shared<NodeValidators>, |
| 23 | location: Location, |
| 24 | absolute_path: Option<Arc<Uri<String>>>, |
| 25 | } |
| 26 | |
| 27 | // Separate type used only during compilation for handling recursive references |
| 28 | #[derive(Clone, Debug)] |
| 29 | pub(crate) struct PendingSchemaNode { |
| 30 | cell: Shared<OnceLock<PendingTarget>>, |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug)] |
| 34 | struct PendingTarget { |
| 35 | validators: SharedWeak<NodeValidators>, |
| 36 | location: Location, |
| 37 | absolute_path: Option<Arc<Uri<String>>>, |
| 38 | } |
| 39 | |
| 40 | enum NodeValidators { |
| 41 | /// The result of compiling a boolean valued schema, e.g |
| 42 | /// |
| 43 | /// ```json |
| 44 | /// { |
| 45 | /// "additionalProperties": false |
| 46 | /// } |
| 47 | /// ``` |
| 48 | /// |
| 49 | /// Here the result of `compiler::compile` called with the `false` value will return a |
| 50 | /// `SchemaNode` with a single `BooleanValidator` as it's `validators`. |
| 51 | Boolean { validator: Option<BoxedValidator> }, |
| 52 | /// The result of compiling a schema which is composed of keywords (almost all schemas) |
| 53 | Keyword(KeywordValidators), |
| 54 | /// The result of compiling a schema which is "array valued", e.g the "dependencies" keyword of |
| 55 | /// draft 7 which can take values which are an array of other property names |
| 56 | Array { |
| 57 | validators: Vec<ArrayValidatorEntry>, |
| 58 | }, |
| 59 | } |
| 60 | |
| 61 | impl fmt::Debug for NodeValidators { |
| 62 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 63 | match self { |
| 64 | Self::Boolean { .. } => f.debug_struct("Boolean").finish(), |
| 65 | Self::Keyword(_) => f.debug_tuple("Keyword").finish(), |
| 66 | Self::Array { .. } => f.debug_struct("Array").finish(), |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | struct KeywordValidators { |
| 72 | /// The keywords on this node which were not recognized by any vocabularies. These are |
| 73 | /// stored so we can later produce them as annotations |
| 74 | unmatched_keywords: Option<Arc<Value>>, |
| 75 | // We should probably use AHashMap here but it breaks a bunch of tests which assume |
| 76 | // validators are in a particular order |
| 77 | validators: Vec<KeywordValidatorEntry>, |
| 78 | } |
| 79 | |
| 80 | struct KeywordValidatorEntry { |
| 81 | validator: BoxedValidator, |
| 82 | location: Location, |
| 83 | absolute_location: Option<Arc<Uri<String>>>, |
| 84 | } |
| 85 | |
| 86 | struct ArrayValidatorEntry { |
| 87 | validator: BoxedValidator, |
| 88 | location: Location, |
| 89 | absolute_location: Option<Arc<Uri<String>>>, |
| 90 | } |
| 91 | |
| 92 | impl PendingSchemaNode { |
| 93 | pub(crate) fn new() -> Self { |
| 94 | PendingSchemaNode { |
| 95 | cell: Shared::new(OnceLock::new()), |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | pub(crate) fn initialize(&self, node: &SchemaNode) { |
| 100 | let target = PendingTarget { |
| 101 | validators: Shared::downgrade(&node.validators), |
| 102 | location: node.location.clone(), |
| 103 | absolute_path: node.absolute_path.clone(), |
| 104 | }; |
| 105 | self.cell |
| 106 | .set(target) |
| 107 | .expect("pending node initialized twice"); |
| 108 | } |
| 109 | |
| 110 | pub(crate) fn get(&self) -> Option<SchemaNode> { |
| 111 | self.cell.get().map(PendingTarget::materialize) |
| 112 | } |
| 113 | |
| 114 | fn with_node<F, R>(&self, f: F) -> R |
| 115 | where |
| 116 | F: FnOnce(SchemaNode) -> R, |
| 117 | { |
| 118 | let node = self |
| 119 | .cell |
| 120 | .get() |
| 121 | .expect("pending node accessed before initialization") |
| 122 | .materialize(); |
| 123 | f(node) |
| 124 | } |
| 125 | |
| 126 | /// Get a unique identifier for this pending node. |
| 127 | /// Uses the address of the inner cell as a stable identifier. |
| 128 | #[inline] |
| 129 | fn node_id(&self) -> usize { |
| 130 | Shared::as_ptr(&self.cell) as usize |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | impl PendingTarget { |
| 135 | fn materialize(&self) -> SchemaNode { |
| 136 | let validators = self |
| 137 | .validators |
| 138 | .upgrade() |
| 139 | .expect("pending schema target dropped"); |
| 140 | SchemaNode { |
| 141 | validators, |
| 142 | location: self.location.clone(), |
| 143 | absolute_path: self.absolute_path.clone(), |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | impl Validate for PendingSchemaNode { |
| 149 | fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool { |
| 150 | if ctx.enter(self.node_id(), instance) { |
| 151 | // Cycle detected - this (node, instance) pair is already being validated. |
| 152 | // A pure reference cycle is equivalent to `true` schema. |
| 153 | return true; |
| 154 | } |
| 155 | let result = self.with_node(|node| node.is_valid(instance, ctx)); |
| 156 | ctx.exit(self.node_id(), instance); |
| 157 | result |
| 158 | } |
| 159 | |
| 160 | fn validate<'i>( |
| 161 | &self, |
| 162 | instance: &'i Value, |
| 163 | location: &LazyLocation, |
| 164 | ctx: &mut ValidationContext, |
| 165 | ) -> Result<(), ValidationError<'i>> { |
| 166 | if ctx.enter(self.node_id(), instance) { |
| 167 | return Ok(()); |
| 168 | } |
| 169 | let result = self.with_node(|node| node.validate(instance, location, ctx)); |
| 170 | ctx.exit(self.node_id(), instance); |
| 171 | result |
| 172 | } |
| 173 | |
| 174 | fn iter_errors<'i>( |
| 175 | &self, |
| 176 | instance: &'i Value, |
| 177 | location: &LazyLocation, |
| 178 | ctx: &mut ValidationContext, |
| 179 | ) -> ErrorIterator<'i> { |
| 180 | if ctx.enter(self.node_id(), instance) { |
| 181 | return crate::error::no_error(); |
| 182 | } |
| 183 | let result = self.with_node(|node| node.iter_errors(instance, location, ctx)); |
| 184 | ctx.exit(self.node_id(), instance); |
| 185 | result |
| 186 | } |
| 187 | |
| 188 | fn evaluate( |
| 189 | &self, |
| 190 | instance: &Value, |
| 191 | location: &LazyLocation, |
| 192 | ctx: &mut ValidationContext, |
| 193 | ) -> EvaluationResult { |
| 194 | if ctx.enter(self.node_id(), instance) { |
| 195 | return EvaluationResult::valid_empty(); |
| 196 | } |
| 197 | let result = self.with_node(|node| node.evaluate(instance, location, ctx)); |
| 198 | ctx.exit(self.node_id(), instance); |
| 199 | result |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | impl SchemaNode { |
| 204 | pub(crate) fn from_boolean(ctx: &Context<'_>, validator: Option<BoxedValidator>) -> SchemaNode { |
| 205 | SchemaNode { |
| 206 | location: ctx.location().clone(), |
| 207 | absolute_path: ctx.base_uri(), |
| 208 | validators: Shared::new(NodeValidators::Boolean { validator }), |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | pub(crate) fn from_keywords( |
| 213 | ctx: &Context<'_>, |
| 214 | validators: Vec<(Keyword, BoxedValidator)>, |
| 215 | unmatched_keywords: Option<Arc<Value>>, |
| 216 | ) -> SchemaNode { |
| 217 | let absolute_path = ctx.base_uri(); |
| 218 | let validators = validators |
| 219 | .into_iter() |
| 220 | .map(|(keyword, validator)| { |
| 221 | let location = ctx.location().join(&keyword); |
| 222 | let absolute_location = ctx.absolute_location(&location); |
| 223 | KeywordValidatorEntry { |
| 224 | validator, |
| 225 | location, |
| 226 | absolute_location, |
| 227 | } |
| 228 | }) |
| 229 | .collect(); |
| 230 | SchemaNode { |
| 231 | location: ctx.location().clone(), |
| 232 | absolute_path, |
| 233 | validators: Shared::new(NodeValidators::Keyword(KeywordValidators { |
| 234 | unmatched_keywords, |
| 235 | validators, |
| 236 | })), |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | pub(crate) fn from_array(ctx: &Context<'_>, validators: Vec<BoxedValidator>) -> SchemaNode { |
| 241 | let absolute_path = ctx.base_uri(); |
| 242 | let validators = validators |
| 243 | .into_iter() |
| 244 | .enumerate() |
| 245 | .map(|(index, validator)| { |
| 246 | let location = ctx.location().join(index); |
| 247 | let absolute_location = ctx.absolute_location(&location); |
| 248 | ArrayValidatorEntry { |
| 249 | validator, |
| 250 | location, |
| 251 | absolute_location, |
| 252 | } |
| 253 | }) |
| 254 | .collect(); |
| 255 | SchemaNode { |
| 256 | location: ctx.location().clone(), |
| 257 | absolute_path, |
| 258 | validators: Shared::new(NodeValidators::Array { validators }), |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | pub(crate) fn clone_with_location( |
| 263 | &self, |
| 264 | location: Location, |
| 265 | absolute_path: Option<Arc<Uri<String>>>, |
| 266 | ) -> SchemaNode { |
| 267 | SchemaNode { |
| 268 | validators: self.validators.clone(), |
| 269 | location, |
| 270 | absolute_path, |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | pub(crate) fn validators(&self) -> impl ExactSizeIterator<Item = &BoxedValidator> { |
| 275 | match self.validators.as_ref() { |
| 276 | NodeValidators::Boolean { validator } => { |
| 277 | if let Some(v) = validator { |
| 278 | NodeValidatorsIter::BooleanValidators(std::iter::once(v)) |
| 279 | } else { |
| 280 | NodeValidatorsIter::NoValidator |
| 281 | } |
| 282 | } |
| 283 | NodeValidators::Keyword(kvals) => { |
| 284 | NodeValidatorsIter::KeywordValidators(kvals.validators.iter()) |
| 285 | } |
| 286 | NodeValidators::Array { validators } => { |
| 287 | NodeValidatorsIter::ArrayValidators(validators.iter()) |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | pub(crate) fn evaluate_instance( |
| 293 | &self, |
| 294 | instance: &Value, |
| 295 | location: &LazyLocation, |
| 296 | ctx: &mut ValidationContext, |
| 297 | ) -> EvaluationNode { |
| 298 | let instance_location: Location = location.into(); |
| 299 | let schema_location = format_schema_location(&self.location, self.absolute_path.as_ref()); |
| 300 | match self.evaluate(instance, location, ctx) { |
| 301 | EvaluationResult::Valid { |
| 302 | annotations, |
| 303 | children, |
| 304 | } => EvaluationNode::valid( |
| 305 | self.location.clone(), |
| 306 | self.absolute_path.clone(), |
| 307 | schema_location, |
| 308 | instance_location, |
| 309 | annotations, |
| 310 | children, |
| 311 | ), |
| 312 | EvaluationResult::Invalid { |
| 313 | errors, |
| 314 | children, |
| 315 | annotations, |
| 316 | } => EvaluationNode::invalid( |
| 317 | self.location.clone(), |
| 318 | self.absolute_path.clone(), |
| 319 | schema_location, |
| 320 | instance_location, |
| 321 | annotations, |
| 322 | errors, |
| 323 | children, |
| 324 | ), |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | /// Helper function to evaluate subschemas which already know their locations. |
| 329 | fn evaluate_subschemas<'a, I>( |
| 330 | instance: &Value, |
| 331 | location: &LazyLocation, |
| 332 | subschemas: I, |
| 333 | annotations: Option<Annotations>, |
| 334 | ctx: &mut ValidationContext, |
| 335 | ) -> EvaluationResult |
| 336 | where |
| 337 | I: Iterator< |
| 338 | Item = ( |
| 339 | &'a Location, |
| 340 | Option<&'a Arc<Uri<String>>>, |
| 341 | &'a BoxedValidator, |
| 342 | ), |
| 343 | > + 'a, |
| 344 | { |
| 345 | let (lower_bound, _) = subschemas.size_hint(); |
| 346 | let mut children: Vec<EvaluationNode> = Vec::with_capacity(lower_bound); |
| 347 | let mut invalid = false; |
| 348 | let instance_location: OnceCell<Location> = OnceCell::new(); |
| 349 | |
| 350 | for (child_location, absolute_location, validator) in subschemas { |
| 351 | let child_result = validator.evaluate(instance, location, ctx); |
| 352 | |
| 353 | let schema_location = child_location.clone(); |
| 354 | let absolute_location = absolute_location.cloned(); |
| 355 | let instance_loc = instance_location.get_or_init(|| location.into()).clone(); |
| 356 | let formatted_schema_location = |
| 357 | format_schema_location(&schema_location, absolute_location.as_ref()); |
| 358 | |
| 359 | let child_node = match child_result { |
| 360 | EvaluationResult::Valid { |
| 361 | annotations, |
| 362 | children, |
| 363 | } => EvaluationNode::valid( |
| 364 | schema_location, |
| 365 | absolute_location, |
| 366 | formatted_schema_location, |
| 367 | instance_loc, |
| 368 | annotations, |
| 369 | children, |
| 370 | ), |
| 371 | EvaluationResult::Invalid { |
| 372 | errors, |
| 373 | children, |
| 374 | annotations, |
| 375 | } => { |
| 376 | invalid = true; |
| 377 | EvaluationNode::invalid( |
| 378 | schema_location, |
| 379 | absolute_location, |
| 380 | formatted_schema_location, |
| 381 | instance_loc, |
| 382 | annotations, |
| 383 | errors, |
| 384 | children, |
| 385 | ) |
| 386 | } |
| 387 | }; |
| 388 | children.push(child_node); |
| 389 | } |
| 390 | if invalid { |
| 391 | EvaluationResult::Invalid { |
| 392 | errors: Vec::new(), |
| 393 | children, |
| 394 | annotations, |
| 395 | } |
| 396 | } else { |
| 397 | EvaluationResult::Valid { |
| 398 | annotations, |
| 399 | children, |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | pub(crate) fn location(&self) -> &Location { |
| 405 | &self.location |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | impl Validate for SchemaNode { |
| 410 | fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool { |
| 411 | match self.validators.as_ref() { |
| 412 | // If we only have one validator then calling it's `is_valid` directly does |
| 413 | // actually save the 20 or so instructions required to call the `slice::Iter::all` |
| 414 | // implementation. Validators at the leaf of a tree are all single node validators so |
| 415 | // this optimization can have significant cumulative benefits |
| 416 | NodeValidators::Keyword(kvs) if kvs.validators.len() == 1 => { |
| 417 | kvs.validators[0].validator.is_valid(instance, ctx) |
| 418 | } |
| 419 | NodeValidators::Keyword(kvs) => { |
| 420 | for entry in &kvs.validators { |
| 421 | if !entry.validator.is_valid(instance, ctx) { |
| 422 | return false; |
| 423 | } |
| 424 | } |
| 425 | true |
| 426 | } |
| 427 | NodeValidators::Array { validators } => validators |
| 428 | .iter() |
| 429 | .all(|entry| entry.validator.is_valid(instance, ctx)), |
| 430 | NodeValidators::Boolean { validator: Some(_) } => false, |
| 431 | NodeValidators::Boolean { validator: None } => true, |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | fn validate<'i>( |
| 436 | &self, |
| 437 | instance: &'i Value, |
| 438 | location: &LazyLocation, |
| 439 | ctx: &mut ValidationContext, |
| 440 | ) -> Result<(), ValidationError<'i>> { |
| 441 | match self.validators.as_ref() { |
| 442 | NodeValidators::Keyword(kvs) => { |
| 443 | for entry in &kvs.validators { |
| 444 | entry.validator.validate(instance, location, ctx)?; |
| 445 | } |
| 446 | } |
| 447 | NodeValidators::Array { validators } => { |
| 448 | for entry in validators { |
| 449 | entry.validator.validate(instance, location, ctx)?; |
| 450 | } |
| 451 | } |
| 452 | NodeValidators::Boolean { validator: Some(_) } => { |
| 453 | return Err(ValidationError::false_schema( |
| 454 | self.location.clone(), |
| 455 | location.into(), |
| 456 | instance, |
| 457 | )); |
| 458 | } |
| 459 | NodeValidators::Boolean { validator: None } => return Ok(()), |
| 460 | } |
| 461 | Ok(()) |
| 462 | } |
| 463 | |
| 464 | fn iter_errors<'i>( |
| 465 | &self, |
| 466 | instance: &'i Value, |
| 467 | location: &LazyLocation, |
| 468 | ctx: &mut ValidationContext, |
| 469 | ) -> ErrorIterator<'i> { |
| 470 | match self.validators.as_ref() { |
| 471 | NodeValidators::Keyword(kvs) if kvs.validators.len() == 1 => kvs.validators[0] |
| 472 | .validator |
| 473 | .iter_errors(instance, location, ctx), |
| 474 | NodeValidators::Keyword(kvs) => ErrorIterator::from_iterator( |
| 475 | kvs.validators |
| 476 | .iter() |
| 477 | .flat_map(|entry| entry.validator.iter_errors(instance, location, ctx)) |
| 478 | .collect::<Vec<_>>() |
| 479 | .into_iter(), |
| 480 | ), |
| 481 | NodeValidators::Boolean { |
| 482 | validator: Some(v), .. |
| 483 | } => v.iter_errors(instance, location, ctx), |
| 484 | NodeValidators::Boolean { |
| 485 | validator: None, .. |
| 486 | } => ErrorIterator::from_iterator(std::iter::empty()), |
| 487 | NodeValidators::Array { validators } => ErrorIterator::from_iterator( |
| 488 | validators |
| 489 | .iter() |
| 490 | .flat_map(move |entry| entry.validator.iter_errors(instance, location, ctx)) |
| 491 | .collect::<Vec<_>>() |
| 492 | .into_iter(), |
| 493 | ), |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | fn evaluate( |
| 498 | &self, |
| 499 | instance: &Value, |
| 500 | location: &LazyLocation, |
| 501 | ctx: &mut ValidationContext, |
| 502 | ) -> EvaluationResult { |
| 503 | match self.validators.as_ref() { |
| 504 | NodeValidators::Array { ref validators } => Self::evaluate_subschemas( |
| 505 | instance, |
| 506 | location, |
| 507 | validators.iter().map(|entry| { |
| 508 | ( |
| 509 | &entry.location, |
| 510 | entry.absolute_location.as_ref(), |
| 511 | &entry.validator, |
| 512 | ) |
| 513 | }), |
| 514 | None, |
| 515 | ctx, |
| 516 | ), |
| 517 | NodeValidators::Boolean { ref validator } => { |
| 518 | if let Some(validator) = validator { |
| 519 | validator.evaluate(instance, location, ctx) |
| 520 | } else { |
| 521 | EvaluationResult::Valid { |
| 522 | annotations: None, |
| 523 | children: Vec::new(), |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | NodeValidators::Keyword(ref kvals) => { |
| 528 | let KeywordValidators { |
| 529 | ref unmatched_keywords, |
| 530 | ref validators, |
| 531 | } = *kvals; |
| 532 | let annotations: Option<Annotations> = unmatched_keywords |
| 533 | .as_ref() |
| 534 | .map(|v| Annotations::from_arc(Arc::clone(v))); |
| 535 | Self::evaluate_subschemas( |
| 536 | instance, |
| 537 | location, |
| 538 | validators.iter().map(|entry| { |
| 539 | ( |
| 540 | &entry.location, |
| 541 | entry.absolute_location.as_ref(), |
| 542 | &entry.validator, |
| 543 | ) |
| 544 | }), |
| 545 | annotations, |
| 546 | ctx, |
| 547 | ) |
| 548 | } |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | enum NodeValidatorsIter<'a> { |
| 554 | NoValidator, |
| 555 | BooleanValidators(std::iter::Once<&'a BoxedValidator>), |
| 556 | KeywordValidators(std::slice::Iter<'a, KeywordValidatorEntry>), |
| 557 | ArrayValidators(std::slice::Iter<'a, ArrayValidatorEntry>), |
| 558 | } |
| 559 | |
| 560 | impl<'a> Iterator for NodeValidatorsIter<'a> { |
| 561 | type Item = &'a BoxedValidator; |
| 562 | |
| 563 | fn next(&mut self) -> Option<Self::Item> { |
| 564 | match self { |
| 565 | Self::NoValidator => None, |
| 566 | Self::BooleanValidators(i) => i.next(), |
| 567 | Self::KeywordValidators(v) => v.next().map(|entry| &entry.validator), |
| 568 | Self::ArrayValidators(v) => v.next().map(|entry| &entry.validator), |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | fn all<F>(&mut self, mut f: F) -> bool |
| 573 | where |
| 574 | Self: Sized, |
| 575 | F: FnMut(Self::Item) -> bool, |
| 576 | { |
| 577 | match self { |
| 578 | Self::NoValidator => true, |
| 579 | Self::BooleanValidators(i) => i.all(f), |
| 580 | Self::KeywordValidators(v) => v.all(|entry| f(&entry.validator)), |
| 581 | Self::ArrayValidators(v) => v.all(|entry| f(&entry.validator)), |
| 582 | } |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | impl ExactSizeIterator for NodeValidatorsIter<'_> { |
| 587 | fn len(&self) -> usize { |
| 588 | match self { |
| 589 | Self::NoValidator => 0, |
| 590 | Self::BooleanValidators(..) => 1, |
| 591 | Self::KeywordValidators(v) => v.len(), |
| 592 | Self::ArrayValidators(v) => v.len(), |
| 593 | } |
| 594 | } |
| 595 | } |