scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
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
//! The file as a tree: maps, lists and scalars, each with its place (SPEC 4.12). One arena holds
//! a file and the files it extends, so a patch moves nodes by relinking them.

use scrusted_feel::Value;
use std::sync::Arc;

use crate::problem::Place;

/// A node in the arena.
pub type NodeId = usize;
/// An entry (`key: value`) in the arena.
pub type EntryId = usize;

/// Where something was written.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Pos {
    /// The file.
    pub file: Arc<str>,
    /// 1-based; 0 for data.
    pub line: u32,
    /// 1-based.
    pub column: u32,
}

/// A key as written, split at its last `!` into a name and a marker (SPEC 4.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Key {
    /// As written: `run!sh`.
    pub raw: Arc<str>,
    /// Before the `!`: `run`.
    pub name: Arc<str>,
    /// None: plain. Some(""): a formula. Some("sh"): the marker `sh`.
    pub marker: Option<Arc<str>>,
}

/// What a key is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyKind {
    /// `key:`
    Plain,
    /// `key!:`
    Formula,
    /// `key!name:`
    Marked,
}

impl Key {
    /// Splits a key at its last `!`.
    pub fn new(raw: &str) -> Key {
        match raw.rfind('!') {
            Some(at) => Key { raw: raw.into(), name: raw[..at].into(), marker: Some(raw[at + 1..].into()) },
            None => Key { raw: raw.into(), name: raw.into(), marker: None },
        }
    }

    /// Plain, formula or marked.
    pub fn kind(&self) -> KeyKind {
        match self.marker.as_deref() {
            None => KeyKind::Plain,
            Some("") => KeyKind::Formula,
            Some(_) => KeyKind::Marked,
        }
    }

    /// True for `$` keys.
    pub fn keyword(&self) -> bool {
        self.name.starts_with('$')
    }

    /// The marker name of a marked key.
    pub fn marker_name(&self) -> &str {
        self.marker.as_deref().unwrap_or("")
    }
}

/// A scalar: its value, and its text as written.
#[derive(Debug, Clone)]
pub struct Scalar {
    /// The value YAML gives it.
    pub value: Value,
    /// The text as written; for a string, the string.
    pub source: Arc<str>,
}

/// What a node holds.
#[derive(Debug, Clone)]
pub enum NodeKind {
    /// A scalar.
    Scalar(Scalar),
    /// A map: its entries in order.
    Map(Vec<EntryId>),
    /// A list: its items in order.
    List(Vec<NodeId>),
}

/// One node.
#[derive(Debug, Clone)]
pub struct Node {
    /// What it holds.
    pub kind: NodeKind,
    /// Where.
    pub pos: Pos,
    /// The map or list that holds it.
    pub parent: Option<NodeId>,
    /// The entry it is the value of.
    pub entry: Option<EntryId>,
    /// For a list: the field that names an item (`id`, or the schema's `key`).
    pub key_field: Arc<str>,
}

/// One `key: value` of a map.
#[derive(Debug, Clone)]
pub struct Entry {
    /// The key.
    pub key: Key,
    /// The value.
    pub value: NodeId,
    /// The map it belongs to.
    pub map: NodeId,
    /// Where the key was written.
    pub pos: Pos,
    /// In a patch, the entry this one replaced: `base` in its formulas.
    pub base: Option<EntryId>,
    /// False for an entry that is only a base, not in its map.
    pub listed: bool,
}

/// The arena.
#[derive(Debug, Clone, Default)]
pub struct Tree {
    /// Every node.
    pub nodes: Vec<Node>,
    /// Every entry.
    pub entries: Vec<Entry>,
}

/// The text of a scalar value as JavaScript's `String(v)` gives it.
pub fn js_string(v: &Value) -> String {
    match v {
        Value::Null => "null".into(),
        other => other.to_feel_string(),
    }
}

impl Tree {
    /// A new node.
    pub fn add(&mut self, kind: NodeKind, pos: Pos) -> NodeId {
        self.nodes.push(Node { kind, pos, parent: None, entry: None, key_field: "id".into() });
        self.nodes.len() - 1
    }

    /// A new scalar node.
    pub fn scalar(&mut self, value: Value, source: impl Into<Arc<str>>, pos: Pos) -> NodeId {
        self.add(NodeKind::Scalar(Scalar { value, source: source.into() }), pos)
    }

    /// A new empty map.
    pub fn map(&mut self, pos: Pos) -> NodeId {
        self.add(NodeKind::Map(Vec::new()), pos)
    }

