Skip to main content

c0/
body.rs

1//! Zero-copy navigator for a document body: files, groups, header rows and
2//! records, each a slice into the original buffer. The structure is built
3//! once by the [`Parser`] with dead elements dropped.
4
5use crate::*;
6use std::borrow::Cow;
7use std::fmt;
8
9/// A document body: the bytes between a heading and EOT, or the inside of
10/// a nested level. Everything it returns borrows the original buffer.
11///
12/// Records before the first GS of a file form an unnamed group; records
13/// and groups before the first FS form an unnamed file.
14pub struct Body<'a> {
15    buf: &'a [u8],
16    start: usize,
17    stop: usize,
18    files: Vec<FileView<'a>>,
19}
20
21impl<'a> Body<'a> {
22    /// Parse a whole buffer as a body (no SYN, no EOT).
23    pub fn new(buf: &'a [u8]) -> Result<Self> {
24        Self::slice(buf, 0, buf.len())
25    }
26
27    /// Parse `buf[start..stop]` as a body.
28    pub fn slice(buf: &'a [u8], start: usize, stop: usize) -> Result<Self> {
29        Self::parse(buf, start, stop, false)
30    }
31
32    /// The contents of a nested level: `raw` is a unit holding `DLE … CAN`
33    /// (layout at its edges allowed).
34    pub fn of_level(raw: &'a [u8]) -> Result<Self> {
35        let t = trim(raw);
36        if t.first() != Some(&DLE) {
37            return Err(Error::other("unit is not a nested level"));
38        }
39        let stop = scan::level(t, 0, t.len())?;
40        Self::parse(t, 1, stop - 1, true)
41    }
42
43    fn parse(buf: &'a [u8], start: usize, stop: usize, level: bool) -> Result<Self> {
44        let mut parser = Parser::new(buf, false);
45        let (files, pos) = parser.body(start, stop, level)?;
46        let pos = scan::layout(buf, pos, stop);
47        if pos < stop {
48            return Err(Error::syntax("unexpected byte in body", pos));
49        }
50        Ok(Body {
51            buf,
52            start,
53            stop,
54            files,
55        })
56    }
57
58    /// A body already parsed (used by the parser).
59    pub(crate) fn from_parts(
60        buf: &'a [u8],
61        start: usize,
62        stop: usize,
63        files: Vec<FileView<'a>>,
64    ) -> Self {
65        Body {
66            buf,
67            start,
68            stop,
69            files,
70        }
71    }
72
73    /// The buffer the body indexes.
74    pub fn buf(&self) -> &'a [u8] {
75        self.buf
76    }
77
78    /// Offset of the body's first byte in the buffer.
79    pub fn start(&self) -> usize {
80        self.start
81    }
82
83    /// Offset just past the body in the buffer.
84    pub fn stop(&self) -> usize {
85        self.stop
86    }
87
88    /// The body's bytes.
89    pub fn raw(&self) -> &'a [u8] {
90        &self.buf[self.start..self.stop]
91    }
92
93    /// The files of the body, in order. There is always at least one (the
94    /// unnamed file, when the body has no FS).
95    pub fn files(&self) -> &[FileView<'a>] {
96        &self.files
97    }
98
99    /// All groups of all files, in order.
100    pub fn groups(&self) -> impl Iterator<Item = &Group<'a>> + '_ {
101        self.files.iter().flat_map(|f| f.groups.iter())
102    }
103
104    /// Groups of the first file.
105    pub fn group_count(&self) -> usize {
106        self.first_file().groups.len()
107    }
108
109    /// Group `i` of the first file.
110    pub fn group(&self, i: usize) -> &Group<'a> {
111        &self.first_file().groups[i]
112    }
113
114    /// The first file's group named `name`.
115    pub fn group_by_name(&self, name: &str) -> Result<&Group<'a>> {
116        self.first_file().group(name)
117    }
118
119    /// Names of the first file's groups.
120    pub fn group_names(&self) -> Vec<&'a [u8]> {
121        self.first_file().groups.iter().map(|g| g.name()).collect()
122    }
123
124    /// Name of the first file (empty when the body has no FS).
125    pub fn name(&self) -> &'a [u8] {
126        self.first_file().name()
127    }
128
129    /// Records of the body when it is a bare record stream (no FS, no
130    /// GS): the unnamed group's records.
131    pub fn records(&self) -> &[Record<'a>] {
132        match self.first_file().groups.first() {
133            Some(g) => &g.records,
134            None => &[],
135        }
136    }
137
138    pub fn record_count(&self) -> usize {
139        self.records().len()
140    }
141
142    pub fn record(&self, i: usize) -> Record<'a> {
143        self.records()[i]
144    }
145
146    /// Whether the body is just records: one unnamed file, at most one
147    /// unnamed group.
148    pub fn bare(&self) -> bool {
149        self.files.len() == 1
150            && self.files[0].leading
151            && self.files[0].groups.len() <= 1
152            && self.files[0].groups.first().is_none_or(|g| g.depth == 0)
153    }
154
155    fn first_file(&self) -> &FileView<'a> {
156        &self.files[0]
157    }
158}
159
160/// A file within a body: its name and groups. The leading file is the
161/// unnamed one before the first FS.
162pub struct FileView<'a> {
163    buf: &'a [u8],
164    name_start: usize,
165    name_end: usize,
166    pub(crate) groups: Vec<Group<'a>>,
167    pub(crate) leading: bool,
168}
169
170impl<'a> FileView<'a> {
171    pub(crate) fn new(buf: &'a [u8], name_start: usize, name_end: usize, leading: bool) -> Self {
172        FileView {
173            buf,
174            name_start,
175            name_end,
176            groups: Vec::new(),
177            leading,
178        }
179    }
180
181    /// The file's name (empty for the unnamed file).
182    pub fn name(&self) -> &'a [u8] {
183        trim(&self.buf[self.name_start..self.name_end])
184    }
185
186    /// Whether this is the unnamed file before the first FS.
187    pub fn is_leading(&self) -> bool {
188        self.leading
189    }
190
191    /// The file's groups, in order.
192    pub fn groups(&self) -> &[Group<'a>] {
193        &self.groups
194    }
195
196    /// The group named `name`.
197    pub fn group(&self, name: &str) -> Result<&Group<'a>> {
198        self.groups
199            .iter()
200            .find(|g| g.name() == name.as_bytes())
201            .ok_or_else(|| Error::Key(format!("No group named '{name}'")))
202    }
203}
204
205/// A group: its depth (one plus its SUB prefix; 0 for the unnamed leading
206/// group), name, optional header row and records.
207pub struct Group<'a> {
208    buf: &'a [u8],
209    pub(crate) depth: usize,
210    name_start: usize,
211    name_end: usize,
212    pub(crate) header: Option<Record<'a>>,
213    pub(crate) records: Vec<Record<'a>>,
214}
215
216/// A group read as a table is itself.
217pub type Table<'a> = Group<'a>;
218
219impl<'a> Group<'a> {
220    pub(crate) fn new(buf: &'a [u8], depth: usize, name_start: usize, name_end: usize) -> Self {
221        Group {
222            buf,
223            depth,
224            name_start,
225            name_end,
226            header: None,
227            records: Vec::new(),
228        }
229    }
230
231    /// The group's name (empty for the unnamed leading group).
232    pub fn name(&self) -> &'a [u8] {
233        trim(&self.buf[self.name_start..self.name_end])
234    }
235
236    /// Depth: 1 for `␝g`, 2 for `␚␝g` (one plus the SUB prefix); 0 for the
237    /// unnamed group.
238    pub fn depth(&self) -> usize {
239        self.depth
240    }
241
242    /// Whether the group has a header row.
243    pub fn has_header(&self) -> bool {
244        self.header.is_some()
245    }
246
247    /// The header row as a record, if any.
248    pub fn header_row(&self) -> Option<Record<'a>> {
249        self.header
250    }
251
252    /// Header names, or an empty vector.
253    pub fn headers(&self) -> Vec<&'a [u8]> {
254        match &self.header {
255            Some(h) => h.fields().into_iter().map(name_value).collect(),
256            None => Vec::new(),
257        }
258    }
259
260    pub fn header_count(&self) -> usize {
261        self.header.map_or(0, |h| h.field_count())
262    }
263
264    pub fn header(&self, i: usize) -> &'a [u8] {
265        self.headers()[i]
266    }
267
268    pub fn record_count(&self) -> usize {
269        self.records.len()
270    }
271
272    pub fn record(&self, i: usize) -> Record<'a> {
273        self.records[i]
274    }
275
276    /// The records, in order.
277    pub fn records(&self) -> &[Record<'a>] {
278        &self.records
279    }
280
281    /// Index of a header name, or `None`.
282    pub fn column(&self, name: &str) -> Option<usize> {
283        self.headers().iter().position(|h| *h == name.as_bytes())
284    }
285}
286
287// The logical value of a unit that holds a name (plain, never text, with
288// notes allowed after it), borrowed from the buffer.
289fn name_value(raw: &[u8]) -> &[u8] {
290    match value(raw) {
291        Ok(Cow::Borrowed(b)) => b,
292        _ => trim(raw),
293    }
294}
295
296/// A key and its logical value, from a keyed record.
297pub type Pair<'a> = (&'a [u8], Cow<'a, [u8]>);
298
299/// One unit as written: its raw value bytes and its sub-units (`␞a␟b␚␟c`:
300/// `b` holds the sub-unit `c`; DESIGN.md, Subordinates), each a `Unit`
301/// with sub-units of its own (`␞a␚␟b␚␚␟c`: `a` holds `b` holding `c`).
302#[derive(Clone, PartialEq, Eq)]
303pub struct Unit<'a> {
304    raw: &'a [u8],
305    subs: Vec<Unit<'a>>,
306}
307
308impl<'a> Unit<'a> {
309    /// Raw bytes of the unit's value (layout at its edges included, its
310    /// sub-units not).
311    pub fn raw(&self) -> &'a [u8] {
312        self.raw
313    }
314
315    /// The sub-units, in written order; empty for a unit without any.
316    pub fn subs(&self) -> &[Unit<'a>] {
317        &self.subs
318    }
319
320    /// The logical value.
321    pub fn value(&self) -> Result<Cow<'a, [u8]>> {
322        value(self.raw)
323    }
324}
325
326impl fmt::Debug for Unit<'_> {
327    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328        f.debug_struct("Unit")
329            .field("raw", &String::from_utf8_lossy(self.raw))
330            .field("subs", &self.subs)
331            .finish()
332    }
333}
334
335// (depth, value start, value end) of a sub-unit as written.
336type SubSpan = (usize, usize, usize);
337
338/// A record: positional or keyed. Copyable, zero-copy accessors. A
339/// sub-unit is not a unit of the record: `fields`, `values` and `pairs`
340/// list the units; [`Record::unit`] and [`Record::get_unit`] give a unit
341/// with its sub-units.
342#[derive(Clone, Copy, PartialEq, Eq)]
343pub struct Record<'a> {
344    buf: &'a [u8],
345    start: usize,
346    end: usize,
347}
348
349impl fmt::Debug for Record<'_> {
350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351        f.debug_struct("Record")
352            .field("raw", &String::from_utf8_lossy(self.raw()))
353            .finish()
354    }
355}
356
357impl<'a> Record<'a> {
358    pub(crate) fn new(buf: &'a [u8], start: usize, end: usize) -> Self {
359        Record { buf, start, end }
360    }
361
362    /// Raw bytes of the record (after its RS).
363    #[inline]
364    pub fn raw(&self) -> &'a [u8] {
365        &self.buf[self.start..self.end]
366    }
367
368    /// Offset of the record's first byte in the buffer.
369    pub fn offset(&self) -> usize {
370        self.start
371    }
372
373    /// Whether the record is keyed (its first unit, live or dead, is an
374    /// SOH).
375    pub fn keyed(&self) -> bool {
376        let buf = self.buf;
377        let end = self.end;
378        let mut p = scan::layout(buf, self.start, end);
379        while p < end && buf[p] == BEL {
380            let p2 = scan::layout(buf, p + 1, end);
381            if p2 < end && buf[p2] == SOH {
382                return true;
383            }
384            if p2 >= end || (buf[p2] < 0x20 && buf[p2] != STX) {
385                break;
386            }
387            match scan::comment(buf, p, end) {
388                Ok(n) => p = scan::layout(buf, n, end),
389                Err(_) => return false,
390            }
391        }
392        p < end && buf[p] == SOH
393    }
394
395    // ---- positional -----------------------------------------------------
396
397    /// Raw slice of unit `n` (layout at its edges included, its sub-units
398    /// not); empty when there is no such unit.
399    pub fn field(&self, n: usize) -> &'a [u8] {
400        self.unit_ranges()
401            .get(n)
402            .map_or(&[][..], |&(s, e)| &self.buf[s..e])
403    }
404
405    /// Number of positional units (0 for a keyed record). A sub-unit is
406    /// not counted.
407    pub fn field_count(&self) -> usize {
408        self.unit_ranges().len()
409    }
410
411    /// Raw slices of every unit.
412    pub fn fields(&self) -> Vec<&'a [u8]> {
413        self.unit_ranges()
414            .into_iter()
415            .map(|(s, e)| &self.buf[s..e])
416            .collect()
417    }
418
419    /// Every positional unit with its sub-units.
420    pub fn units(&self) -> Vec<Unit<'a>> {
421        self.unit_spans()
422            .into_iter()
423            .map(|(s, e, subs)| Unit {
424                raw: &self.buf[s..e],
425                subs: sub_tree(self.buf, &subs),
426            })
427            .collect()
428    }
429
430    /// Positional unit `n` with its sub-units, or `None` when there is no
431    /// such unit.
432    pub fn unit(&self, n: usize) -> Option<Unit<'a>> {
433        self.unit_spans()
434            .into_iter()
435            .nth(n)
436            .map(|(s, e, subs)| Unit {
437                raw: &self.buf[s..e],
438                subs: sub_tree(self.buf, &subs),
439            })
440    }
441
442    /// Logical value of unit `n`: text decoded, layout trimmed.
443    pub fn value(&self, n: usize) -> Result<Cow<'a, [u8]>> {
444        value(self.field(n))
445    }
446
447    /// Logical values of every unit.
448    pub fn values(&self) -> Result<Vec<Cow<'a, [u8]>>> {
449        self.fields().into_iter().map(value).collect()
450    }
451
452    /// Unit `n` as a nested level.
453    pub fn level(&self, n: usize) -> Result<Body<'a>> {
454        Body::of_level(self.field(n))
455    }
456
457    /// Unit `n` as a flat list: a level holding exactly one positional
458    /// record (an empty level is the empty list).
459    pub fn list(&self, n: usize) -> Result<Vec<Cow<'a, [u8]>>> {
460        let body = self.level(n)?;
461        let recs = body.records();
462        if recs.is_empty() && body.bare() {
463            return Ok(Vec::new());
464        }
465        if !(recs.len() == 1 && body.bare()) {
466            return Err(Error::other(format!(
467                "level is not a list ({} records)",
468                recs.len()
469            )));
470        }
471        if body.group_count() > 0 && body.group(0).has_header() {
472            return Err(Error::other("level is not a list (header row)"));
473        }
474        if recs[0].keyed() {
475            return Err(Error::other("level is not a list (keyed record)"));
476        }
477        recs[0].values()
478    }
479
480    /// Unit `n` as a reference.
481    pub fn reference(&self, n: usize) -> Result<Reference<'a>> {
482        Reference::parse(self.field(n))
483    }
484
485    // ---- keyed ---------------------------------------------------------
486
487    /// Keys in written order (duplicates included).
488    pub fn keys(&self) -> Vec<&'a [u8]> {
489        self.keyed_ranges()
490            .unwrap_or_default()
491            .into_iter()
492            .map(|(k, _, _, _)| k)
493            .collect()
494    }
495
496    /// (key, logical value) pairs in written order.
497    pub fn pairs(&self) -> Result<Vec<Pair<'a>>> {
498        self.keyed_ranges()?
499            .into_iter()
500            .map(|(k, vs, ve, _)| Ok((k, value(&self.buf[vs..ve])?)))
501            .collect()
502    }
503
504    /// Raw unit for a key (last wins), or `None`.
505    pub fn get_raw(&self, key: &str) -> Option<&'a [u8]> {
506        let mut found = None;
507        for (k, vs, ve, _) in self.keyed_ranges().unwrap_or_default() {
508            if k == key.as_bytes() {
509                found = Some(&self.buf[vs..ve]);
510            }
511        }
512        found
513    }
514
515    /// The unit under a key with its sub-units (last wins), or `None`.
516    pub fn get_unit(&self, key: &str) -> Option<Unit<'a>> {
517        let mut found = None;
518        for (k, vs, ve, subs) in self.keyed_ranges().unwrap_or_default() {
519            if k == key.as_bytes() {
520                found = Some(Unit {
521                    raw: &self.buf[vs..ve],
522                    subs: sub_tree(self.buf, &subs),
523                });
524            }
525        }
526        found
527    }
528
529    /// Logical value for a key (last wins), or `None`.
530    pub fn get(&self, key: &str) -> Result<Option<Cow<'a, [u8]>>> {
531        self.get_raw(key).map(value).transpose()
532    }
533
534    /// The value for a key as a nested level, or `None`.
535    pub fn get_level(&self, key: &str) -> Result<Option<Body<'a>>> {
536        self.get_raw(key).map(Body::of_level).transpose()
537    }
538
539    pub fn has_key(&self, key: &str) -> bool {
540        self.get_raw(key).is_some()
541    }
542
543    // ---- internals ------------------------------------------------------
544
545    // Skip the sub-units after a value ending at `pos`, collecting their
546    // (depth, start, end) spans. Returns the position after them: the US
547    // of the next unit, a SUB prefixing the next line, or the end.
548    fn sub_spans(&self, mut pos: usize, spans: &mut Vec<SubSpan>) -> usize {
549        let buf = self.buf;
550        let end = self.end;
551        loop {
552            if !(pos < end && buf[pos] == SUB) {
553                return pos;
554            }
555            let mut q = pos;
556            let mut run = 0usize;
557            while q < end && buf[q] == SUB {
558                run += 1;
559                q = scan::layout(buf, q + 1, end);
560            }
561            if !(q < end && buf[q] == US) {
562                return pos;
563            }
564            let ss = q + 1;
565            let se = scan::unit(buf, ss, end).unwrap_or(end);
566            spans.push((run, ss, se));
567            pos = se;
568        }
569    }
570
571    // (start, end, sub-unit spans) of each positional unit. A record comes
572    // from a parsed body, whose text and levels were already checked, so
573    // the unit scan cannot fail; should it, the unit runs to the end.
574    fn unit_spans(&self) -> Vec<(usize, usize, Vec<SubSpan>)> {
575        let buf = self.buf;
576        let end = self.end;
577        let mut out = Vec::new();
578        if self.keyed() {
579            return out;
580        }
581        let mut pos = scan::layout(buf, self.start, end);
582        let mut unit_start = self.start;
583        loop {
584            pos = scan::unit(buf, pos, end).unwrap_or(end);
585            let mut spans = Vec::new();
586            let next = self.sub_spans(pos, &mut spans);
587            out.push((unit_start, pos, spans));
588            if !(next < end && buf[next] == US) {
589                break;
590            }
591            pos = next + 1;
592            unit_start = pos;
593        }
594        out
595    }
596
597    // (start, end) of each positional unit.
598    fn unit_ranges(&self) -> Vec<(usize, usize)> {
599        self.unit_spans()
600            .into_iter()
601            .map(|(s, e, _)| (s, e))
602            .collect()
603    }
604
605    // (key, value start, value end, sub-unit spans) per keyed unit.
606    #[allow(clippy::type_complexity)]
607    fn keyed_ranges(&self) -> Result<Vec<(&'a [u8], usize, usize, Vec<SubSpan>)>> {
608        let buf = self.buf;
609        let end = self.end;
610        let mut out = Vec::new();
611        let mut pos = scan::layout(buf, self.start, end);
612        while pos < end {
613            let b = buf[pos];
614            if b == SOH {
615                let ks = scan::layout(buf, pos + 1, end);
616                let ke = scan::plain(buf, ks, end);
617                if !(ke < end && buf[ke] == US) {
618                    return Err(Error::syntax("key without a value (no US)", ke));
619                }
620                let vs = ke + 1;
621                let ve = scan::unit(buf, vs, end)?;
622                let mut spans = Vec::new();
623                pos = self.sub_spans(ve, &mut spans);
624                out.push((trim(&buf[ks..ke]), vs, ve, spans));
625            } else if b == BEL {
626                // a note, or a dead keyed unit, which takes its sub-units
627                pos = scan::comment(buf, pos, end)?;
628                let mut dead = Vec::new();
629                pos = self.sub_spans(pos, &mut dead);
630            } else if is_layout(b) {
631                pos += 1;
632            } else {
633                break;
634            }
635        }
636        Ok(out)
637    }
638
639    // Whether any unit, positional or keyed, holds a sub-unit.
640    pub(crate) fn has_sub_units(&self) -> bool {
641        self.unit_spans()
642            .iter()
643            .any(|(_, _, subs)| !subs.is_empty())
644            || self
645                .keyed_ranges()
646                .unwrap_or_default()
647                .iter()
648                .any(|(_, _, _, subs)| !subs.is_empty())
649    }
650}
651
652// Build the sub-unit tree from (depth, start, end) spans in written order:
653// the spans after one that are deeper than it are its descendants. The
654// parser has refused skipped depths.
655fn sub_tree<'a>(buf: &'a [u8], spans: &[SubSpan]) -> Vec<Unit<'a>> {
656    let mut out = Vec::new();
657    let mut i = 0;
658    while i < spans.len() {
659        let (d, s, e) = spans[i];
660        let mut j = i + 1;
661        while j < spans.len() && spans[j].0 > d {
662            j += 1;
663        }
664        out.push(Unit {
665            raw: &buf[s..e],
666            subs: sub_tree(buf, &spans[i + 1..j]),
667        });
668        i = j;
669    }
670    out
671}
672
673/// A reference (DESIGN.md, References): a group name written plain, or a
674/// pattern, a level that is one branch of the target with its values left
675/// out. The pattern is reported as the level it is written as.
676pub struct Reference<'a> {
677    name: Option<&'a [u8]>,
678    pattern: Option<Body<'a>>,
679}
680
681impl fmt::Debug for Reference<'_> {
682    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
683        let path: Vec<String> = self
684            .path()
685            .iter()
686            .map(|s| String::from_utf8_lossy(s).into_owned())
687            .collect();
688        f.debug_struct("Reference")
689            .field("group", &self.name.is_some())
690            .field("path", &path)
691            .finish()
692    }
693}
694
695impl<'a> Reference<'a> {
696    pub(crate) fn new(name: Option<&'a [u8]>, pattern: Option<Body<'a>>) -> Self {
697        Reference { name, pattern }
698    }
699
700    /// Parse a raw unit holding a reference (notes after it allowed).
701    pub fn parse(raw: &'a [u8]) -> Result<Self> {
702        let t = trim(raw);
703        if t.first() != Some(&ENQ) {
704            return Err(Error::other("unit is not a reference"));
705        }
706        let mut parser = Parser::new(t, false);
707        let (r, pos) = parser.reference(0, t.len())?;
708        let mut pos = scan::layout(t, pos, t.len());
709        while pos < t.len() {
710            if t[pos] != BEL {
711                return Err(Error::syntax("unexpected byte after a reference", pos));
712            }
713            pos = scan::layout(t, scan::comment(t, pos, t.len())?, t.len());
714        }
715        Ok(r)
716    }
717
718    /// The group name of a plain reference, or `None` for a pattern.
719    pub fn name(&self) -> Option<&'a [u8]> {
720        self.name
721    }
722
723    /// The pattern of `ENQ DLE … CAN`, or `None` for a plain reference.
724    pub fn pattern(&self) -> Option<&Body<'a>> {
725        self.pattern.as_ref()
726    }
727
728    /// Whether the reference names a group as a whole: a plain name, or a
729    /// pattern that is a bare group line.
730    pub fn is_group(&self) -> bool {
731        if self.name.is_some() {
732            return true;
733        }
734        let p = self
735            .pattern
736            .as_ref()
737            .expect("a reference is a name or a pattern");
738        let groups: Vec<&Group<'a>> = p.groups().collect();
739        p.files()[0].is_leading() && groups.len() == 1 && groups[0].records().is_empty()
740    }
741
742    /// The group named, when the reference names a group as a whole.
743    pub fn group_name(&self) -> Option<&'a [u8]> {
744        if let Some(n) = self.name {
745            return Some(n);
746        }
747        if self.is_group() {
748            self.pattern
749                .as_ref()
750                .and_then(|p| p.groups().next().map(|g| g.name()))
751        } else {
752            None
753        }
754    }
755
756    /// The steps of the pattern in walking order (file, groups, record id,
757    /// field name, then the inner pattern's steps), or the group name
758    /// alone. Informal: a keyed step contributes its key.
759    pub fn path(&self) -> Vec<&'a [u8]> {
760        if let Some(n) = self.name {
761            return vec![n];
762        }
763        let mut out = Vec::new();
764        let Some(p) = self.pattern.as_ref() else {
765            return out;
766        };
767        let f = &p.files()[0];
768        if !f.is_leading() {
769            out.push(f.name());
770        }
771        for g in f.groups() {
772            if g.depth() > 0 {
773                out.push(g.name());
774            }
775        }
776        let Some(rec) = f.groups().last().and_then(|g| g.records().first()) else {
777            return out;
778        };
779        if rec.keyed() {
780            if let Some(k) = rec.keys().first() {
781                out.push(k);
782            }
783        } else {
784            for (i, raw) in rec.fields().into_iter().enumerate() {
785                if i < 2 {
786                    out.push(name_value(raw));
787                } else if let Ok(inner) = Body::of_level(raw) {
788                    out.extend(Reference::new(None, Some(inner)).path());
789                }
790            }
791        }
792        out
793    }
794}