loftspec 2.0.2

The Loft Specification Format: document model, identity, canonical bytes, hashing and conversion
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! A record checked against its kind's schema: its fields known, none repeated, the required
//! ones present, each value of its field's shape and syntax, held in the Format's field order
//! (RQ-30, RQ-34). Formatting, reading and writing all pass through it.

use super::error::{Located, Problem};
use super::schema::{Field, Item, Kind, Scalar, Shape, field};
use crate::canonical::Digest;
use crate::identity::{Key, Label};
use crate::names::{CategoryName, TagName};
use crate::slug::Slug;
use crate::yaml::{self, Out, Position, Style, Value};

/// How strictly a record is read: every role but the formatter requires keys and slugs; the
/// formatter accepts their absence and supplies them (RQ-59, RQ-213).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Strict,
    Formatting,
}

/// A checked record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rec {
    pub kind: Kind,
    pub position: Position,
    /// The fields present, in the Format's order.
    pub fields: Vec<(&'static str, Val)>,
    /// The conflict records it holds, apart from its fields: only a record whose kind
    /// [`Kind::hosts_conflicts`] has any, and the writer puts them after every other field
    /// (AC-862).
    pub conflicts: Vec<ConflictRec>,
}

/// A conflict record (RQ-125): the path of the field it names, and each side's value in the
/// shape of that field; a side on which the field is absent has none (AC-859).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConflictRec {
    pub field: String,
    pub base: Option<Val>,
    pub ours: Option<Val>,
    pub theirs: Option<Val>,
}

impl ConflictRec {
    /// A conflict over the field at `field`, with its sides in the Format's order: base, ours,
    /// theirs.
    #[must_use]
    pub fn new(field: impl Into<String>, [base, ours, theirs]: [Option<Val>; 3]) -> Self {
        Self {
            field: field.into(),
            base,
            ours,
            theirs,
        }
    }

    /// The sides by name, in the Format's order: `base`, `ours`, `theirs` (AC-857).
    #[must_use]
    pub fn sides(&self) -> [(&'static str, Option<&Val>); 3] {
        [
            (field::BASE, self.base.as_ref()),
            (field::OURS, self.ours.as_ref()),
            (field::THEIRS, self.theirs.as_ref()),
        ]
    }

    /// The side named `name`, to set.
    pub fn side_mut(&mut self, name: &str) -> Option<&mut Option<Val>> {
        match name {
            field::BASE => Some(&mut self.base),
            field::OURS => Some(&mut self.ours),
            field::THEIRS => Some(&mut self.theirs),
            _ => None,
        }
    }
}

/// A checked field value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Val {
    Scalar {
        text: String,
        position: Position,
    },
    Record(Rec),
    List(Vec<Val>),
    /// YAML's plain `null`: the side of a conflict that deleted the record.
    Null {
        position: Position,
    },
}

impl Val {
    /// A scalar the writer or formatter supplies, with no position in a source file.
    #[must_use]
    pub fn scalar(text: &(impl std::fmt::Display + ?Sized)) -> Self {
        Self::Scalar {
            text: text.to_string(),
            position: Position::new(1, 1),
        }
    }

    /// The scalar's text.
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        match self {
            Self::Scalar { text, .. } => Some(text),
            _ => None,
        }
    }

    /// The records the value holds: itself, or a list's records.
    pub fn records(&self) -> impl Iterator<Item = &Rec> {
        let items: &[Self] = match self {
            Self::List(items) => items,
            other => std::slice::from_ref(other),
        };
        items.iter().filter_map(|item| match item {
            Self::Record(record) => Some(record),
            _ => None,
        })
    }

    /// The records the value holds, to change.
    pub fn records_mut(&mut self) -> impl Iterator<Item = &mut Rec> {
        let items: &mut [Self] = match self {
            Self::List(items) => items,
            other => std::slice::from_mut(other),
        };
        items.iter_mut().filter_map(|item| match item {
            Self::Record(record) => Some(record),
            _ => None,
        })
    }

    #[must_use]
    pub const fn position(&self) -> Option<Position> {
        match self {
            Self::Scalar { position, .. } | Self::Null { position } => Some(*position),
            Self::Record(record) => Some(record.position),
            Self::List(_) => None,
        }
    }
}

impl Rec {
    #[must_use]
    pub fn new(kind: Kind) -> Self {
        Self {
            kind,
            position: Position::new(1, 1),
            fields: Vec::new(),
            conflicts: Vec::new(),
        }
    }