    /// A new empty list.
    pub fn list(&mut self, pos: Pos) -> NodeId {
        self.add(NodeKind::List(Vec::new()), pos)
    }

    /// The node.
    pub fn node(&self, id: NodeId) -> &Node {
        &self.nodes[id]
    }

    /// The entry.
    pub fn entry(&self, id: EntryId) -> &Entry {
        &self.entries[id]
    }

    /// The entries of a map; empty for anything else.
    pub fn entries_of(&self, map: NodeId) -> &[EntryId] {
        match &self.nodes[map].kind {
            NodeKind::Map(e) => e,
            _ => &[],
        }
    }

    /// The items of a list; empty for anything else.
    pub fn items(&self, list: NodeId) -> &[NodeId] {
        match &self.nodes[list].kind {
            NodeKind::List(i) => i,
            _ => &[],
        }
    }

    /// True for a map.
    pub fn is_map(&self, id: NodeId) -> bool {
        matches!(self.nodes[id].kind, NodeKind::Map(_))
    }

    /// True for a list.
    pub fn is_list(&self, id: NodeId) -> bool {
        matches!(self.nodes[id].kind, NodeKind::List(_))
    }

    /// The scalar of a node.
    pub fn scalar_of(&self, id: NodeId) -> Option<&Scalar> {
        match &self.nodes[id].kind {
            NodeKind::Scalar(s) => Some(s),
            _ => None,
        }
    }

    /// The entry of a map with this name, whatever its marker.
    pub fn get(&self, map: NodeId, name: &str) -> Option<EntryId> {
        self.entries_of(map).iter().copied().find(|e| &*self.entries[*e].key.name == name)
    }

    /// The cases of a map's `$when`.
    pub fn cases(&self, map: NodeId) -> Vec<NodeId> {
        match self.get(map, "$when") {
            Some(when) => self.items(self.entries[when].value).iter().copied().filter(|i| self.is_map(*i)).collect(),
            None => Vec::new(),
        }
    }

    /// Like `get`, and also a key that only a `$when` case adds.
    pub fn find(&self, map: NodeId, name: &str) -> Option<EntryId> {
        if let Some(own) = self.get(map, name) {
            return Some(own);
        }
        self.cases(map).into_iter().find_map(|case| self.get(case, name))
    }

    /// A plain scalar value of a map, such as its `id`.
    pub fn scalar_field(&self, map: NodeId, name: &str) -> Option<&Value> {
        let e = self.get(map, name)?;
        let entry = &self.entries[e];
        if entry.key.kind() != KeyKind::Plain {
            return None;
        }
        self.scalar_of(entry.value).map(|s| &s.value)
    }

    /// Adds an entry to a map, at the end or at a position.
    pub fn set(&mut self, map: NodeId, raw: &str, value: NodeId, pos: Pos, at: Option<usize>) -> EntryId {
        let entry = Entry { key: Key::new(raw), value, map, pos, base: None, listed: true };
        self.entries.push(entry);
        let id = self.entries.len() - 1;
        self.nodes[value].entry = Some(id);
        self.nodes[value].parent = Some(map);
        if let NodeKind::Map(list) = &mut self.nodes[map].kind {
            match at {
                Some(i) if i <= list.len() => list.insert(i, id),
                _ => list.push(id),
            }
        }
        id
    }

    /// An entry that belongs to a map but is not in it: a base kept for `base`.
    pub fn detached(&mut self, map: NodeId, raw: &str, value: NodeId, pos: Pos) -> EntryId {
        self.entries.push(Entry { key: Key::new(raw), value, map, pos, base: None, listed: false });
        let id = self.entries.len() - 1;
        self.nodes[value].entry = Some(id);
        self.nodes[value].parent = Some(map);
        id
    }

    /// Takes an entry out of its map.
    pub fn remove(&mut self, entry: EntryId) {
        let map = self.entries[entry].map;
        if let NodeKind::Map(list) = &mut self.nodes[map].kind {
            list.retain(|e| *e != entry);
        }
        self.entries[entry].listed = false;
    }

    /// Adds an item to a list.
    pub fn push_item(&mut self, list: NodeId, item: NodeId, at: Option<usize>) {
        self.nodes[item].parent = Some(list);
        self.nodes[item].entry = None;
        if let NodeKind::List(items) = &mut self.nodes[list].kind {
            match at {
                Some(i) if i <= items.len() => items.insert(i, item),
                _ => items.push(item),
            }
        }
    }

