| 1 | use std::sync::Arc; |
| 2 | |
| 3 | use crate::{ |
| 4 | compiler, |
| 5 | error::{no_error, ErrorIterator, ValidationError}, |
| 6 | evaluation::Annotations, |
| 7 | keywords::CompilationResult, |
| 8 | node::SchemaNode, |
| 9 | options::PatternEngineOptions, |
| 10 | paths::{LazyLocation, Location}, |
| 11 | regex::RegexEngine, |
| 12 | types::JsonType, |
| 13 | validator::{EvaluationResult, Validate, ValidationContext}, |
| 14 | }; |
| 15 | use serde_json::{Map, Value}; |
| 16 | |
| 17 | pub(crate) struct PatternPropertiesValidator<R> { |
| 18 | patterns: Vec<(Arc<R>, SchemaNode)>, |
| 19 | } |
| 20 | |
| 21 | impl<R: RegexEngine> Validate for PatternPropertiesValidator<R> { |
| 22 | fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool { |
| 23 | if let Value::Object(item) = instance { |
| 24 | for (re, node) in &self.patterns { |
| 25 | for (key, value) in item { |
| 26 | if re.is_match(key).unwrap_or(false) && !node.is_valid(value, ctx) { |
| 27 | return false; |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | true |
| 32 | } else { |
| 33 | true |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | fn validate<'i>( |
| 38 | &self, |
| 39 | instance: &'i Value, |
| 40 | location: &LazyLocation, |
| 41 | ctx: &mut ValidationContext, |
| 42 | ) -> Result<(), ValidationError<'i>> { |
| 43 | if let Value::Object(item) = instance { |
| 44 | for (key, value) in item { |
| 45 | for (re, node) in &self.patterns { |
| 46 | if re.is_match(key).unwrap_or(false) { |
| 47 | node.validate(value, &location.push(key), ctx)?; |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | Ok(()) |
| 53 | } |
| 54 | |
| 55 | fn iter_errors<'i>( |
| 56 | &self, |
| 57 | instance: &'i Value, |
| 58 | location: &LazyLocation, |
| 59 | ctx: &mut ValidationContext, |
| 60 | ) -> ErrorIterator<'i> { |
| 61 | if let Value::Object(item) = instance { |
| 62 | let mut errors = Vec::new(); |
| 63 | for (re, node) in &self.patterns { |
| 64 | for (key, value) in item { |
| 65 | if re.is_match(key).unwrap_or(false) { |
| 66 | errors.extend(node.iter_errors(value, &location.push(key.as_str()), ctx)); |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | ErrorIterator::from_iterator(errors.into_iter()) |
| 71 | } else { |
| 72 | no_error() |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | fn evaluate( |
| 77 | &self, |
| 78 | instance: &Value, |
| 79 | location: &LazyLocation, |
| 80 | ctx: &mut ValidationContext, |
| 81 | ) -> EvaluationResult { |
| 82 | if let Value::Object(item) = instance { |
| 83 | let mut matched_propnames = Vec::with_capacity(item.len()); |
| 84 | let mut children = Vec::new(); |
| 85 | for (pattern, node) in &self.patterns { |
| 86 | for (key, value) in item { |
| 87 | if pattern.is_match(key).unwrap_or(false) { |
| 88 | matched_propnames.push(key.clone()); |
| 89 | children.push(node.evaluate_instance( |
| 90 | value, |
| 91 | &location.push(key.as_str()), |
| 92 | ctx, |
| 93 | )); |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | let mut result = EvaluationResult::from_children(children); |
| 98 | result.annotate(Annotations::new(Value::from(matched_propnames))); |
| 99 | result |
| 100 | } else { |
| 101 | EvaluationResult::valid_empty() |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | pub(crate) struct SingleValuePatternPropertiesValidator<R> { |
| 107 | regex: Arc<R>, |
| 108 | node: SchemaNode, |
| 109 | } |
| 110 | |
| 111 | impl<R: RegexEngine> Validate for SingleValuePatternPropertiesValidator<R> { |
| 112 | fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool { |
| 113 | if let Value::Object(item) = instance { |
| 114 | for (key, value) in item { |
| 115 | if self.regex.is_match(key).unwrap_or(false) && !self.node.is_valid(value, ctx) { |
| 116 | return false; |
| 117 | } |
| 118 | } |
| 119 | true |
| 120 | } else { |
| 121 | true |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | fn validate<'i>( |
| 126 | &self, |
| 127 | instance: &'i Value, |
| 128 | location: &LazyLocation, |
| 129 | ctx: &mut ValidationContext, |
| 130 | ) -> Result<(), ValidationError<'i>> { |
| 131 | if let Value::Object(item) = instance { |
| 132 | for (key, value) in item { |
| 133 | if self.regex.is_match(key).unwrap_or(false) { |
| 134 | self.node.validate(value, &location.push(key), ctx)?; |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | Ok(()) |
| 139 | } |
| 140 | |
| 141 | fn iter_errors<'i>( |
| 142 | &self, |
| 143 | instance: &'i Value, |
| 144 | location: &LazyLocation, |
| 145 | ctx: &mut ValidationContext, |
| 146 | ) -> ErrorIterator<'i> { |
| 147 | if let Value::Object(item) = instance { |
| 148 | let mut errors = Vec::new(); |
| 149 | for (key, value) in item { |
| 150 | if self.regex.is_match(key).unwrap_or(false) { |
| 151 | errors.extend( |
| 152 | self.node |
| 153 | .iter_errors(value, &location.push(key.as_str()), ctx), |
| 154 | ); |
| 155 | } |
| 156 | } |
| 157 | ErrorIterator::from_iterator(errors.into_iter()) |
| 158 | } else { |
| 159 | no_error() |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | fn evaluate( |
| 164 | &self, |
| 165 | instance: &Value, |
| 166 | location: &LazyLocation, |
| 167 | ctx: &mut ValidationContext, |
| 168 | ) -> EvaluationResult { |
| 169 | if let Value::Object(item) = instance { |
| 170 | let mut matched_propnames = Vec::with_capacity(item.len()); |
| 171 | let mut children = Vec::new(); |
| 172 | for (key, value) in item { |
| 173 | if self.regex.is_match(key).unwrap_or(false) { |
| 174 | matched_propnames.push(key.clone()); |
| 175 | children.push(self.node.evaluate_instance( |
| 176 | value, |
| 177 | &location.push(key.as_str()), |
| 178 | ctx, |
| 179 | )); |
| 180 | } |
| 181 | } |
| 182 | let mut result = EvaluationResult::from_children(children); |
| 183 | result.annotate(Annotations::new(Value::from(matched_propnames))); |
| 184 | result |
| 185 | } else { |
| 186 | EvaluationResult::valid_empty() |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | #[inline] |
| 192 | pub(crate) fn compile<'a>( |
| 193 | ctx: &compiler::Context, |
| 194 | parent: &'a Map<String, Value>, |
| 195 | schema: &'a Value, |
| 196 | ) -> Option<CompilationResult<'a>> { |
| 197 | if matches!( |
| 198 | parent.get("additionalProperties"), |
| 199 | Some(Value::Bool(false) | Value::Object(_)) |
| 200 | ) { |
| 201 | // This type of `additionalProperties` validator handles `patternProperties` logic |
| 202 | return None; |
| 203 | } |
| 204 | |
| 205 | let Value::Object(map) = schema else { |
| 206 | return Some(Err(ValidationError::single_type_error( |
| 207 | Location::new(), |
| 208 | ctx.location().clone(), |
| 209 | schema, |
| 210 | JsonType::Object, |
| 211 | ))); |
| 212 | }; |
| 213 | let ctx = ctx.new_at_location("patternProperties"); |
| 214 | let result = match ctx.config().pattern_options() { |
| 215 | PatternEngineOptions::FancyRegex { .. } => { |
| 216 | compile_pattern_entries(&ctx, map, |pctx, pattern, subschema| { |
| 217 | pctx.get_or_compile_regex(pattern) |
| 218 | .map_err(|()| invalid_regex(pctx, subschema)) |
| 219 | }) |
| 220 | .map(|patterns| { |
| 221 | build_validator_from_entries(patterns, |regex, node| { |
| 222 | Box::new(SingleValuePatternPropertiesValidator { regex, node }) |
| 223 | as Box<dyn Validate> |
| 224 | }) |
| 225 | }) |
| 226 | } |
| 227 | PatternEngineOptions::Regex { .. } => { |
| 228 | compile_pattern_entries(&ctx, map, |pctx, pattern, subschema| { |
| 229 | pctx.get_or_compile_standard_regex(pattern) |
| 230 | .map_err(|()| invalid_regex(pctx, subschema)) |
| 231 | }) |
| 232 | .map(|patterns| { |
| 233 | build_validator_from_entries(patterns, |regex, node| { |
| 234 | Box::new(SingleValuePatternPropertiesValidator { regex, node }) |
| 235 | as Box<dyn Validate> |
| 236 | }) |
| 237 | }) |
| 238 | } |
| 239 | }; |
| 240 | Some(result) |
| 241 | } |
| 242 | |
| 243 | fn invalid_regex<'a>(ctx: &compiler::Context, schema: &'a Value) -> ValidationError<'a> { |
| 244 | ValidationError::format(Location::new(), ctx.location().clone(), schema, "regex") |
| 245 | } |
| 246 | |
| 247 | /// Compile every `(pattern, subschema)` pair into `(regex, node)` tuples. |
| 248 | fn compile_pattern_entries<'a, R, F>( |
| 249 | ctx: &compiler::Context, |
| 250 | map: &'a Map<String, Value>, |
| 251 | mut compile_regex: F, |
| 252 | ) -> Result<Vec<(Arc<R>, SchemaNode)>, ValidationError<'a>> |
| 253 | where |
| 254 | F: FnMut(&compiler::Context, &str, &'a Value) -> Result<Arc<R>, ValidationError<'a>>, |
| 255 | { |
| 256 | let mut patterns = Vec::with_capacity(map.len()); |
| 257 | for (pattern, subschema) in map { |
| 258 | let pctx = ctx.new_at_location(pattern.as_str()); |
| 259 | let regex = compile_regex(&pctx, pattern, subschema)?; |
| 260 | let node = compiler::compile(&pctx, pctx.as_resource_ref(subschema))?; |
| 261 | patterns.push((regex, node)); |
| 262 | } |
| 263 | Ok(patterns) |
| 264 | } |
| 265 | |
| 266 | /// Pick the optimal validator representation for the compiled pattern entries. |
| 267 | fn build_validator_from_entries<R>( |
| 268 | mut entries: Vec<(Arc<R>, SchemaNode)>, |
| 269 | single_factory: impl FnOnce(Arc<R>, SchemaNode) -> Box<dyn Validate>, |
| 270 | ) -> Box<dyn Validate> |
| 271 | where |
| 272 | R: RegexEngine + 'static, |
| 273 | { |
| 274 | if entries.len() == 1 { |
| 275 | let (regex, node) = entries.pop().expect("len checked"); |
| 276 | single_factory(regex, node) |
| 277 | } else { |
| 278 | Box::new(PatternPropertiesValidator { patterns: entries }) |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | #[cfg(test)] |
| 283 | mod tests { |
| 284 | use crate::tests_util; |
| 285 | use serde_json::{json, Value}; |
| 286 | use test_case::test_case; |
| 287 | |
| 288 | #[test_case(&json!({"patternProperties": {"^f": {"type": "string"}}}), &json!({"f": 42}), "/patternProperties/^f/type")] |
| 289 | #[test_case(&json!({"patternProperties": {"^f": {"type": "string"}, "^x": {"type": "string"}}}), &json!({"f": 42}), "/patternProperties/^f/type")] |
| 290 | fn location(schema: &Value, instance: &Value, expected: &str) { |
| 291 | tests_util::assert_schema_location(schema, instance, expected); |
| 292 | } |
| 293 | } |