    /// A field's value. Naming a field the kind does not define is a programming error.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&Val> {
        debug_assert!(
            self.kind.field(name).is_some(),
            "{:?} has no field {name}",
            self.kind
        );
        self.fields
            .iter()
            .find(|(field, _)| *field == name)
            .map(|(_, value)| value)
    }

    /// A field's value, to change.
    pub fn get_mut(&mut self, name: &str) -> Option<&mut Val> {
        debug_assert!(
            self.kind.field(name).is_some(),
            "{:?} has no field {name}",
            self.kind
        );
        self.fields
            .iter_mut()
            .find(|(field, _)| *field == name)
            .map(|(_, value)| value)
    }

    #[must_use]
    pub fn text(&self, name: &str) -> Option<&str> {
        self.get(name).and_then(Val::text)
    }

    #[must_use]
    pub fn record(&self, name: &str) -> Option<&Self> {
        match self.get(name) {
            Some(Val::Record(record)) => Some(record),
            _ => None,
        }
    }

    /// The entries of a list field; none when the field is absent (AC-799).
    #[must_use]
    pub fn list(&self, name: &str) -> &[Val] {
        match self.get(name) {
            Some(Val::List(items)) => items,
            _ => &[],
        }
    }

    /// The records of a list field.
    pub fn records(&self, name: &str) -> impl Iterator<Item = &Self> {
        self.list(name).iter().flat_map(Val::records)
    }

    /// The records inside this record's fields.
    pub fn children(&self) -> impl Iterator<Item = &Self> {
        self.fields.iter().flat_map(|(_, value)| value.records())
    }

    /// The records inside this record's fields, to change.
    pub fn children_mut(&mut self) -> impl Iterator<Item = &mut Self> {
        self.fields
            .iter_mut()
            .flat_map(|(_, value)| value.records_mut())
    }

    /// The entries of a list field, to change; an absent field is added empty.
    pub fn list_mut(&mut self, name: &'static str) -> &mut Vec<Val> {
        if self.get(name).is_none() {
            self.set(name, Val::List(Vec::new()));
        }
        match self.get_mut(name) {
            Some(Val::List(items)) => items,
            _ => unreachable!("{name} is a list field"),
        }
    }

    /// Sets a field, keeping the Format's order.
    pub fn set(&mut self, name: &'static str, value: Val) {
        let place = |field: &str| {
            self.kind
                .field(field)
                .expect("a field the schema defines")
                .0
        };
        let at = place(name);
        match self.fields.iter().position(|(field, _)| place(field) >= at) {
            Some(index) if self.fields[index].0 == name => self.fields[index].1 = value,
            Some(index) => self.fields.insert(index, (name, value)),
            None => self.fields.push((name, value)),
        }
    }

    /// Sets a scalar field.
    pub fn set_text(&mut self, name: &'static str, text: impl Into<String>) {
        let position = self.position;
        self.set(
            name,
            Val::Scalar {
                text: text.into(),
                position,
            },
        );
    }
}

/// Checks a node as a record of `kind`.
pub(crate) fn check(node: &yaml::Node, kind: Kind, mode: Mode) -> Result<Rec, Located> {
    let Value::Mapping(entries) = &node.value else {
        return Err(located(
            node.position,
            Problem::Expected("a mapping of fields"),
        ));
    };
    let mut record = Rec {
        kind,
        position: node.position,
        fields: Vec::with_capacity(entries.len()),
        conflicts: Vec::new(),
    };
    for entry in entries {
        if entry.key == field::CONFLICTS && kind.hosts_conflicts() {
            record.conflicts = super::conflict::check_conflicts(&entry.value, kind, mode)?;
            continue;
        }
        let Some((_, field)) = kind.field(&entry.key) else {
            return Err(located(
                entry.key_position,
                Problem::UnknownField(entry.key.clone()),
            ));
        };
        let value = check_shape(&entry.value, field.shape, mode)?;
        record.fields.push((field.name, value));
    }
    for field in kind.fields() {
        if field.required && record.get(field.name).is_none() && !may_lack(field, mode) {
            return Err(located(node.position, Problem::MissingField(field.name)));
        }
    }
    record
        .fields
        .sort_by_cached_key(|(name, _)| kind.field(name).map(|(at, _)| at));
    super::variants::check(&record)?;
    Ok(record)
}

/// Whether a required field may be missing in this mode: one the formatter supplies.
fn may_lack(field: &Field, mode: Mode) -> bool {
    mode == Mode::Formatting && field.supply.is_some()
}

fn located(position: Position, problem: Problem) -> Located {
    Located { position, problem }
}

pub(super) fn check_shape(node: &yaml::Node, shape: Shape, mode: Mode) -> Result<Val, Located> {
    match shape {
        Shape::One(item) => check_item(node, item, mode),
        Shape::List(item) => match &node.value {
            Value::Sequence(items) => items
                .iter()
                .map(|item_node| check_item(item_node, item, mode))
                .collect::<Result<_, _>>()
                .map(Val::List),
            Value::Empty => Ok(Val::List(Vec::new())),
            _ => Err(located(node.position, Problem::Expected("a list"))),
        },
    }
}

