alpha2-diagnose 0.10.0

Format-neutral document diagnostics for alpha2: a document tree, a JSON reader that recovers, a schema walker, advice and fixes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! One problem found in a document, and what can be done about it.

use serde::{Deserialize, Serialize};

use crate::path::Path;
use crate::tree::{Node, Span};

/// How serious a diagnostic is. Ordered from most to least serious.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Severity {
    /// The engine refuses the document.
    Error,
    /// The engine accepts the document, but it is likely not what was meant.
    Warning,
    /// Information that helps the next step.
    Hint,
}

impl Severity {
    /// The lower-case name, as serialized.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warning => "warning",
            Self::Hint => "hint",
        }
    }
}

/// A kind of diagnostic: its stable name, severity, level and one sentence. Codes are the
/// contract a consumer switches on; messages are not.
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct Code {
    /// `layer.name`, such as `shape.unknown_field`.
    pub name: &'static str,
    /// The severity of every diagnostic of this code.
    pub severity: Severity,
    /// 1 for a fact the rules state, 2 for a heuristic, 3 for a reviewer's finding.
    pub level: u8,
    /// What the code means, in one sentence.
    pub summary: &'static str,
}

impl Code {
    /// The layer: the part of the name before the first `.`.
    #[must_use]
    pub fn layer(&self) -> &'static str {
        self.name.split('.').next().unwrap_or(self.name)
    }
}

/// The prefix of the codes a reviewer outside the engine uses for its findings.
pub const REVIEW_PREFIX: &str = "review.";

/// Whether a fix may be applied by a program without asking.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Applicability {
    /// The document's meaning cannot change: a syntax recovery, an integer's spelling, a key
    /// spelt another way. The engine applies these when asked.
    Certain,
    /// Probably right, never applied by the engine.
    Likely,
}

/// One change to a document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Edit {
    /// Replaces bytes of the text the document was read from; the reader's fixes only.
    Text {
        /// Byte offset in the text.
        offset: usize,
        /// Bytes replaced.
        length: usize,
        /// What goes in their place.
        replacement: String,
    },
    /// Replaces the value at `path`.
    Replace {
        /// The value replaced.
        path: Path,
        /// The new value.
        value: Node,
    },
    /// Renames the key that ends `path`, keeping its value and place.
    RenameKey {
        /// The entry renamed.
        path: Path,
        /// The new key.
        to: String,
    },
    /// Removes the entry or item at `path`.
    Remove {
        /// What is removed.
        path: Path,
    },
    /// Adds `value` at `path`: a new key of an object, or an index of an array, the items from
    /// it on moved one up.
    Insert {
        /// Where the value goes; its parent exists.
        path: Path,
        /// The value.
        value: Node,
    },
    /// Moves the value at `from` to `to`, whose parent exists and which is not taken.
    Move {
        /// The value moved.
        from: Path,
        /// Where it goes.
        to: Path,
    },
}

impl Edit {
    /// The path an edit changes first; `None` for a text edit.
    #[must_use]
    pub const fn path(&self) -> Option<&Path> {
        match self {
            Self::Text { .. } => None,
            Self::Replace { path, .. }
            | Self::RenameKey { path, .. }
            | Self::Remove { path }
            | Self::Insert { path, .. } => Some(path),
            Self::Move { from, .. } => Some(from),
        }
    }
}

/// A way to fix a diagnostic: edits applied together.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Fix {
    /// What the fix does, in a few words.
    pub title: String,
    /// Whether a program may apply it without asking.
    pub applicability: Applicability,
    /// The edits, applied together.
    pub edits: Vec<Edit>,
}

impl Fix {
    /// A fix that cannot change what the document means.
    #[must_use]
    pub fn certain(title: impl Into<String>, edits: Vec<Edit>) -> Self {
        Self {
            title: title.into(),
            applicability: Applicability::Certain,
            edits,
        }
    }

    /// A fix that is probably right.
    #[must_use]
    pub fn likely(title: impl Into<String>, edits: Vec<Edit>) -> Self {
        Self {
            title: title.into(),
            applicability: Applicability::Likely,
            edits,
        }
    }
}

/// A section of the schema reference: a topic and a definition, as
/// `schema/reference/index.json` names them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Reference {
    /// `project`, `compose`, `effects`, ...
    pub topic: String,
    /// The definition's name.
    pub definition: String,
}

/// One problem in a document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Diagnostic {
    /// The code, `layer.name`.
    pub code: String,
    /// How serious it is.
    pub severity: Severity,
    /// 1 for a fact, 2 for a heuristic, 3 for a reviewer's finding.
    pub level: u8,
    /// Where in the document. It names a value that exists in the document read.
    pub path: Path,
    /// Where in the text; absent for a document without text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<Span>,
    /// What is wrong, in one sentence.
    pub message: String,
    /// What to do about it; a guess says so.
    #[serde(default)]
    pub help: Vec<String>,
    /// Changes that fix it.
    #[serde(default)]
    pub fixes: Vec<Fix>,
    /// The section of the schema reference about the value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reference: Option<Reference>,
    /// The object it is about, by id: `{"type": "clip", "clip": "clip-1"}`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject: Option<Node>,
    /// How many places have this problem; the others are in `also`.
    #[serde(default = "one")]
    pub count: usize,
    /// Up to three other places with the same problem.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub also: Vec<Path>,
    /// Fields the code defines: what was found, a limit, the parts of a lint issue.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<Node>,
    /// Who found it, when not the engine: a host's or a reviewer's name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
    /// The text of the value it is about, when asked for; at most 400 bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub excerpt: Option<String>,
}

