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
423
424
425
//! Paths into a document: `project.timeline.tracks[0].clips[2].visual`.

use std::fmt::{self, Write as _};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// One step of a path.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Segment {
    /// A key of an object.
    Key(String),
    /// An index of an array.
    Index(usize),
}

/// A place in a document: a root name the document kind gives, then keys and indexes.
///
/// Written as `root.key[2].other`; a key that is empty or holds `.`, `[`, `]`, `"`, `\`,
/// whitespace or a control character is written quoted, `root["a key"]`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Path {
    root: String,
    segments: Vec<Segment>,
}

/// Why a path could not be read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PathError {
    /// The byte offset in the path text.
    pub offset: usize,
    /// What was wrong there.
    pub message: &'static str,
}

impl fmt::Display for PathError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{} at byte {}", self.message, self.offset)
    }
}

impl std::error::Error for PathError {}

impl Path {
    /// The root of a document.
    #[must_use]
    pub fn root(name: impl Into<String>) -> Self {
        Self {
            root: name.into(),
            segments: Vec::new(),
        }
    }

    /// The path one key further.
    #[must_use]
    pub fn key(&self, key: impl Into<String>) -> Self {
        let mut path = self.clone();
        path.segments.push(Segment::Key(key.into()));
        path
    }

    /// The path one index further.
    #[must_use]
    pub fn index(&self, index: usize) -> Self {
        let mut path = self.clone();
        path.segments.push(Segment::Index(index));
        path
    }

    /// Adds a segment.
    pub fn push(&mut self, segment: Segment) {
        self.segments.push(segment);
    }

    /// Removes and answers the last segment.
    pub fn pop(&mut self) -> Option<Segment> {
        self.segments.pop()
    }

    /// The path with `segments` added.
    #[must_use]
    pub fn join(&self, segments: impl IntoIterator<Item = Segment>) -> Self {
        let mut path = self.clone();
        path.segments.extend(segments);
        path
    }

    /// The root name.
    #[must_use]
    pub fn root_name(&self) -> &str {
        &self.root
    }

    /// The keys and indexes after the root.
    #[must_use]
    pub fn segments(&self) -> &[Segment] {
        &self.segments
    }

    /// The last segment.
    #[must_use]
    pub fn last(&self) -> Option<&Segment> {
        self.segments.last()
    }

    /// The last segment when it is a key.
    #[must_use]
    pub fn last_key(&self) -> Option<&str> {
        match self.segments.last() {
            Some(Segment::Key(key)) => Some(key),
            _ => None,
        }
    }

    /// The path one step up, or `None` at the root.
    #[must_use]
    pub fn parent(&self) -> Option<Self> {
        let mut path = self.clone();
        path.segments.pop().map(|_| path)
    }

    /// Whether `self` is `other` or lies inside it (roots compared too).
    #[must_use]
    pub fn starts_with(&self, other: &Self) -> bool {
        self.root == other.root && self.segments.starts_with(&other.segments)
    }

    /// The written form with every index replaced by `*`, which groups one problem repeated
    /// over a list.
    #[must_use]
    pub fn starred(&self) -> String {
        let mut text = self.root.clone();
        for segment in &self.segments {
            match segment {
                Segment::Key(key) => write_key(&mut text, key),
                Segment::Index(_) => text.push_str("[*]"),
            }
        }
        text
    }

    /// Reads a written path. The first name is the root; `spec.body.children[2].path`,
    /// `project["a key"][0]`.
    ///
    /// # Errors
    /// [`PathError`] with the offset of the first character that does not fit.
    pub fn parse(text: &str) -> Result<Self, PathError> {
        let bytes = text.as_bytes();
        let mut at = 0;
        let root = read_name(text, &mut at);
        if root.is_empty() {
            return Err(PathError {
                offset: 0,
                message: "a path starts with a name",
            });
        }
        let mut path = Self::root(root);
        path.segments = read_segments(text, bytes, &mut at)?;
        Ok(path)
    }

    /// The path with a relative written path added: `visual.opacity`, `[2].value` or
    /// `.visual`. An empty text or `.` adds nothing.
    ///
    /// # Errors
    /// [`PathError`] with the offset in `relative`.
    pub fn join_text(&self, relative: &str) -> Result<Self, PathError> {
        if relative.is_empty() || relative == "." {
            return Ok(self.clone());
        }
        let bytes = relative.as_bytes();
        let mut at = 0;
        let mut path = self.clone();
        if !matches!(bytes[0], b'.' | b'[') {
            let first = read_name(relative, &mut at);
            if first.is_empty() {
                return Err(PathError {
                    offset: 0,
                    message: "expected a key",
                });
            }
            path.segments.push(Segment::Key(first.to_owned()));
        }
        path.segments
            .extend(read_segments(relative, bytes, &mut at)?);
        Ok(path)
    }
}

fn read_name<'a>(text: &'a str, at: &mut usize) -> &'a str {
    let start = *at;
    let bytes = text.as_bytes();
    while *at < bytes.len() && !matches!(bytes[*at], b'.' | b'[' | b']') {
        *at += 1;
    }
    &text[start..*at]
}

