1use std::{cmp::Ordering, fmt};
54
55use serde_json::{Map, Number, Value};
56
57use crate::{
58 json_utils::compare_numbers,
59 tool::decode::{Whole, whole},
60};
61
62#[derive(Clone, Debug, PartialEq, Eq)]
64pub struct Problem {
65 pub at: String,
68 pub what: String,
70}
71
72impl fmt::Display for Problem {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 if self.at.is_empty() {
76 f.write_str(&self.what)
77 } else {
78 write!(f, "{}: {}", self.at, self.what)
79 }
80 }
81}
82
83pub fn validate(schema: &Value, value: &Value) -> Result<(), Vec<Problem>> {
87 let problems = Validator { root: schema }.check(schema, value, "", &[]);
88 if problems.is_empty() {
89 Ok(())
90 } else {
91 Err(problems)
92 }
93}
94
95struct Validator<'s> {
97 root: &'s Value,
98}
99
100impl<'s> Validator<'s> {
101 fn check(&self, schema: &'s Value, value: &Value, at: &str, refs: &[&'s str]) -> Vec<Problem> {
105 let schema = match schema {
106 Value::Object(schema) => schema,
107 Value::Bool(false) => return vec![problem(at, "no value is allowed here")],
108 _ => return Vec::new(),
109 };
110 let mut problems = Vec::new();
111 if let Some(Value::String(reference)) = schema.get("$ref")
112 && !refs.contains(&reference.as_str())
113 && let Some(target) = self.resolve(reference)
114 {
115 let mut followed = refs.to_vec();
116 followed.push(reference);
117 problems.extend(self.check(target, value, at, &followed));
118 }
119 if let Some(types) = schema.get("type")
120 && !fits_type(types, value)
121 {
122 problems.push(problem(
123 at,
124 format!(
125 "expected {}, got {}",
126 expected(types),
127 got(names_integer(types), value)
128 ),
129 ));
130 return problems;
131 }
132 if let Some(Value::Array(allowed)) = schema.get("enum")
133 && !allowed.iter().any(|it| same(it, value))
134 {
135 let allowed: Vec<String> = allowed.iter().map(Value::to_string).collect();
136 let what = format!(
137 "expected one of {}, got {}",
138 allowed.join(", "),
139 shown(value)
140 );
141 problems.push(problem(at, what));
142 }
143 if let Some(constant) = schema.get("const")
144 && !same(constant, value)
145 {
146 problems.push(problem(
147 at,
148 format!("expected {constant}, got {}", shown(value)),
149 ));
150 }
151 match value {
152 Value::Object(fields) => problems.extend(self.object(schema, fields, at)),
153 Value::Array(items) => problems.extend(self.array(schema, items, at)),
154 Value::String(text) => {
155 let length = text.chars().count();
156 problems.extend(count(
157 schema,
158 "minLength",
159 "maxLength",
160 "character",
161 length,
162 at,
163 ));
164 }
165 Value::Number(number) => problems.extend(bounds(schema, number, at)),
166 Value::Null | Value::Bool(_) => {}
167 }
168 if let Some(Value::Array(all)) = schema.get("allOf") {
169 for alternative in all {
170 problems.extend(self.check(alternative, value, at, refs));
171 }
172 }
173 if let Some(Value::Array(any)) = schema.get("anyOf") {
174 let results: Vec<_> = any
175 .iter()
176 .map(|it| self.check(it, value, at, refs))
177 .collect();
178 if !results.iter().any(Vec::is_empty) {
179 problems.extend(closest(any, results, value, at, "anyOf"));
180 }
181 }
182 if let Some(Value::Array(one)) = schema.get("oneOf") {
183 let results: Vec<_> = one
184 .iter()
185 .map(|it| self.check(it, value, at, refs))
186 .collect();
187 match results.iter().filter(|it| it.is_empty()).count() {
188 0 => problems.extend(closest(one, results, value, at, "oneOf")),
189 1 => {}
190 fitting => problems.push(problem(
191 at,
192 format!("fits {fitting} of its `oneOf` alternatives, not exactly one"),
193 )),
194 }
195 }
196 problems
197 }
198
199 fn object(
204 &self,
205 schema: &'s Map<String, Value>,
206 fields: &Map<String, Value>,
207 at: &str,
208 ) -> Vec<Problem> {
209 let mut problems = Vec::new();
210 let properties = schema.get("properties").and_then(Value::as_object);
211 let additional = schema
212 .get("additionalProperties")
213 .filter(|_| !schema.contains_key("patternProperties"));
214 let required: Vec<&str> = match schema.get("required") {
215 Some(Value::Array(required)) => required.iter().filter_map(Value::as_str).collect(),
216 _ => Vec::new(),
217 };
218 for (key, field) in fields {
219 let at = child(at, key);
220 match (
221 properties.and_then(|declared| declared.get(key)),
222 additional,
223 ) {
224 (Some(_), _) if field.is_null() && !required.contains(&key.as_str()) => {}
225 (Some(property), _) => problems.extend(self.check(property, field, &at, &[])),
226 (None, Some(Value::Bool(false))) => {
227 let allowed: Vec<String> = properties
228 .into_iter()
229 .flat_map(Map::keys)
230 .map(|name| format!("`{name}`"))
231 .collect();
232 let what = if allowed.is_empty() {
233 "not allowed: no keys are".to_owned()
234 } else {
235 format!("not allowed; the keys are {}", allowed.join(", "))
236 };
237 problems.push(problem(&at, what));
238 }
239 (None, Some(additional)) => {
240 problems.extend(self.check(additional, field, &at, &[]))
241 }
242 (None, None) => {}
243 }
244 }
245 for name in required {
246 if !fields.contains_key(name) {
247 problems.push(problem(&child(at, name), "missing"));
248 }
249 }
250 problems
251 }
252
253 fn array(&self, schema: &'s Map<String, Value>, items: &[Value], at: &str) -> Vec<Problem> {
257 let mut problems = count(schema, "minItems", "maxItems", "item", items.len(), at);
258 let (prefix, rest) = match (schema.get("prefixItems"), schema.get("items")) {
259 (Some(Value::Array(prefix)), rest) => (prefix.as_slice(), rest),
260 (_, Some(Value::Array(prefix))) => (prefix.as_slice(), None),
261 (_, rest) => (&[][..], rest),
262 };
263 for (index, item) in items.iter().enumerate() {
264 let subschema = prefix
265 .get(index)
266 .or_else(|| rest.filter(|_| index >= prefix.len()));
267 if let Some(subschema) = subschema {
268 problems.extend(self.check(subschema, item, &child(at, &index.to_string()), &[]));
269 }
270 }
271 problems
272 }
273
274 fn resolve(&self, reference: &str) -> Option<&'s Value> {
276 let pointer = reference.strip_prefix('#')?;
277 if pointer.is_empty() {
278 Some(self.root)
279 } else if pointer.starts_with('/') {
280 self.root.pointer(pointer)
281 } else {
282 None
283 }
284 }
285}
286
287fn closest(
291 alternatives: &[Value],
292 results: Vec<Vec<Problem>>,
293 value: &Value,
294 at: &str,
295 keyword: &str,
296) -> Vec<Problem> {
297 let types: Option<Vec<&Value>> = alternatives
298 .iter()
299 .map(|alternative| {
300 alternative
301 .get("type")
302 .filter(|types| !fits_type(types, value))
303 })
304 .collect();
305 if let Some(types) = types.filter(|types| !types.is_empty()) {
306 let integer = types.iter().any(|types| names_integer(types));
307 let names: Vec<String> = types.into_iter().map(expected).collect();
308 return vec![problem(
309 at,
310 format!(
311 "expected {}, got {}",
312 names.join(" or "),
313 got(integer, value)
314 ),
315 )];
316 }
317 results
318 .into_iter()
319 .filter(|problems| problems.iter().all(|it| it.at.len() > at.len()))
320 .min_by_key(Vec::len)
321 .unwrap_or_else(|| {
322 vec![problem(
323 at,
324 format!("fits none of its `{keyword}` alternatives"),
325 )]
326 })
327}
328
329fn count(
333 schema: &Map<String, Value>,
334 min: &str,
335 max: &str,
336 unit: &str,
337 length: usize,
338 at: &str,
339) -> Vec<Problem> {
340 let limit = |key| match schema.get(key).and_then(Value::as_number).and_then(whole) {
341 Some(Whole::Unsigned(limit)) => Some(limit),
342 _ => None,
343 };
344 let plural = |n: u64| {
345 if n == 1 {
346 format!("{n} {unit}")
347 } else {
348 format!("{n} {unit}s")
349 }
350 };
351 let length = u64::try_from(length).unwrap_or(u64::MAX);
352 let mut problems = Vec::new();
353 if let Some(min) = limit(min).filter(|min| length < *min) {
354 problems.push(problem(
355 at,
356 format!("expected at least {}, got {length}", plural(min)),
357 ));
358 }
359 if let Some(max) = limit(max).filter(|max| length > *max) {
360 problems.push(problem(
361 at,
362 format!("expected at most {}, got {length}", plural(max)),
363 ));
364 }
365 problems
366}
367
368fn bounds(schema: &Map<String, Value>, number: &Number, at: &str) -> Vec<Problem> {
370 let checks: [(&str, &str, fn(Ordering) -> bool); 4] = [
371 ("minimum", "at least", Ordering::is_ge),
372 ("maximum", "at most", Ordering::is_le),
373 ("exclusiveMinimum", "more than", Ordering::is_gt),
374 ("exclusiveMaximum", "less than", Ordering::is_lt),
375 ];
376 checks
377 .into_iter()
378 .filter_map(|(key, words, fits)| {
379 let bound = schema.get(key)?.as_number()?;
380 let fit = compare_numbers(number, bound).is_none_or(fits);
381 (!fit).then(|| problem(at, format!("expected {words} {bound}, got {number}")))
382 })
383 .collect()
384}
385
386fn fits_type(types: &Value, value: &Value) -> bool {
389 let is = |name: &str| match name {
390 "string" => value.is_string(),
391 "integer" => value.as_number().is_some_and(integral),
392 "number" => value.is_number(),
393 "boolean" => value.is_boolean(),
394 "array" => value.is_array(),
395 "object" => value.is_object(),
396 "null" => value.is_null(),
397 _ => true,
398 };
399 match types {
400 Value::String(name) => is(name),
401 Value::Array(names) => names.iter().filter_map(Value::as_str).any(is),
402 _ => true,
403 }
404}
405
406fn expected(types: &Value) -> String {
408 let word = |name: &str| match name {
409 "string" | "number" | "boolean" => format!("a {name}"),
410 "integer" | "array" | "object" => format!("an {name}"),
411 _ => name.to_owned(),
412 };
413 match types {
414 Value::String(name) => word(name),
415 Value::Array(names) => {
416 let words: Vec<String> = names.iter().filter_map(Value::as_str).map(word).collect();
417 words.join(" or ")
418 }
419 other => other.to_string(),
420 }
421}
422
423fn names_integer(types: &Value) -> bool {
425 match types {
426 Value::String(name) => name == "integer",
427 Value::Array(names) => names.iter().any(|name| name == "integer"),
428 _ => false,
429 }
430}
431
432fn got(integer: bool, value: &Value) -> &'static str {
435 match value {
436 Value::Number(number)
437 if integer
438 && !integral(number)
439 && number.as_f64().is_some_and(|n| n.fract() == 0.0) =>
440 {
441 "a number out of an integer's range"
442 }
443 value => kind(value),
444 }
445}
446
447fn kind(value: &Value) -> &'static str {
449 match value {
450 Value::Null => "null",
451 Value::Bool(_) => "a boolean",
452 Value::Number(number) if number.as_f64().is_some_and(|n| n.fract() == 0.0) => "a number",
453 Value::Number(_) => "a number with a fraction",
454 Value::String(_) => "a string",
455 Value::Array(_) => "an array",
456 Value::Object(_) => "an object",
457 }
458}
459
460fn shown(value: &Value) -> String {
462 match value {
463 Value::Array(_) | Value::Object(_) => kind(value).to_owned(),
464 Value::String(text) if text.chars().count() > 40 => kind(value).to_owned(),
465 scalar => scalar.to_string(),
466 }
467}
468
469fn integral(number: &Number) -> bool {
472 whole(number).is_some()
473}
474
475fn same(a: &Value, b: &Value) -> bool {
478 match (a, b) {
479 (Value::Number(a), Value::Number(b)) => {
480 a == b || compare_numbers(a, b) == Some(Ordering::Equal)
481 }
482 (Value::Array(a), Value::Array(b)) => {
483 a.len() == b.len() && a.iter().zip(b).all(|(a, b)| same(a, b))
484 }
485 (Value::Object(a), Value::Object(b)) => {
486 a.len() == b.len()
487 && a.iter()
488 .all(|(key, a)| b.get(key).is_some_and(|b| same(a, b)))
489 }
490 (a, b) => a == b,
491 }
492}
493
494fn child(at: &str, key: &str) -> String {
496 format!("{at}/{}", key.replace('~', "~0").replace('/', "~1"))
497}
498
499fn problem(at: &str, what: impl Into<String>) -> Problem {
500 Problem {
501 at: at.to_owned(),
502 what: what.into(),
503 }
504}
505
506#[cfg(test)]
507mod tests;