Skip to main content

alpha2_diagnose/
diagnostic.rs

1//! One problem found in a document, and what can be done about it.
2
3use serde::{Deserialize, Serialize};
4
5use crate::path::Path;
6use crate::tree::{Node, Span};
7
8/// How serious a diagnostic is. Ordered from most to least serious.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
10#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
11#[serde(rename_all = "snake_case")]
12pub enum Severity {
13    /// The engine refuses the document.
14    Error,
15    /// The engine accepts the document, but it is likely not what was meant.
16    Warning,
17    /// Information that helps the next step.
18    Hint,
19}
20
21impl Severity {
22    /// The lower-case name, as serialized.
23    #[must_use]
24    pub const fn name(self) -> &'static str {
25        match self {
26            Self::Error => "error",
27            Self::Warning => "warning",
28            Self::Hint => "hint",
29        }
30    }
31}
32
33/// A kind of diagnostic: its stable name, severity, level and one sentence. Codes are the
34/// contract a consumer switches on; messages are not.
35#[derive(Debug, PartialEq, Eq, Serialize)]
36pub struct Code {
37    /// `layer.name`, such as `shape.unknown_field`.
38    pub name: &'static str,
39    /// The severity of every diagnostic of this code.
40    pub severity: Severity,
41    /// 1 for a fact the rules state, 2 for a heuristic, 3 for a reviewer's finding.
42    pub level: u8,
43    /// What the code means, in one sentence.
44    pub summary: &'static str,
45}
46
47impl Code {
48    /// The layer: the part of the name before the first `.`.
49    #[must_use]
50    pub fn layer(&self) -> &'static str {
51        self.name.split('.').next().unwrap_or(self.name)
52    }
53}
54
55/// The prefix of the codes a reviewer outside the engine uses for its findings.
56pub const REVIEW_PREFIX: &str = "review.";
57
58/// Whether a fix may be applied by a program without asking.
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
60#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
61#[serde(rename_all = "snake_case")]
62pub enum Applicability {
63    /// The document's meaning cannot change: a syntax recovery, an integer's spelling, a key
64    /// spelt another way. The engine applies these when asked.
65    Certain,
66    /// Probably right, never applied by the engine.
67    Likely,
68}
69
70/// One change to a document.
71#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
72#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
73#[serde(tag = "op", rename_all = "snake_case")]
74pub enum Edit {
75    /// Replaces bytes of the text the document was read from; the reader's fixes only.
76    Text {
77        /// Byte offset in the text.
78        offset: usize,
79        /// Bytes replaced.
80        length: usize,
81        /// What goes in their place.
82        replacement: String,
83    },
84    /// Replaces the value at `path`.
85    Replace {
86        /// The value replaced.
87        path: Path,
88        /// The new value.
89        value: Node,
90    },
91    /// Renames the key that ends `path`, keeping its value and place.
92    RenameKey {
93        /// The entry renamed.
94        path: Path,
95        /// The new key.
96        to: String,
97    },
98    /// Removes the entry or item at `path`.
99    Remove {
100        /// What is removed.
101        path: Path,
102    },
103    /// Adds `value` at `path`: a new key of an object, or an index of an array, the items from
104    /// it on moved one up.
105    Insert {
106        /// Where the value goes; its parent exists.
107        path: Path,
108        /// The value.
109        value: Node,
110    },
111    /// Moves the value at `from` to `to`, whose parent exists and which is not taken.
112    Move {
113        /// The value moved.
114        from: Path,
115        /// Where it goes.
116        to: Path,
117    },
118}
119
120impl Edit {
121    /// The path an edit changes first; `None` for a text edit.
122    #[must_use]
123    pub const fn path(&self) -> Option<&Path> {
124        match self {
125            Self::Text { .. } => None,
126            Self::Replace { path, .. }
127            | Self::RenameKey { path, .. }
128            | Self::Remove { path }
129            | Self::Insert { path, .. } => Some(path),
130            Self::Move { from, .. } => Some(from),
131        }
132    }
133}
134
135/// A way to fix a diagnostic: edits applied together.
136#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
137#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
138pub struct Fix {
139    /// What the fix does, in a few words.
140    pub title: String,
141    /// Whether a program may apply it without asking.
142    pub applicability: Applicability,
143    /// The edits, applied together.
144    pub edits: Vec<Edit>,
145}
146
147impl Fix {
148    /// A fix that cannot change what the document means.
149    #[must_use]
150    pub fn certain(title: impl Into<String>, edits: Vec<Edit>) -> Self {
151        Self {
152            title: title.into(),
153            applicability: Applicability::Certain,
154            edits,
155        }
156    }
157
158    /// A fix that is probably right.
159    #[must_use]
160    pub fn likely(title: impl Into<String>, edits: Vec<Edit>) -> Self {
161        Self {
162            title: title.into(),
163            applicability: Applicability::Likely,
164            edits,
165        }
166    }
167}
168
169/// A section of the schema reference: a topic and a definition, as
170/// `schema/reference/index.json` names them.
171#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
172#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
173pub struct Reference {
174    /// `project`, `compose`, `effects`, ...
175    pub topic: String,
176    /// The definition's name.
177    pub definition: String,
178}
179
180/// One problem in a document.
181#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
182#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
183pub struct Diagnostic {
184    /// The code, `layer.name`.
185    pub code: String,
186    /// How serious it is.
187    pub severity: Severity,
188    /// 1 for a fact, 2 for a heuristic, 3 for a reviewer's finding.
189    pub level: u8,
190    /// Where in the document. It names a value that exists in the document read.
191    pub path: Path,
192    /// Where in the text; absent for a document without text.
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub span: Option<Span>,
195    /// What is wrong, in one sentence.
196    pub message: String,
197    /// What to do about it; a guess says so.
198    #[serde(default)]
199    pub help: Vec<String>,
200    /// Changes that fix it.
201    #[serde(default)]
202    pub fixes: Vec<Fix>,
203    /// The section of the schema reference about the value.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub reference: Option<Reference>,
206    /// The object it is about, by id: `{"type": "clip", "clip": "clip-1"}`.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub subject: Option<Node>,
209    /// How many places have this problem; the others are in `also`.
210    #[serde(default = "one")]
211    pub count: usize,
212    /// Up to three other places with the same problem.
213    #[serde(default, skip_serializing_if = "Vec::is_empty")]
214    pub also: Vec<Path>,
215    /// Fields the code defines: what was found, a limit, the parts of a lint issue.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub data: Option<Node>,
218    /// Who found it, when not the engine: a host's or a reviewer's name.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub origin: Option<String>,
221    /// The text of the value it is about, when asked for; at most 400 bytes.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub excerpt: Option<String>,
224}
225
226const fn one() -> usize {
227    1
228}
229
230impl Diagnostic {
231    /// A diagnostic of one of the engine's codes.
232    #[must_use]
233    pub fn new(code: &'static Code, path: Path, message: impl Into<String>) -> Self {
234        Self::external(code.name, code.severity, code.level, path, message)
235    }
236
237    /// A diagnostic of a code outside the engine's tables, such as a reviewer's `review.*`
238    /// finding; give it an [`origin`](Self::origin).
239    #[must_use]
240    pub fn external(
241        code: impl Into<String>,
242        severity: Severity,
243        level: u8,
244        path: Path,
245        message: impl Into<String>,
246    ) -> Self {
247        Self {
248            code: code.into(),
249            severity,
250            level,
251            path,
252            span: None,
253            message: message.into(),
254            help: Vec::new(),
255            fixes: Vec::new(),
256            reference: None,
257            subject: None,
258            count: 1,
259            also: Vec::new(),
260            data: None,
261            origin: None,
262            excerpt: None,
263        }
264    }
265
266    /// Sets the place in the text.
267    #[must_use]
268    pub const fn at(mut self, span: Option<Span>) -> Self {
269        self.span = span;
270        self
271    }
272
273    /// Adds a help line.
274    #[must_use]
275    pub fn help(mut self, line: impl Into<String>) -> Self {
276        self.help.push(line.into());
277        self
278    }
279
280    /// Adds a fix.
281    #[must_use]
282    pub fn fix(mut self, fix: Fix) -> Self {
283        self.fixes.push(fix);
284        self
285    }
286
287    /// Sets the reference section.
288    #[must_use]
289    pub fn reference(mut self, topic: impl Into<String>, definition: impl Into<String>) -> Self {
290        self.reference = Some(Reference {
291            topic: topic.into(),
292            definition: definition.into(),
293        });
294        self
295    }
296
297    /// Sets the object it is about.
298    #[must_use]
299    pub fn subject(mut self, subject: Node) -> Self {
300        self.subject = Some(subject);
301        self
302    }
303
304    /// Sets the code's fields.
305    #[must_use]
306    pub fn data(mut self, data: Node) -> Self {
307        self.data = Some(data);
308        self
309    }
310
311    /// Sets who found it.
312    #[must_use]
313    pub fn origin(mut self, origin: impl Into<String>) -> Self {
314        self.origin = Some(origin.into());
315        self
316    }
317
318    /// Whether the code is `code`.
319    #[must_use]
320    pub fn is(&self, code: &Code) -> bool {
321        self.code == code.name
322    }
323
324    /// Whether it is an error.
325    #[must_use]
326    pub fn is_error(&self) -> bool {
327        self.severity == Severity::Error
328    }
329
330    /// A field of [`data`](Self::data).
331    #[must_use]
332    pub fn datum(&self, key: &str) -> Option<&Node> {
333        self.data.as_ref()?.get(key)
334    }
335
336    /// Whether some help line or fix already exists.
337    #[must_use]
338    pub fn has_advice(&self) -> bool {
339        !self.help.is_empty() || !self.fixes.is_empty()
340    }
341}
342
343/// Collects diagnostics up to a capacity and counts the ones past it.
344#[derive(Clone, Debug)]
345pub struct Collector {
346    items: Vec<Diagnostic>,
347    dropped: usize,
348    capacity: usize,
349}
350
351impl Default for Collector {
352    fn default() -> Self {
353        Self::new(Self::DEFAULT_CAPACITY)
354    }
355}
356
357impl Collector {
358    /// The most diagnostics collected for one document by default.
359    pub const DEFAULT_CAPACITY: usize = 1000;
360
361    /// A collector that keeps at most `capacity` diagnostics.
362    #[must_use]
363    pub const fn new(capacity: usize) -> Self {
364        Self {
365            items: Vec::new(),
366            dropped: 0,
367            capacity,
368        }
369    }
370
371    /// Adds a diagnostic, or counts it when full.
372    pub fn push(&mut self, diagnostic: Diagnostic) {
373        if self.items.len() < self.capacity {
374            self.items.push(diagnostic);
375        } else {
376            self.dropped += 1;
377        }
378    }
379
380    /// Whether no more diagnostics are kept.
381    #[must_use]
382    pub const fn is_full(&self) -> bool {
383        self.items.len() >= self.capacity
384    }
385
386    /// The diagnostics kept.
387    #[must_use]
388    pub fn items(&self) -> &[Diagnostic] {
389        &self.items
390    }
391
392    /// The diagnostics kept, for change.
393    pub fn items_mut(&mut self) -> &mut [Diagnostic] {
394        &mut self.items
395    }
396
397    /// How many were not kept.
398    #[must_use]
399    pub const fn dropped(&self) -> usize {
400        self.dropped
401    }
402
403    /// Whether an error was kept.
404    #[must_use]
405    pub fn has_errors(&self) -> bool {
406        self.items.iter().any(Diagnostic::is_error)
407    }
408
409    /// The diagnostics kept and the count of those dropped.
410    #[must_use]
411    pub fn into_parts(self) -> (Vec<Diagnostic>, usize) {
412        (self.items, self.dropped)
413    }
414}
415
416impl Extend<Diagnostic> for Collector {
417    fn extend<I: IntoIterator<Item = Diagnostic>>(&mut self, items: I) {
418        for item in items {
419            self.push(item);
420        }
421    }
422}