fn check_item(node: &yaml::Node, item: Item, mode: Mode) -> Result<Val, Located> {
    match item {
        Item::Scalar(Scalar::Ref(_)) | Item::NodeRef if written_by_name(node) => match mode {
            Mode::Formatting => check(node, Kind::ByName, mode).map(Val::Record),
            Mode::Strict => Err(located(node.position, Problem::ByName)),
        },
        Item::Scalar(scalar) => check_scalar(node, scalar),
        Item::Record(kind) => check(node, kind, mode).map(Val::Record),
        Item::NodeRef => match &node.value {
            Value::Mapping(_) => check(node, Kind::FormerLabel, mode).map(Val::Record),
            _ => check_scalar(node, Scalar::Key),
        },
    }
}

/// Whether a reference is written as a record naming its target.
fn written_by_name(node: &yaml::Node) -> bool {
    matches!(&node.value, Value::Mapping(entries) if entries.iter().any(|entry| entry.key == field::NAME))
}

pub(super) fn check_scalar(node: &yaml::Node, scalar: Scalar) -> Result<Val, Located> {
    let Value::Scalar(value) = &node.value else {
        return Err(located(node.position, Problem::Expected(describe(scalar))));
    };
    let text = &value.text;
    let single_line = value.style != Style::Literal;
    let valid = match scalar {
        Scalar::Text => true,
        Scalar::Key | Scalar::Ref(_) => single_line && Key::parse(text).is_ok(),
        Scalar::Label => single_line && Label::parse(text).is_ok(),
        Scalar::Slug => single_line && Slug::parse(text).is_ok(),
        Scalar::Tag => single_line && TagName::parse(text).is_ok(),
        Scalar::Category => single_line && CategoryName::parse(text).is_ok(),
        Scalar::Digest => single_line && text.parse::<Digest>().is_ok(),
        Scalar::Integer => {
            value.style == Style::Plain
                && text.parse::<u64>().is_ok_and(|number| number > 0)
                && !text.starts_with('0')
        }
        Scalar::Enum(values) => single_line && values.contains(&text.as_str()),
        Scalar::Identifier => single_line && !text.is_empty() && !text.contains('\n'),
    };
    if !valid {
        return Err(located(
            node.position,
            Problem::Invalid {
                value: text.clone(),
                expected: describe(scalar),
            },
        ));
    }
    Ok(Val::Scalar {
        text: text.clone(),
        position: node.position,
    })
}

const fn describe(scalar: Scalar) -> &'static str {
    match scalar {
        Scalar::Key | Scalar::Ref(_) => "a lowercase hyphenated UUID",
        Scalar::Label => "a label",
        Scalar::Slug => "a slug",
        Scalar::Tag => "a tag name",
        Scalar::Category => "a category name",
        Scalar::Digest => "a SHA-256 digest in lowercase hexadecimal",
        Scalar::Integer => "a positive integer",
        Scalar::Enum(_) => "a value the field defines",
        Scalar::Identifier => "an identifier",
        Scalar::Text => "text",
    }
}

/// The record as the writer lays it out: its fields in order, an empty list left out
/// (AC-798), each scalar in the style its shape gives, then its conflicts (AC-862).
#[must_use]
pub fn to_out(record: &Rec) -> Out {
    let mut fields: Vec<_> = record
        .fields
        .iter()
        .filter(|(_, value)| !matches!(value, Val::List(items) if items.is_empty()))
        .map(|(name, value)| {
            let (_, field) = record.kind.field(name).expect("a field the schema defines");
            (field.name, value_out(value, field.shape))
        })
        .collect();
    if !record.conflicts.is_empty() {
        let conflicts = super::conflict::conflicts_out(&record.conflicts, record.kind);
        fields.push((field::CONFLICTS, conflicts));
    }
    Out::Mapping(fields)
}

pub(super) fn value_out(value: &Val, shape: Shape) -> Out {
    match (shape, value) {
        (Shape::List(item), Val::List(items)) => {
            Out::Sequence(items.iter().map(|entry| item_out(entry, item)).collect())
        }
        (Shape::One(item), _) => item_out(value, item),
        (Shape::List(_), _) => unreachable!("a checked list"),
    }
}

fn item_out(value: &Val, item: Item) -> Out {
    match value {
        Val::Record(record) => to_out(record),
        Val::Scalar { text, .. } => match item {
            Item::Scalar(Scalar::Text) => Out::Text(text.clone()),
            Item::Scalar(Scalar::Integer) => Out::Integer(text.parse().expect("a checked integer")),
            _ => Out::Token(text.clone()),
        },
        Val::Null { .. } => Out::Null,
        Val::List(_) => unreachable!("lists do not nest"),
    }
}