fn read_segments(text: &str, bytes: &[u8], at: &mut usize) -> Result<Vec<Segment>, PathError> {
    let mut segments = Vec::new();
    while *at < bytes.len() {
        match bytes[*at] {
            b'.' => {
                *at += 1;
                let key = read_name(text, at);
                if key.is_empty() {
                    return Err(PathError {
                        offset: *at,
                        message: "expected a key after `.`",
                    });
                }
                segments.push(Segment::Key(key.to_owned()));
            }
            b'[' => {
                *at += 1;
                if bytes.get(*at) == Some(&b'"') {
                    let (key, end) = read_quoted(text, *at)?;
                    *at = end;
                    segments.push(Segment::Key(key));
                } else {
                    let start = *at;
                    while bytes.get(*at).is_some_and(u8::is_ascii_digit) {
                        *at += 1;
                    }
                    let index = text[start..*at].parse().map_err(|_| PathError {
                        offset: start,
                        message: "expected an index or a quoted key",
                    })?;
                    segments.push(Segment::Index(index));
                }
                if bytes.get(*at) != Some(&b']') {
                    return Err(PathError {
                        offset: *at,
                        message: "expected `]`",
                    });
                }
                *at += 1;
            }
            _ => {
                return Err(PathError {
                    offset: *at,
                    message: "expected `.` or `[`",
                });
            }
        }
    }
    Ok(segments)
}

fn read_quoted(text: &str, start: usize) -> Result<(String, usize), PathError> {
    let mut key = String::new();
    let mut chars = text[start + 1..].char_indices();
    while let Some((offset, char)) = chars.next() {
        match char {
            '"' => return Ok((key, start + 1 + offset + 1)),
            '\\' => match chars.next() {
                Some((_, '"')) => key.push('"'),
                Some((_, '\\')) => key.push('\\'),
                Some((_, 'n')) => key.push('\n'),
                Some((_, 't')) => key.push('\t'),
                Some((_, 'r')) => key.push('\r'),
                Some((offset, 'u')) => {
                    let begin = start + 1 + offset + 1;
                    let code = text
                        .get(begin..begin + 4)
                        .and_then(|hex| u32::from_str_radix(hex, 16).ok())
                        .and_then(char::from_u32)
                        .ok_or(PathError {
                            offset: begin,
                            message: "expected four hex digits",
                        })?;
                    key.push(code);
                    for _ in 0..4 {
                        chars.next();
                    }
                }
                _ => {
                    return Err(PathError {
                        offset: start + 1 + offset,
                        message: "unknown escape",
                    });
                }
            },
            other => key.push(other),
        }
    }
    Err(PathError {
        offset: text.len(),
        message: "unterminated quoted key",
    })
}

fn plain_key(key: &str) -> bool {
    !key.is_empty()
        && !key.chars().any(|char| {
            matches!(char, '.' | '[' | ']' | '"' | '\\')
                || char.is_whitespace()
                || char.is_control()
        })
}

fn write_key(text: &mut String, key: &str) {
    if plain_key(key) {
        text.push('.');
        text.push_str(key);
        return;
    }
    text.push_str("[\"");
    for char in key.chars() {
        match char {
            '"' => text.push_str("\\\""),
            '\\' => text.push_str("\\\\"),
            '\n' => text.push_str("\\n"),
            '\t' => text.push_str("\\t"),
            '\r' => text.push_str("\\r"),
            char if char.is_control() => {
                let _ = write!(text, "\\u{:04x}", u32::from(char));
            }
            char => text.push(char),
        }
    }
    text.push_str("\"]");
}

impl fmt::Display for Path {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut text = self.root.clone();
        for segment in &self.segments {
            match segment {
                Segment::Key(key) => write_key(&mut text, key),
                Segment::Index(index) => {
                    let _ = write!(text, "[{index}]");
                }
            }
        }
        formatter.write_str(&text)
    }
}

impl Serialize for Path {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Path {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        Self::parse(&text).map_err(serde::de::Error::custom)
    }
}

#[cfg(feature = "schema")]
impl schemars::JsonSchema for Path {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Path".into()
    }

    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "description": "A place in the document: a root name, then `.key`, `[\"quoted key\"]` and `[index]` steps.",
            "type": "string"
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn writes_and_reads_back() {
        let path = Path::root("project")
            .key("timeline")
            .key("tracks")
            .index(0)
            .key("a key")
            .key("q\"uote");
        let text = path.to_string();
        assert_eq!(text, r#"project.timeline.tracks[0]["a key"]["q\"uote"]"#);
        assert_eq!(Path::parse(&text).unwrap(), path);
    }

    #[test]
    fn reads_the_forms_the_engine_writes() {
        let path = Path::parse("spec.body.children[2].path").unwrap();
        assert_eq!(path.root_name(), "spec");
        assert_eq!(path.segments().len(), 4);
        let base = Path::root("project").key("clips").index(1);
        assert_eq!(
            base.join_text("visual.opacity").unwrap().to_string(),
            "project.clips[1].visual.opacity"
        );
        assert_eq!(
            base.join_text("masks[0].feather").unwrap().to_string(),
            "project.clips[1].masks[0].feather"
        );
        assert_eq!(
            base.join_text("[3]").unwrap().to_string(),
            "project.clips[1][3]"
        );
        assert_eq!(base.join_text(".").unwrap(), base);
    }

    #[test]
    fn refuses_malformed_paths() {
        for bad in ["", ".a", "a..b", "a[x]", "a[1", "a[\"b]", "a]"] {
            assert!(Path::parse(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn starred_replaces_indexes() {
        let path = Path::parse("project.tracks[3].clips[12].id").unwrap();
        assert_eq!(path.starred(), "project.tracks[*].clips[*].id");
    }

    #[test]
    fn parent_and_prefix() {
        let path = Path::parse("a.b[1]").unwrap();
        assert_eq!(path.parent().unwrap().to_string(), "a.b");
        assert!(path.starts_with(&Path::parse("a.b").unwrap()));
        assert!(!path.starts_with(&Path::parse("x.b").unwrap()));
        assert!(Path::root("a").parent().is_none());
    }
}