1use regex::Regex;
17use serde_json::{Map, Value};
18use std::collections::{BTreeSet, HashMap};
19
20const ANNOTATIONS: &[&str] = &[
22 "title",
23 "description",
24 "default",
25 "example",
26 "examples",
27 "deprecated",
28 "readOnly",
29 "writeOnly",
30 "format",
31 "contentMediaType",
32 "contentEncoding",
33 "discriminator",
34 "$schema",
35 "$id",
36 "$comment",
37 "$defs",
38 "definitions",
39 "nullable",
40];
41
42const CHECKED: &[&str] = &[
44 "$ref",
45 "type",
46 "enum",
47 "const",
48 "properties",
49 "required",
50 "additionalProperties",
51 "propertyNames",
52 "items",
53 "minItems",
54 "maxItems",
55 "minimum",
56 "maximum",
57 "exclusiveMinimum",
58 "exclusiveMaximum",
59 "minLength",
60 "maxLength",
61 "pattern",
62 "oneOf",
63 "anyOf",
64 "allOf",
65];
66
67const MAX_DEPTH: usize = 64;
70
71pub(crate) fn problems(schema: &Map<String, Value>, value: &Value) -> Vec<String> {
74 let root = Value::Object(schema.clone());
75 let mut checker = Checker {
76 root: &root,
77 problems: Vec::new(),
78 unsupported: Vec::new(),
79 named_by_all_of: HashMap::new(),
80 };
81 checker.check(&root, value, "", 0);
82 let mut all = checker.unsupported;
83 all.extend(checker.problems);
84 all
85}
86
87struct Checker<'a> {
88 root: &'a Value,
89 problems: Vec<String>,
91 unsupported: Vec<String>,
93 named_by_all_of: HashMap<String, BTreeSet<String>>,
95}
96
97impl<'a> Checker<'a> {
98 fn fork(&self) -> Checker<'a> {
99 Checker {
100 root: self.root,
101 problems: Vec::new(),
102 unsupported: Vec::new(),
103 named_by_all_of: self.named_by_all_of.clone(),
104 }
105 }
106
107 fn unsupported(&mut self, path: &str, what: String) {
108 self.unsupported.push(format!(
109 "the outputs schema {what} at {}, which Alien can't check a binding against",
110 describe(path)
111 ));
112 }
113
114 fn problem(&mut self, path: &str, what: String) {
115 self.problems.push(format!("{} {what}", describe(path)));
116 }
117
118 fn check(&mut self, schema: &Value, value: &Value, path: &str, depth: usize) {
119 if depth > MAX_DEPTH {
120 self.unsupported(path, "nests deeper than 64 references".to_string());
121 return;
122 }
123 let schema = match schema {
124 Value::Bool(true) => return,
125 Value::Bool(false) => {
126 self.problem(path, "is not allowed".to_string());
127 return;
128 }
129 Value::Object(schema) => schema,
130 _ => {
131 self.unsupported(path, "has a schema that is not an object".to_string());
132 return;
133 }
134 };
135 for keyword in schema.keys() {
136 if !CHECKED.contains(&keyword.as_str())
137 && !ANNOTATIONS.contains(&keyword.as_str())
138 && !keyword.starts_with("x-")
139 {
140 self.unsupported(path, format!("uses '{keyword}'"));
141 }
142 }
143 if schema
144 .get("properties")
145 .is_some_and(|properties| !properties.is_object())
146 {
147 self.unsupported(path, "has 'properties' that is not an object".to_string());
148 }
149 if schema.get("required").is_some_and(|required| {
150 !required
151 .as_array()
152 .is_some_and(|names| names.iter().all(Value::is_string))
153 }) {
154 self.unsupported(
155 path,
156 "has a 'required' that is not a list of names".to_string(),
157 );
158 }
159 if !self.unsupported.is_empty() {
160 return;
161 }
162 if value.is_null() && schema.get("nullable") == Some(&Value::Bool(true)) {
163 return;
164 }
165
166 if let Some(reference) = schema.get("$ref") {
167 match reference
168 .as_str()
169 .and_then(|reference| self.resolve(reference))
170 {
171 Some(target) => self.check(target, value, path, depth + 1),
172 None => self.unsupported(path, format!("has the reference {reference}")),
173 }
174 }
175 if let Some(kinds) = schema.get("type") {
176 let kinds: Vec<&str> = match kinds {
177 Value::String(kind) => vec![kind.as_str()],
178 Value::Array(kinds) => kinds.iter().filter_map(Value::as_str).collect(),
179 _ => Vec::new(),
180 };
181 if kinds.is_empty() {
182 self.unsupported(path, format!("has the type {}", schema["type"]));
183 return;
184 }
185 if !kinds.iter().any(|kind| has_type(kind, value)) {
186 self.problem(
187 path,
188 format!(
189 "is {}, where the outputs schema says {}",
190 type_name(value),
191 kinds.join(" or ")
192 ),
193 );
194 return;
195 }
196 }
197 if let Some(allowed) = schema.get("enum") {
198 match allowed {
199 Value::Array(allowed) if !allowed.contains(value) => {
200 self.problem(
201 path,
202 format!(
203 "is {value}, which is not one of {}",
204 Value::Array(allowed.clone())
205 ),
206 );
207 }
208 Value::Array(_) => {}
209 _ => self.unsupported(path, "has an 'enum' that is not a list".to_string()),
210 }
211 }
212 if let Some(constant) = schema.get("const") {
213 if constant != value {
214 self.problem(
215 path,
216 format!("is {value}, where the outputs schema says {constant}"),
217 );
218 }
219 }
220 if value.is_object() && schema.contains_key("allOf") {
221 let names = property_names(self.root, schema, depth);
222 self.named_by_all_of
223 .entry(path.to_string())
224 .or_default()
225 .extend(names);
226 }
227 match value {
228 Value::Object(object) => self.check_object(schema, object, path, depth),
229 Value::Array(items) => self.check_array(schema, items, path, depth),
230 Value::String(text) => self.check_string(schema, text, path),
231 Value::Number(_) => self.check_number(schema, value, path),
232 _ => {}
233 }
234 for keyword in ["allOf", "anyOf", "oneOf"] {
235 if let Some(branches) = schema.get(keyword) {
236 self.check_branches(keyword, branches, value, path, depth);
237 }
238 }
239 }
240
241 fn check_branches(
242 &mut self,
243 keyword: &str,
244 branches: &Value,
245 value: &Value,
246 path: &str,
247 depth: usize,
248 ) {
249 let Value::Array(branches) = branches else {
250 self.unsupported(path, format!("has a '{keyword}' that is not a list"));
251 return;
252 };
253 let mut matched = 0;
254 let mut first_problems = Vec::new();
255 for branch in branches {
256 let mut fork = self.fork();
257 fork.check(branch, value, path, depth + 1);
258 if !fork.unsupported.is_empty() {
259 self.unsupported.extend(fork.unsupported);
260 return;
261 }
262 if fork.problems.is_empty() {
263 matched += 1;
264 } else if keyword == "allOf" {
265 self.problems.extend(fork.problems);
266 } else if first_problems.is_empty() {
267 first_problems = fork.problems;
268 }
269 }
270 match keyword {
271 "anyOf" if matched == 0 => self.problem(
272 path,
273 format!(
274 "matches none of its alternatives ({})",
275 first_problems.join("; ")
276 ),
277 ),
278 "oneOf" if matched == 0 => self.problem(
279 path,
280 format!(
281 "matches none of its alternatives ({})",
282 first_problems.join("; ")
283 ),
284 ),
285 "oneOf" if matched > 1 => self.problem(
286 path,
287 format!("matches {matched} of its alternatives, where exactly one must"),
288 ),
289 _ => {}
290 }
291 }
292
293 fn check_object(
294 &mut self,
295 schema: &Map<String, Value>,
296 object: &Map<String, Value>,
297 path: &str,
298 depth: usize,
299 ) {
300 let properties = schema.get("properties").and_then(Value::as_object);
302 for name in schema
303 .get("required")
304 .and_then(Value::as_array)
305 .into_iter()
306 .flatten()
307 .filter_map(Value::as_str)
308 {
309 if !object.contains_key(name) {
310 self.problem(path, format!("has no '{name}'"));
311 }
312 }
313 let named_elsewhere = self.named_by_all_of.get(path).cloned().unwrap_or_default();
314 for (name, field) in object {
315 let field_path = join(path, name);
316 if let Some(names) = schema.get("propertyNames") {
317 self.check(names, &Value::String(name.clone()), &field_path, depth);
318 }
319 match (
320 properties.and_then(|properties| properties.get(name)),
321 schema.get("additionalProperties"),
322 ) {
323 (Some(property), _) => self.check(property, field, &field_path, depth),
324 (None, Some(additional)) => self.check(additional, field, &field_path, depth),
325 (None, None) if properties.is_some() && !named_elsewhere.contains(name) => {
326 self.problem(
327 &field_path,
328 "is not one of the outputs its schema names".to_string(),
329 );
330 }
331 (None, None) => {}
332 }
333 }
334 }
335
336 fn check_array(
337 &mut self,
338 schema: &Map<String, Value>,
339 items: &[Value],
340 path: &str,
341 depth: usize,
342 ) {
343 if let Some(item) = schema.get("items") {
344 if item.is_array() {
345 self.unsupported(path, "has a list of 'items'".to_string());
346 return;
347 }
348 for (index, value) in items.iter().enumerate() {
349 self.check(
350 item,
351 value,
352 &format!(
353 "{}[{index}]",
354 if path.is_empty() { "outputs" } else { path }
355 ),
356 depth,
357 );
358 }
359 }
360 self.check_count(schema, "minItems", "maxItems", items.len(), "items", path);
361 }
362
363 fn check_string(&mut self, schema: &Map<String, Value>, text: &str, path: &str) {
364 self.check_count(
365 schema,
366 "minLength",
367 "maxLength",
368 text.chars().count(),
369 "characters",
370 path,
371 );
372 if let Some(pattern) = schema.get("pattern") {
373 match pattern.as_str().map(Regex::new) {
374 Some(Ok(pattern)) if pattern.is_match(text) => {}
375 Some(Ok(pattern)) => self.problem(
376 path,
377 format!("is {text:?}, which doesn't match {}", pattern.as_str()),
378 ),
379 _ => self.unsupported(path, format!("has the pattern {pattern}")),
380 }
381 }
382 }
383
384 fn check_number(&mut self, schema: &Map<String, Value>, value: &Value, path: &str) {
385 let Some(number) = value.as_f64() else { return };
386 for (keyword, holds) in [
387 (
388 "minimum",
389 (|n: f64, bound: f64| n >= bound) as fn(f64, f64) -> bool,
390 ),
391 ("maximum", |n, bound| n <= bound),
392 ("exclusiveMinimum", |n, bound| n > bound),
393 ("exclusiveMaximum", |n, bound| n < bound),
394 ] {
395 match schema.get(keyword) {
396 None => {}
397 Some(bound) => match bound.as_f64() {
398 Some(bound) if holds(number, bound) => {}
399 Some(bound) => self.problem(
400 path,
401 format!("is {value}, where the outputs schema says {keyword} {bound}"),
402 ),
403 None => self.unsupported(path, format!("has the {keyword} {bound}")),
404 },
405 }
406 }
407 }
408
409 fn check_count(
410 &mut self,
411 schema: &Map<String, Value>,
412 min: &str,
413 max: &str,
414 count: usize,
415 unit: &str,
416 path: &str,
417 ) {
418 for (keyword, holds) in [
419 (
420 min,
421 (|count: u64, bound: u64| count >= bound) as fn(u64, u64) -> bool,
422 ),
423 (max, |count, bound| count <= bound),
424 ] {
425 match schema.get(keyword) {
426 None => {}
427 Some(bound) => match bound.as_u64() {
428 Some(bound) if holds(count as u64, bound) => {}
429 Some(bound) => self.problem(
430 path,
431 format!(
432 "has {count} {unit}, where the outputs schema says {keyword} {bound}"
433 ),
434 ),
435 None => self.unsupported(path, format!("has the {keyword} {bound}")),
436 },
437 }
438 }
439 }
440
441 fn resolve(&self, reference: &str) -> Option<&'a Value> {
443 let pointer = reference.strip_prefix('#')?;
444 self.root.pointer(pointer)
445 }
446}
447
448fn property_names(root: &Value, schema: &Map<String, Value>, depth: usize) -> BTreeSet<String> {
451 let mut names = BTreeSet::new();
452 if depth > MAX_DEPTH {
453 return names;
454 }
455 if let Some(Value::Object(properties)) = schema.get("properties") {
456 names.extend(properties.keys().cloned());
457 }
458 if let Some(Value::Object(target)) = schema
459 .get("$ref")
460 .and_then(Value::as_str)
461 .and_then(|reference| root.pointer(reference.strip_prefix('#')?))
462 {
463 names.extend(property_names(root, target, depth + 1));
464 }
465 for branch in schema
466 .get("allOf")
467 .and_then(Value::as_array)
468 .into_iter()
469 .flatten()
470 {
471 if let Value::Object(branch) = branch {
472 names.extend(property_names(root, branch, depth + 1));
473 }
474 }
475 names
476}
477
478pub fn output_names(schema: &Map<String, Value>) -> BTreeSet<String> {
482 property_names(&Value::Object(schema.clone()), schema, 0)
483}
484
485pub const FLATTENED_OPTION: &str = "flatten an Option or an enum, whose fields depend on the value, which Alien can't check a binding against; flatten a struct and make its fields optional instead";
487
488pub const FLATTENED_MAP: &str = "flatten a map beside a struct's fields, which Alien can't check a binding against; put the map under a named field instead of flattening it";
490
491pub fn flattens_alternatives(schema: &Map<String, Value>) -> bool {
497 let root = Value::Object(schema.clone());
498 any_all_of(&root, &root, &|branches| {
499 branches
500 .iter()
501 .any(|branch| branch.contains_key("oneOf") || branch.contains_key("anyOf"))
502 })
503}
504
505pub fn flattens_a_map_beside_fields(schema: &Map<String, Value>) -> bool {
510 let root = Value::Object(schema.clone());
511 any_all_of(&root, &root, &|branches| {
512 let open = |branch: &Map<String, Value>| {
513 branch
514 .get("additionalProperties")
515 .is_some_and(|additional| additional != &Value::Bool(false))
516 };
517 branches.iter().any(|branch| open(branch))
518 && branches
519 .iter()
520 .any(|branch| !open(branch) && !property_names(&root, branch, 0).is_empty())
521 })
522}
523
524type AllOfTest<'a> = dyn Fn(&[&Map<String, Value>]) -> bool + 'a;
526
527fn any_all_of(root: &Value, node: &Value, test: &AllOfTest<'_>) -> bool {
531 let Value::Object(schema) = node else {
532 return false;
533 };
534 if let Some(Value::Array(branches)) = schema.get("allOf") {
535 let branches: Vec<_> = branches
536 .iter()
537 .filter_map(Value::as_object)
538 .map(|branch| resolved(root, branch, 0))
539 .collect();
540 if test(&branches) {
541 return true;
542 }
543 }
544 schema
545 .iter()
546 .any(|(keyword, value)| match keyword.as_str() {
547 "properties" | "$defs" | "definitions" => value
549 .as_object()
550 .into_iter()
551 .flat_map(Map::values)
552 .any(|schema| any_all_of(root, schema, test)),
553 "enum" | "const" | "default" | "example" | "examples" => false,
555 _ => match value {
556 Value::Array(schemas) => {
557 schemas.iter().any(|schema| any_all_of(root, schema, test))
558 }
559 schema => any_all_of(root, schema, test),
560 },
561 })
562}
563
564fn resolved<'a>(
566 root: &'a Value,
567 schema: &'a Map<String, Value>,
568 depth: usize,
569) -> &'a Map<String, Value> {
570 match schema
571 .get("$ref")
572 .and_then(Value::as_str)
573 .and_then(|reference| root.pointer(reference.strip_prefix('#')?))
574 .and_then(Value::as_object)
575 {
576 Some(target) if depth <= MAX_DEPTH => resolved(root, target, depth + 1),
577 _ => schema,
578 }
579}
580
581fn has_type(kind: &str, value: &Value) -> bool {
584 match kind {
585 "integer" => value.as_f64().is_some_and(|number| number.fract() == 0.0),
586 "number" => value.is_number(),
587 other => type_name(value) == other,
588 }
589}
590
591fn type_name(value: &Value) -> &'static str {
592 match value {
593 Value::Null => "null",
594 Value::Bool(_) => "boolean",
595 Value::Number(_) => "number",
596 Value::String(_) => "string",
597 Value::Array(_) => "array",
598 Value::Object(_) => "object",
599 }
600}
601
602fn join(path: &str, name: &str) -> String {
603 if path.is_empty() {
604 name.to_string()
605 } else {
606 format!("{path}.{name}")
607 }
608}
609
610fn describe(path: &str) -> String {
611 if path.is_empty() {
612 "the binding".to_string()
613 } else {
614 format!("'{path}'")
615 }
616}