const fn one() -> usize {
    1
}

impl Diagnostic {
    /// A diagnostic of one of the engine's codes.
    #[must_use]
    pub fn new(code: &'static Code, path: Path, message: impl Into<String>) -> Self {
        Self::external(code.name, code.severity, code.level, path, message)
    }

    /// A diagnostic of a code outside the engine's tables, such as a reviewer's `review.*`
    /// finding; give it an [`origin`](Self::origin).
    #[must_use]
    pub fn external(
        code: impl Into<String>,
        severity: Severity,
        level: u8,
        path: Path,
        message: impl Into<String>,
    ) -> Self {
        Self {
            code: code.into(),
            severity,
            level,
            path,
            span: None,
            message: message.into(),
            help: Vec::new(),
            fixes: Vec::new(),
            reference: None,
            subject: None,
            count: 1,
            also: Vec::new(),
            data: None,
            origin: None,
            excerpt: None,
        }
    }

    /// Sets the place in the text.
    #[must_use]
    pub const fn at(mut self, span: Option<Span>) -> Self {
        self.span = span;
        self
    }

    /// Adds a help line.
    #[must_use]
    pub fn help(mut self, line: impl Into<String>) -> Self {
        self.help.push(line.into());
        self
    }

    /// Adds a fix.
    #[must_use]
    pub fn fix(mut self, fix: Fix) -> Self {
        self.fixes.push(fix);
        self
    }

    /// Sets the reference section.
    #[must_use]
    pub fn reference(mut self, topic: impl Into<String>, definition: impl Into<String>) -> Self {
        self.reference = Some(Reference {
            topic: topic.into(),
            definition: definition.into(),
        });
        self
    }

    /// Sets the object it is about.
    #[must_use]
    pub fn subject(mut self, subject: Node) -> Self {
        self.subject = Some(subject);
        self
    }

    /// Sets the code's fields.
    #[must_use]
    pub fn data(mut self, data: Node) -> Self {
        self.data = Some(data);
        self
    }

    /// Sets who found it.
    #[must_use]
    pub fn origin(mut self, origin: impl Into<String>) -> Self {
        self.origin = Some(origin.into());
        self
    }

    /// Whether the code is `code`.
    #[must_use]
    pub fn is(&self, code: &Code) -> bool {
        self.code == code.name
    }

    /// Whether it is an error.
    #[must_use]
    pub fn is_error(&self) -> bool {
        self.severity == Severity::Error
    }

    /// A field of [`data`](Self::data).
    #[must_use]
    pub fn datum(&self, key: &str) -> Option<&Node> {
        self.data.as_ref()?.get(key)
    }

    /// Whether some help line or fix already exists.
    #[must_use]
    pub fn has_advice(&self) -> bool {
        !self.help.is_empty() || !self.fixes.is_empty()
    }
}

/// Collects diagnostics up to a capacity and counts the ones past it.
#[derive(Clone, Debug)]
pub struct Collector {
    items: Vec<Diagnostic>,
    dropped: usize,
    capacity: usize,
}

impl Default for Collector {
    fn default() -> Self {
        Self::new(Self::DEFAULT_CAPACITY)
    }
}

impl Collector {
    /// The most diagnostics collected for one document by default.
    pub const DEFAULT_CAPACITY: usize = 1000;

    /// A collector that keeps at most `capacity` diagnostics.
    #[must_use]
    pub const fn new(capacity: usize) -> Self {
        Self {
            items: Vec::new(),
            dropped: 0,
            capacity,
        }
    }

    /// Adds a diagnostic, or counts it when full.
    pub fn push(&mut self, diagnostic: Diagnostic) {
        if self.items.len() < self.capacity {
            self.items.push(diagnostic);
        } else {
            self.dropped += 1;
        }
    }

    /// Whether no more diagnostics are kept.
    #[must_use]
    pub const fn is_full(&self) -> bool {
        self.items.len() >= self.capacity
    }

    /// The diagnostics kept.
    #[must_use]
    pub fn items(&self) -> &[Diagnostic] {
        &self.items
    }

    /// The diagnostics kept, for change.
    pub fn items_mut(&mut self) -> &mut [Diagnostic] {
        &mut self.items
    }

    /// How many were not kept.
    #[must_use]
    pub const fn dropped(&self) -> usize {
        self.dropped
    }

    /// Whether an error was kept.
    #[must_use]
    pub fn has_errors(&self) -> bool {
        self.items.iter().any(Diagnostic::is_error)
    }

    /// The diagnostics kept and the count of those dropped.
    #[must_use]
    pub fn into_parts(self) -> (Vec<Diagnostic>, usize) {
        (self.items, self.dropped)
    }
}

impl Extend<Diagnostic> for Collector {
    fn extend<I: IntoIterator<Item = Diagnostic>>(&mut self, items: I) {
        for item in items {
            self.push(item);
        }
    }
}