Skip to main content

roas_codegen/
validate.rs

1//! The step between parsing and generating, enforced by a type.
2
3use crate::diagnostic::Diagnostic;
4use crate::report;
5use crate::source::SourceDocument;
6use enumset::EnumSet;
7use roas::validation::{Options, Validate, ValidationError};
8use std::fmt;
9use thiserror::Error;
10
11/// The `roas` validation checks that say nothing about the schemas being
12/// generated: unused components and path items, undeclared tags, empty
13/// titles, versions, response descriptions and external-documentation
14/// URLs, duplicate operation ids, malformed URLs.
15/// Generation starts from this set; a caller adds to it.
16pub fn generation_options() -> EnumSet<Options> {
17    roas::validation::IGNORE_UNUSED
18        | roas::validation::IGNORE_EMPTY_REQUIRED_FIELDS
19        | Options::IgnoreUnusedPathItems
20        | Options::IgnoreMissingTags
21        | Options::IgnoreNonUniqOperationIDs
22        | Options::IgnoreInvalidUrls
23}
24
25/// Validate a document with `roas`, skipping external references.
26///
27/// The result is the only way to obtain a [`ValidatedSourceDocument`],
28/// which is the only thing generation accepts — so the step cannot be
29/// forgotten and cannot be bypassed. `options` is `roas`'s own set;
30/// [`Options::IgnoreExternalReferences`] is always added, because the
31/// validator would read a fetched document under the root's version.
32/// External references are reported by
33/// [`ValidatedSourceDocument::diagnostics`] instead.
34///
35/// On failure the document comes back inside the error, so nothing the
36/// caller parsed is lost.
37pub fn validate(
38    document: SourceDocument,
39    options: EnumSet<Options>,
40) -> Result<ValidatedSourceDocument, SourceValidationError> {
41    let options = options | Options::IgnoreExternalReferences;
42    match document.spec().validate(options, None) {
43        Ok(()) => Ok(ValidatedSourceDocument { document }),
44        Err(error) => Err(SourceValidationError {
45            document: Box::new(document),
46            errors: error.errors,
47        }),
48    }
49}
50
51/// A [`SourceDocument`] that passed [`validate`].
52#[derive(Debug, Clone)]
53pub struct ValidatedSourceDocument {
54    document: SourceDocument,
55}
56
57impl ValidatedSourceDocument {
58    /// The document itself.
59    pub fn document(&self) -> &SourceDocument {
60        &self.document
61    }
62
63    /// Give the document back, dropping the proof of validation.
64    pub fn into_document(self) -> SourceDocument {
65        self.document
66    }
67
68    /// Everything the generator has to say before generating: what the
69    /// normalization to 3.2 lost, and every reference the first release
70    /// refuses to follow. Ordered by where it occurs in the source.
71    pub fn diagnostics(&self) -> Vec<Diagnostic> {
72        let mut out = self.document.normalization().to_vec();
73        report::reference_restrictions(self.document.raw(), self.document.uri(), &mut out);
74        out.sort_by(|a, b| a.pointer.cmp(&b.pointer).then(a.severity.cmp(&b.severity)));
75        out
76    }
77}
78
79impl std::ops::Deref for ValidatedSourceDocument {
80    type Target = SourceDocument;
81
82    fn deref(&self) -> &SourceDocument {
83        &self.document
84    }
85}
86
87/// The document failed `roas` validation. The document is returned, not
88/// consumed, so it can be inspected or validated again with other
89/// options. Boxed, since the whole 3.2 model rides inside.
90#[derive(Debug, Error)]
91#[non_exhaustive]
92pub struct SourceValidationError {
93    pub document: Box<SourceDocument>,
94    pub errors: Vec<ValidationError>,
95}
96
97impl fmt::Display for SourceValidationError {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        write!(
100            f,
101            "{} is not a valid {} description: {} error(s)",
102            self.document.uri(),
103            self.document.version(),
104            self.errors.len()
105        )?;
106        for error in &self.errors {
107            write!(f, "\n- {error}")?;
108        }
109        Ok(())
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    #[test]
116    fn unused_path_items_are_exempt_too() {
117        let options = super::generation_options();
118        assert!(options.contains(roas::validation::Options::IgnoreUnusedPathItems));
119        assert!(options.contains(roas::validation::Options::IgnoreEmptyExternalDocumentationUrl));
120    }
121}