    /// The item of a list whose key field is this name.
    pub fn by_id(&self, list: NodeId, id: &str) -> Option<NodeId> {
        let field = self.nodes[list].key_field.clone();
        self.items(list)
            .iter()
            .copied()
            .find(|item| self.is_map(*item) && self.scalar_field(*item, &field).is_some_and(|v| js_string(v) == id))
    }

    /// How an item is named in a path: `.explore` by id, `[2]` by position.
    pub fn label(&self, list: NodeId, item: NodeId) -> String {
        let field = self.nodes[list].key_field.clone();
        match self.is_map(item).then(|| self.scalar_field(item, &field)).flatten() {
            Some(v) => format!(".{}", js_string(v)),
            None => format!("[{}]", self.items(list).iter().position(|i| *i == item).map(|i| i + 1).unwrap_or(0)),
        }
    }

    /// The path of a node, as problems name it.
    pub fn path(&self, id: NodeId) -> String {
        let node = &self.nodes[id];
        if let Some(e) = node.entry {
            return self.entry_path(e);
        }
        if let Some(parent) = node.parent
            && self.is_list(parent)
        {
            return format!("{}{}", self.path(parent), self.label(parent, id));
        }
        String::new()
    }

    /// The path of an entry: `stages.explore.when!`.
    pub fn entry_path(&self, e: EntryId) -> String {
        let entry = &self.entries[e];
        let before = self.path(entry.map);
        if before.is_empty() { entry.key.raw.to_string() } else { format!("{before}.{}", entry.key.raw) }
    }

    /// The place of a node itself: its own line, and the path of its key.
    pub fn place(&self, id: NodeId) -> Place {
        let pos = &self.nodes[id].pos;
        Place { file: pos.file.to_string(), line: pos.line, column: pos.column, key: self.path(id) }
    }

    /// The place of the entry a node is the value of, or of the node when it has none.
    pub fn at(&self, id: NodeId) -> Place {
        match self.nodes[id].entry {
            Some(e) => self.entry_place(e),
            None => self.place(id),
        }
    }

    /// The place of an entry.
    pub fn entry_place(&self, e: EntryId) -> Place {
        let pos = &self.entries[e].pos;
        Place { file: pos.file.to_string(), line: pos.line, column: pos.column, key: self.entry_path(e) }
    }

    /// The ancestors of a node, nearest first.
    pub fn ancestors(&self, id: NodeId) -> Vec<NodeId> {
        let mut out = Vec::new();
        let mut at = self.nodes[id].parent;
        while let Some(p) = at {
            out.push(p);
            at = self.nodes[p].parent;
        }
        out
    }

    /// True when `id` is `ancestor` or inside it.
    pub fn within(&self, id: NodeId, ancestor: NodeId) -> bool {
        let mut at = Some(id);
        while let Some(n) = at {
            if n == ancestor {
                return true;
            }
            at = self.nodes[n].parent;
        }
        false
    }

    /// The node as plain data, keys as written.
    pub fn to_data(&self, id: NodeId) -> Value {
        match &self.nodes[id].kind {
            NodeKind::Scalar(s) => s.value.clone(),
            NodeKind::List(items) => Value::List(items.iter().map(|i| self.to_data(*i)).collect::<Vec<_>>().into()),
            NodeKind::Map(entries) => {
                let mut map = scrusted_feel::Map::new();
                for e in entries {
                    let entry = &self.entries[*e];
                    map.insert(entry.key.raw.clone(), self.to_data(entry.value));
                }
                Value::from(map)
            }
        }
    }

    /// A deep copy of a node, unattached.
    pub fn clone_node(&mut self, id: NodeId) -> NodeId {
        let node = self.nodes[id].clone();
        match node.kind {
            NodeKind::Scalar(s) => self.add(NodeKind::Scalar(s), node.pos),
            NodeKind::List(items) => {
                let copy = self.add(NodeKind::List(Vec::new()), node.pos);
                self.nodes[copy].key_field = node.key_field;
                for item in items {
                    let c = self.clone_node(item);
                    self.push_item(copy, c, None);
                }
                copy
            }
            NodeKind::Map(entries) => {
                let copy = self.add(NodeKind::Map(Vec::new()), node.pos);
                for e in entries {
                    let entry = self.entries[e].clone();
                    let c = self.clone_node(entry.value);
                    self.set(copy, &entry.key.raw, c, entry.pos, None);
                }
                copy
            }
        }
    }
}