Skip to main content

roas_codegen/
diagnostic.rs

1//! What the generator reports, and how a report names its subject.
2
3use std::fmt;
4use url::Url;
5
6/// The identity of a schema, or of any other location in a description:
7/// the document's URI plus a JSON Pointer ([RFC 6901]) into it.
8///
9/// Two schemas from two documents never collide, and the same schema
10/// gets the same id on every run, because both halves come from the
11/// input rather than from anything the generator decides.
12///
13/// [RFC 6901]: https://www.rfc-editor.org/rfc/rfc6901
14#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
15#[non_exhaustive]
16pub struct SchemaId {
17    /// The document the schema lives in.
18    pub uri: Url,
19    /// Where in that document, as a JSON Pointer such as
20    /// `/components/schemas/Pet`. Empty for the document root.
21    pub pointer: String,
22}
23
24impl SchemaId {
25    pub fn new(uri: Url, pointer: impl Into<String>) -> Self {
26        SchemaId {
27            uri,
28            pointer: pointer.into(),
29        }
30    }
31}
32
33impl fmt::Display for SchemaId {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        write!(f, "{}#{}", self.uri, self.pointer)
36    }
37}
38
39/// How much a diagnostic matters.
40///
41/// An `Error` prevents generation of the affected type and of anything
42/// that depends on it; the rest of the document is still generated. A
43/// `Warning` changes nothing by itself, and a strict run promotes every
44/// warning to an error.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
46#[non_exhaustive]
47pub enum Severity {
48    Warning,
49    Error,
50}
51
52impl fmt::Display for Severity {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.write_str(match self {
55            Severity::Warning => "warning",
56            Severity::Error => "error",
57        })
58    }
59}
60
61/// What kind of thing a diagnostic reports. The message says it in
62/// words; the kind lets a caller act on it without parsing them.
63#[derive(Debug, Clone, PartialEq, Eq, Hash)]
64#[non_exhaustive]
65pub enum DiagnosticKind {
66    /// Upconverting the source version to 3.2 dropped something the
67    /// generator would have used. `keyword` names it.
68    NormalizationLoss { keyword: String },
69    /// A `$ref` to another resource. Nothing outside the document is
70    /// resolved yet, because a fetched document has its own version
71    /// and dialect and would be read under the root's.
72    ExternalReference { reference: String },
73    /// A `$ref` whose fragment is a plain-name anchor such as `#Pet`
74    /// rather than a JSON Pointer.
75    AnchorReference { reference: String },
76    /// An `$id` that re-bases the references beneath it. Their meaning
77    /// depends on the re-basing, which is not tracked yet.
78    IdRebasing { id: String },
79    /// A `$ref` to a local pointer that is not a component schema.
80    UnsupportedReferenceTarget { reference: String },
81    /// A keyword the model keeps but the generator does not handle.
82    /// Nothing is silently skipped: every one is named.
83    UnsupportedKeyword { keyword: String },
84    /// A schema no type can represent: `false`, or `not`.
85    Ungeneratable { keyword: String },
86    /// A `$schema` or `jsonSchemaDialect` other than the OAS dialect
87    /// and Draft 2020-12.
88    UnsupportedDialect { dialect: String },
89    /// The mapped numeric type narrows what the schema permits.
90    LossyNumber,
91    /// A composition that could not be proven safe and so lowers to
92    /// an open holder rather than a struct or an enum.
93    OpenComposition { keyword: String },
94    /// A typeless schema with object keywords: it permits every
95    /// instance type, so it lowers to an open holder.
96    TypelessObject,
97    /// An `enum` of numbers; the type stays the scalar.
98    NumericEnum,
99    /// A code-bearing `x-` extension left unapplied because
100    /// `allow_codegen_extensions` is off.
101    IgnoredExtension { keyword: String },
102    /// A component that is a bare `$ref` leading back to itself through
103    /// other bare references: nothing to generate.
104    ReferenceCycle,
105    /// `rustfmt` did not format the output — not installed, failed, or
106    /// could not be set up; the message says why — so it is unformatted and
107    /// will not match a formatted run byte for byte.
108    Unformatted,
109    /// With generated validation on, a constraint no generated check
110    /// covers: on a value of a type it does not apply to, or on array items
111    /// or map values written inline. `keyword` names it.
112    Unvalidated { keyword: String },
113}
114
115/// One thing the generator has to say about the description.
116#[derive(Debug, Clone, PartialEq, Eq)]
117#[non_exhaustive]
118pub struct Diagnostic {
119    pub severity: Severity,
120    pub kind: DiagnosticKind,
121    /// The schema, or the nearest schema-like object, the diagnostic is
122    /// about.
123    pub schema_id: SchemaId,
124    /// The exact spot, as a JSON Pointer into the same document as
125    /// [`schema_id`](Self::schema_id): usually one keyword beneath it.
126    pub pointer: String,
127    pub message: String,
128}
129
130impl Diagnostic {
131    /// A diagnostic for a [`Generation`](crate::Generation) a caller builds
132    /// itself; an `Error` one makes [`write`](crate::write()) refuse unless
133    /// partial output is allowed.
134    pub fn new(
135        severity: Severity,
136        kind: DiagnosticKind,
137        schema_id: SchemaId,
138        pointer: impl Into<String>,
139        message: impl Into<String>,
140    ) -> Self {
141        Diagnostic {
142            severity,
143            kind,
144            schema_id,
145            pointer: pointer.into(),
146            message: message.into(),
147        }
148    }
149}
150
151impl fmt::Display for Diagnostic {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(
154            f,
155            "{}: {}#{}: {}",
156            self.severity, self.schema_id.uri, self.pointer, self.message
157        )
158    }
159}
160
161/// Escape one reference token per RFC 6901 and append it to `pointer`.
162/// Mark a pointer as one of several readings of the same source
163/// schema — a `type: [a, b]` member — with a segment that can never
164/// appear in a real JSON Pointer: an unescaped `~` not followed by `0`
165/// or `1` is invalid there.
166pub(crate) fn synthetic(pointer: &str, label: &str) -> String {
167    format!("{pointer}/~{label}")
168}
169
170/// The source location of a possibly synthetic pointer: every synthetic
171/// segment removed.
172pub(crate) fn source_of(pointer: &str) -> String {
173    pointer
174        .split('/')
175        .filter(|segment| {
176            !(segment.starts_with('~') && !segment.starts_with("~0") && !segment.starts_with("~1"))
177        })
178        .collect::<Vec<_>>()
179        .join("/")
180}
181
182pub(crate) fn push_token(pointer: &mut String, token: &str) {
183    pointer.push('/');
184    for c in token.chars() {
185        match c {
186            '~' => pointer.push_str("~0"),
187            '/' => pointer.push_str("~1"),
188            c => pointer.push(c),
189        }
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn schema_id_displays_as_uri_and_pointer() {
199        let id = SchemaId::new(
200            Url::parse("file:///a.json").unwrap(),
201            "/components/schemas/Pet",
202        );
203        assert_eq!(id.to_string(), "file:///a.json#/components/schemas/Pet");
204    }
205
206    #[test]
207    fn pointer_tokens_are_escaped() {
208        let mut p = String::new();
209        push_token(&mut p, "a/b");
210        push_token(&mut p, "c~d");
211        assert_eq!(p, "/a~1b/c~0d");
212    }
213
214    #[test]
215    fn diagnostic_displays_severity_location_and_message() {
216        let d = Diagnostic {
217            severity: Severity::Warning,
218            kind: DiagnosticKind::NormalizationLoss {
219                keyword: "collectionFormat".into(),
220            },
221            schema_id: SchemaId::new(Url::parse("file:///a.json").unwrap(), "/parameters/0"),
222            pointer: "/parameters/0/collectionFormat".into(),
223            message: "dropped".into(),
224        };
225        assert_eq!(
226            d.to_string(),
227            "warning: file:///a.json#/parameters/0/collectionFormat: dropped"
228        );
229        assert!(Severity::Warning < Severity::Error);
230    }
231}