techy 0.1.1

A fast, extensible LaTeX parser for Rust
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! The read proxy over a [`NodeTree`]'s flat storage: [`NodeRef`], its
//! [`Descendants`] iterator, and the [`NamedAccessError`] of the by-name accessors.

use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use core::fmt;

use crate::source::{Source, SourceSpan};
use crate::spec::CallableSpec;
use crate::state::{Lang, ParsingState};

use alloc::vec::Vec;

use super::arguments::{BodySlotExt, ChildRegion, ParsedArguments, ParsedSlots};
use super::kind::{CallableData, CommentData, GroupData, NodeKind};
use super::slice::NodeSlice;
use super::tree::{NodeData, NodeId, NodeTree, NO_PARENT};
use super::{NodeExt, SlotExt};

/// A reference to one node of a [`NodeTree`]: `Copy`, and valid for as long as it
/// borrows the tree.
///
/// Every read of a parsed tree goes through a `NodeRef`. One comes from
/// [`NodeTree::root`](super::NodeTree::root), from
/// [`NodeTree::node`](super::NodeTree::node) or
/// [`get`](super::NodeTree::get) for a [`NodeId`], from a source-position query
/// ([`NodeTree::node_at`](super::NodeTree::node_at)), or from another node:
/// [`parent`](NodeRef::parent), [`child`](NodeRef::child),
/// [`children`](NodeRef::children), and [`descendants`](NodeRef::descendants) navigate
/// the structure, while [`kind`](NodeRef::kind), [`span`](NodeRef::span), and the
/// kind-specific accessors below read one node.
///
/// A `NodeRef` stores only a borrow of the tree and an index, so the borrow checker
/// guarantees it cannot outlive the storage that index points into. Its accessors
/// return data borrowed from the *tree*, not from this transient proxy, so what they
/// return outlives the `NodeRef` value itself.
///
/// A kind-specific accessor answers `None` on a node of another kind. For latexlike
/// trees the preset adds accessors in its own vocabulary to this same type —
/// [`macro_name`](NodeRef::macro_name),
/// [`environment_name`](NodeRef::environment_name),
/// [`is_math_group`](NodeRef::is_math_group), and others.
pub struct NodeRef<'t, L: Lang, A = ()> {
    tree: &'t NodeTree<L, A>,
    id: NodeId,
}

impl<'t, L: Lang, A> NodeRef<'t, L, A> {
    pub(crate) fn new(tree: &'t NodeTree<L, A>, id: NodeId) -> NodeRef<'t, L, A> {
        debug_assert_eq!(
            id.tree_tag(),
            tree.tree_tag(),
            "NodeId used with a tree that did not mint it \
             (ids are only meaningful for their own tree)"
        );
        NodeRef { tree, id }
    }

    fn data(&self) -> &'t NodeData<L> {
        &self.tree.nodes()[self.id.index()]
    }

    /// The tree this reference points into, for tree-level operations reached from a
    /// node ([`NodeTree::node_at`](super::NodeTree::node_at),
    /// [`annotations`](super::NodeTree::annotations), …).
    pub fn tree(&self) -> &'t NodeTree<L, A> {
        self.tree
    }

    /// This node's parent, or `None` at the root. O(1) — the tree stores a parent
    /// table.
    ///
    /// To visit all ancestors, innermost first:
    /// `core::iter::successors(node.parent(), |n| n.parent())`.
    pub fn parent(&self) -> Option<NodeRef<'t, L, A>> {
        let parent = self.tree.parent_table()[self.id.index()];
        (parent != NO_PARENT).then(|| NodeRef::new(self.tree, self.tree.make_id(parent)))
    }

    /// This node's position in its parent's child list (`parent().child(i)` is this
    /// node) — `None` at the root. O(1): the own index minus the parent's
    /// children-block start.
    pub fn index_in_parent(&self) -> Option<usize> {
        let parent = self.parent()?;
        Some(self.id.index() - parent.data().children.start as usize)
    }

    /// This node's annotation: the tree's consumer-owned per-node data (see
    /// [`NodeTree`]'s annotation notes).
    ///
    /// There is no setter — trees are immutable, and a new annotation stage comes from
    /// [`NodeTree::annotate`](super::NodeTree::annotate).
    pub fn annotation(&self) -> &'t A {
        &self.tree.annotations[self.id.index()]
    }

    /// This node's id within its tree.
    pub fn id(&self) -> NodeId {
        self.id
    }

    /// The structural kind (exhaustively matchable).
    pub fn kind(&self) -> &'t NodeKind<L> {
        &self.data().kind
    }

    /// This node's language-specific ext data ([`NodeExt`], the same type for every
    /// node kind).
    pub fn ext(&self) -> &'t NodeExt<L> {
        &self.data().ext
    }

    /// Where the node came from: its provenance span, an `Arc<Source>` and a byte
    /// range.
    ///
    /// On a tree parsed from a language that obeys span tiling
    /// ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING)) the span is
    /// exactly the stretch of source the node was parsed from. For a language with
    /// `OBEYS_SPAN_TILING = false` it is the span the token reader described for that
    /// stretch of the stream, and for a restaged or synthesized node it is whatever the
    /// transform recorded. What the node *says* is read from its own data, never from
    /// the span.
    pub fn span(&self) -> &'t SourceSpan<L::SourceOrigin> {
        &self.data().span
    }

    /// The text this node's [`span`](NodeRef::span) points at — the node's original
    /// spelling, verbatim.
    ///
    /// It needs no external lookup and works for detached and mixed-origin trees, since
    /// the span names its own source.
    ///
    /// The answer comes from the coordinates, not from the node's data. The two agree
    /// on a tree parsed from a language that obeys span tiling
    /// ([`Lang::OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING)), where the
    /// span is exactly the node's original text. For a language with
    /// `OBEYS_SPAN_TILING = false`, and on restaged or synthesized trees, they need not
    /// agree: what the node says is its recorded data ([`chars`](NodeRef::chars),
    /// [`group_delimiters`](NodeRef::group_delimiters), [`comment`](NodeRef::comment),
    /// [`callable`](NodeRef::callable)), and re-emitting the spelling of a whole tree is
    /// what [`recompose`](crate::recompose) does.
    pub fn span_content(&self) -> &'t str {
        self.data().span.content()
    }

    /// The parsing state this node was parsed under.
    pub fn parsing_state(&self) -> &'t Arc<ParsingState<L>> {
        &self.data().parsing_state
    }

    /// A compact one-line description of the node, for assertions and log messages:
    /// `chars(ab )`, `group(Math(Inline) $ $)`, `Macro(emph)`, `comment( note)`,
    /// `list(3)`.
    ///
    /// It is the short companion of the verbose `Debug` rendering. Groups print their
    /// class (`?` when they have none) and their recorded delimiters; callables print
    /// their invocation form (via `Debug`) and their spelling; chars and comment nodes
    /// print their full logical text; lists print their child count. A whole subtree is
    /// rendered by [`display_tree`](super::display_tree).
    ///
    /// The format is human-oriented and **not a stability contract**: it may change
    /// between releases. Within a release it is exact, and the crate's own tests pin
    /// it, so a re-implementation that must agree with these renderings — a binding
    /// porting the test suite — can reproduce it verbatim. Where exactness has to
    /// outlast a test, compare trees structurally instead, through kinds, spans, and
    /// accessors.
    ///
    /// # Panics
    ///
    /// The rendering resolves the node's span-backed text, so it panics on a broken
    /// tree invariant, exactly as [`chars`](NodeRef::chars) does.
    pub fn summary(&self) -> String {
        if let Some(text) = self.chars() {
            format!("chars({text})")
        } else if self.is_group() {
            let class = self
                .group_type()
                .map_or_else(|| "?".to_string(), |group_type| format!("{group_type:?}"));
            let (open, close) = self.group_delimiters().unwrap_or(("", ""));
            format!("group({class} {open} {close})")
        } else if let Some(data) = self.callable() {
            format!("{:?}({})", data.callable_type, data.name)
        } else if let Some(data) = self.comment() {
            format!("comment({})", data.content.resolve(self.source()))
        } else {
            format!("list({})", self.child_count())
        }
    }

    /// This node's own source (what `TextContent::Spanned` resolves against).
    pub(crate) fn source(&self) -> &'t Source<L::SourceOrigin> {
        self.data().span.source()
    }

    // --- children ---------------------------------------------------------------------

    /// The number of structural children.
    pub fn child_count(&self) -> usize {
        self.data().children.len()
    }

    /// The `i`-th structural child.
    pub fn child(&self, i: usize) -> Option<NodeRef<'t, L, A>> {
        let children = &self.data().children;
        let id = children.start.checked_add(u32::try_from(i).ok()?)?;
        (id < children.end).then(|| NodeRef::new(self.tree, self.tree.make_id(id)))
    }

    /// The structural children, in order, as a [`NodeSlice`] (iterable directly; use
    /// [`iter()`](NodeSlice::iter) for adaptor chains).
    pub fn children(&self) -> NodeSlice<'t, L, A> {
        NodeSlice::new(self.tree, self.data().children.clone())
    }

    /// The node's descendants in **document order** — preorder depth-first, each node
    /// before its children and siblings left to right — the node itself excluded.
    ///
    /// This is how to visit everything under a node: find every `\cite`, collect every
    /// math group. The flat storage order
    /// ([`NodeTree::iter_storage_order`](super::NodeTree::iter_storage_order)) is
    /// deliberately not document order.
    pub fn descendants(&self) -> Descendants<'t, L, A> {
        let mut stack = Vec::new();
        push_children_reversed(&mut stack, self.data());
        Descendants { tree: self.tree, stack }
    }

    // --- kind predicates and kind-specific accessors ------------------------------------

    /// Whether this is a `Chars` node.
    pub fn is_chars(&self) -> bool {
        matches!(self.kind(), NodeKind::Chars { .. })
    }

    /// Whether this is a `Group` node.
    pub fn is_group(&self) -> bool {
        matches!(self.kind(), NodeKind::Group { .. })
    }

    /// Whether this is a `Callable` node.
    pub fn is_callable(&self) -> bool {
        matches!(self.kind(), NodeKind::Callable(_))
    }

    /// Whether this is a `Comment` node.
    pub fn is_comment(&self) -> bool {
        matches!(self.kind(), NodeKind::Comment { .. })
    }

    /// Whether this is a `List` node.
    pub fn is_list(&self) -> bool {
        matches!(self.kind(), NodeKind::List)
    }

    /// A `Chars` node's logical text — its recorded content, resolved against the
    /// node's own source.
    ///
    /// # Panics
    ///
    /// Panics if the node records its content as a span that is not a valid
    /// `char`-boundary range of the node's own source. That is a broken tree
    /// invariant, which no parsed input can cause and which
    /// [`validate_tree`](super::validate_tree) detects; the panic is
    /// [`TextContent::resolve`](crate::source::TextContent::resolve)'s (see the [list
    /// of panicking items](crate::guide::panics)).
    pub fn chars(&self) -> Option<&'t str> {
        match self.kind() {
            NodeKind::Chars { content, .. } => Some(content.resolve(self.source())),
            _ => None,
        }
    }

    /// A `Comment` node's full payload ([`CommentData`]: start delimiter, content,
    /// and syntactic post-space). Span-backed payload fields resolve against the
    /// node's own source, `node.span().source()`
    /// ([`TextContent::resolve`](crate::source::TextContent::resolve)).
    pub fn comment(&self) -> Option<&'t CommentData> {
        match self.kind() {
            NodeKind::Comment(data) => Some(data),
            _ => None,
        }
    }

    /// A `Group` node's full payload ([`GroupData`]: the delimiters as written and
    /// the group's class).
    pub fn group(&self) -> Option<&'t GroupData<L>> {
        match self.kind() {
            NodeKind::Group(data) => Some(data),
            _ => None,
        }
    }

    /// A `Group` node's class. `None` for non-groups *and* for synthesized groups
    /// without a language group class — consult [`group()`](NodeRef::group) to
    /// distinguish.
    pub fn group_type(&self) -> Option<L::GroupTypeId> {
        self.group().and_then(|data| data.group_type)
    }

    /// A `Group` node's delimiters, as logical text: the opening one and the closing
    /// one. The closing delimiter is empty when the close was never found.
    ///
    /// # Panics
    ///
    /// Panics on a broken tree invariant, exactly as [`chars`](NodeRef::chars) does:
    /// a delimiter recorded as a span must be a valid `char`-boundary range of the
    /// node's own source.
    pub fn group_delimiters(&self) -> Option<(&'t str, &'t str)> {
        self.group().map(|data| {
            (data.open.resolve(self.source()), data.close.resolve(self.source()))
        })
    }

    // --- callable accessors -------------------------------------------------------------

    /// A `Callable` node's full invocation data.
    pub fn callable(&self) -> Option<&'t CallableData<L>> {
        match self.kind() {
            NodeKind::Callable(data) => Some(data),
            _ => None,
        }
    }

    /// A `Callable` node's invocation form.
    pub fn callable_type(&self) -> Option<L::CallableTypeId> {
        self.callable().map(|data| data.callable_type)
    }

    /// A `Callable` node's invocation spelling.
    pub fn name(&self) -> Option<&'t str> {
        self.callable().map(|data| &*data.name)
    }

    /// A `Callable` node's behavior spec.
    pub fn spec(&self) -> Option<&'t Arc<dyn CallableSpec<L>>> {
        self.callable().map(|data| &data.spec)
    }

    /// A `Callable` node's recorded invocation-syntax payload
    /// ([`CallableData::invocation_syntax`]): the trigger-spelling facts, in the type
    /// the language chose.
    ///
    /// Typed readers for it are defined with that payload type — the preset's
    /// [`post_space`](NodeRef::post_space), for one, reads its `Macro` arm.
    pub fn invocation_syntax(&self) -> Option<&'t L::InvocationSyntax> {
        self.callable().map(|data| &data.invocation_syntax)
    }

    /// A `Callable` node's parsed-arguments record.
    pub fn arguments(&self) -> Option<&'t ParsedArguments<L>> {
        self.callable().map(|data| &data.arguments)
    }

    /// A `Callable` node's parsed-slots record.
    pub fn slots(&self) -> Option<&'t ParsedSlots<L>> {
        self.callable().map(|data| &data.slots)
    }

    /// The nodes of argument `i`'s region, in source order: the argument's full
    /// syntactic extent, comment and whitespace nodes included.
    ///
    /// `None` for a non-callable, an out-of-range index, and an argument that was not
    /// provided. To tell those apart, read [`arguments`](NodeRef::arguments), or use
    /// the by-name form [`argument_nodes_named`](NodeRef::argument_nodes_named), whose
    /// `Result` separates the category errors from a merely absent argument.
    pub fn argument_nodes(&self, i: usize) -> Option<NodeSlice<'t, L, A>> {
        self.region_nodes(self.callable()?.arguments.get(i)?.region.as_ref()?)
    }

    /// The nodes of the region of the argument named `name`, per its
    /// [`ArgumentSpec`](crate::core::specs::ArgumentSpec) —
    /// [`argument_nodes`](NodeRef::argument_nodes) by name.
    ///
    /// # Errors
    ///
    /// `Err` is a category mismatch: the node is not a callable, or `name` is not among
    /// the spec's declared arguments (the misspelling trap). `Ok(None)` means precisely
    /// "declared but absent", and `Ok(Some)` that the argument is present.
    pub fn argument_nodes_named(
        &self,
        name: &str,
    ) -> Result<Option<NodeSlice<'t, L, A>>, NamedAccessError> {
        let callable = self.callable().ok_or(NamedAccessError::NotACallable)?;
        let argument = callable.arguments.get_named(name).ok_or_else(|| {
            NamedAccessError::UnknownArgumentName { name: name.into() }
        })?;
        Ok(argument.region.as_ref().and_then(|region| self.region_nodes(region)))
    }

    /// The content nodes of argument `i`, with delimiters and comment and whitespace
    /// nodes excluded: the group's children for `\textbf{abc}`, the single `Chars`
    /// node for `\frac 1 2`.
    ///
    /// These are exactly the nodes the argument's parser designated as content; no
    /// unwrapping is guessed here.
    ///
    /// `None` for a non-callable, an out-of-range index, and an argument that was not
    /// provided. To tell those apart, read [`arguments`](NodeRef::arguments), or use
    /// the by-name form
    /// [`argument_content_nodes_named`](NodeRef::argument_content_nodes_named), whose
    /// `Result` separates the category errors from a merely absent argument.
    pub fn argument_content_nodes(&self, i: usize) -> Option<NodeSlice<'t, L, A>> {
        self.region_content(self.callable()?.arguments.get(i)?.region.as_ref()?)
    }

    /// The content nodes of the argument named `name` —
    /// [`argument_content_nodes`](NodeRef::argument_content_nodes) by name.
    ///
    /// # Errors
    ///
    /// The contract of [`argument_nodes_named`](NodeRef::argument_nodes_named): `Err`
    /// is a category mismatch, `Ok(None)` is declared but absent, and `Ok(Some)` is
    /// present.
    pub fn argument_content_nodes_named(
        &self,
        name: &str,
    ) -> Result<Option<NodeSlice<'t, L, A>>, NamedAccessError> {
        let callable = self.callable().ok_or(NamedAccessError::NotACallable)?;
        let argument = callable.arguments.get_named(name).ok_or_else(|| {
            NamedAccessError::UnknownArgumentName { name: name.into() }
        })?;
        Ok(argument.region.as_ref().and_then(|region| self.region_content(region)))
    }

    fn region_nodes(&self, region: &ChildRegion) -> Option<NodeSlice<'t, L, A>> {
        Some(NodeSlice::new(self.tree, region.children()))
    }

    fn region_content(&self, region: &ChildRegion) -> Option<NodeSlice<'t, L, A>> {
        Some(NodeSlice::new(self.tree, region.content_range()))
    }

    /// The node whose child list holds slot `i`'s content — the body `List` of the
    /// standard environment shape — when this is a callable with such a slot.
    ///
    /// `None` when the slot's content sits directly among the callable's own children
    /// (a [`ContentNodes::InRegion`](super::ContentNodes) designation), where no
    /// wrapper node exists; answering with the callable itself would send a naive
    /// recursive walker into a loop. The one such shape the crate ships is the
    /// `attached` slot of
    /// [`input_macro_spec`](crate::latexlike::input_macro_spec), where the included
    /// content's nodes sit directly among the `\input` callable's children (producing
    /// them requires a [`SourceResolver`](crate::source::SourceResolver) on the
    /// driver).
    ///
    /// For content access that works for *both* shapes, use
    /// [`slot_content_nodes`](NodeRef::slot_content_nodes) or
    /// [`body`](NodeRef::body).
    pub fn slot_content_parent(&self, i: usize) -> Option<NodeRef<'t, L, A>> {
        let region = &self.callable()?.slots.get(i)?.region;
        let parent = region.content_parent();
        (parent != self.id).then(|| NodeRef::new(self.tree, parent))
    }

    /// The content nodes of slot `i`, in source order — the body nodes, for the
    /// standard environment shape.
    ///
    /// `None` for a non-callable and for an out-of-range index; the by-name form
    /// [`slot_content_nodes_named`](NodeRef::slot_content_nodes_named) reports those
    /// category mismatches as errors instead.
    pub fn slot_content_nodes(&self, i: usize) -> Option<NodeSlice<'t, L, A>> {
        self.region_content(&self.callable()?.slots.get(i)?.region)
    }

    /// The content nodes of the slot named `name`, per its
    /// [`ParsedSlot`](super::ParsedSlot) record —
    /// [`slot_content_nodes`](NodeRef::slot_content_nodes) by name.
    ///
    /// Unlike the argument family there is no `Option` layer: a recorded slot always
    /// has content nodes, possibly zero of them, so an `Ok` slice may be empty and
    /// there is no "declared but absent" state.
    ///
    /// # Errors
    ///
    /// `Err` is a category mismatch: the node is not a callable, or it has no slot
    /// named `name` (the misspelling trap).
    pub fn slot_content_nodes_named(
        &self,
        name: &str,
    ) -> Result<NodeSlice<'t, L, A>, NamedAccessError> {
        let callable = self.callable().ok_or(NamedAccessError::NotACallable)?;
        let slot = callable
            .slots
            .get_named(name)
            .ok_or_else(|| NamedAccessError::UnknownSlotName { name: name.into() })?;
        Ok(NodeSlice::new(self.tree, slot.region.content_range()))
    }

    /// The content nodes of the **body slot**, in source order: the body of an
    /// environment-shaped callable.
    ///
    /// The body is the first slot whose ext reports
    /// [`is_body()`](BodySlotExt::is_body). The method is available where the
    /// language's [`SlotExt`](crate::core::NodeExtTypes::SlotExt) implements
    /// [`BodySlotExt`]; for a language without slot exts every slot reports body, so
    /// this is the first slot.
    ///
    /// The selection looks at the ext alone, and deliberately not also at the slot's
    /// [`SlotRole`](super::SlotRole): a framework that marks an `Attached` or `Hidden`
    /// slot as its body must not find that slot silently unreachable here.
    ///
    /// The body's wrapper node, when one exists, is
    /// [`slot_content_parent`](NodeRef::slot_content_parent) at the same slot index.
    pub fn body(&self) -> Option<NodeSlice<'t, L, A>>
    where
        SlotExt<L>: BodySlotExt,
    {
        let slot = self.callable()?.slots.iter().find(|slot| slot.ext.is_body())?;
        self.region_content(&slot.region)
    }
}

/// A category mismatch reported by the by-name accessors: the node is not a callable,
/// or the name matches nothing the callable declares.
///
/// Returned by [`NodeRef::argument_nodes_named`],
/// [`NodeRef::argument_content_nodes_named`], and
/// [`NodeRef::slot_content_nodes_named`].
///
/// These accessors report an error rather than answering `None`, because a `None` on a
/// misspelled name gives the call site nothing cheap to distinguish it by, and names
/// are the access form the API recommends. `Ok(None)` stays reserved for the argument
/// family's "declared but absent". None of these accessors ever panics.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NamedAccessError {
    /// The node is not a `Callable` — it has no arguments or slots to access.
    NotACallable,
    /// The name matches none of the callable's declared arguments (the names on
    /// its spec's [`ArgumentSpec`](crate::core::specs::ArgumentSpec)s).
    UnknownArgumentName {
        /// The unmatched name, as queried.
        name: Box<str>,
    },
    /// The name matches none of the callable's recorded slots
    /// ([`ParsedSlot`](super::ParsedSlot) names).
    UnknownSlotName {
        /// The unmatched name, as queried.
        name: Box<str>,
    },
}

impl fmt::Display for NamedAccessError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NamedAccessError::NotACallable => {
                write!(f, "the node is not a callable (no arguments or slots)")
            }
            NamedAccessError::UnknownArgumentName { name } => {
                write!(f, "no argument named ‘{name}’ among the declared arguments")
            }
            NamedAccessError::UnknownSlotName { name } => {
                write!(f, "no slot named ‘{name}’ on the callable")
            }
        }
    }
}

impl core::error::Error for NamedAccessError {}

/// Iterator over a node's descendants in document order (see
/// [`NodeRef::descendants`]; preorder depth-first via an explicit stack).
pub struct Descendants<'t, L: Lang, A = ()> {
    tree: &'t NodeTree<L, A>,
    /// Nodes not yet yielded, next on top; a yielded node's children are pushed in
    /// reverse so the leftmost comes off first.
    stack: Vec<u32>,
}

fn push_children_reversed<L: Lang>(stack: &mut Vec<u32>, data: &NodeData<L>) {
    for i in data.children.clone().rev() {
        stack.push(i);
    }
}

impl<'t, L: Lang, A> Iterator for Descendants<'t, L, A> {
    type Item = NodeRef<'t, L, A>;

    fn next(&mut self) -> Option<NodeRef<'t, L, A>> {
        let index = self.stack.pop()?;
        let node = self.tree.node(self.tree.make_id(index));
        push_children_reversed(&mut self.stack, &self.tree.nodes()[index as usize]);
        Some(node)
    }
}

impl<L: Lang, A> fmt::Debug for Descendants<'_, L, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Descendants").field("pending", &self.stack.len()).finish()
    }
}

// Manual impls: `NodeRef` is Copy regardless of `L` (it stores only a borrow and an id).

impl<L: Lang, A> Clone for NodeRef<'_, L, A> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<L: Lang, A> Copy for NodeRef<'_, L, A> {}

impl<L: Lang, A> fmt::Debug for NodeRef<'_, L, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NodeRef")
            .field("id", &self.id)
            .field("kind", self.kind())
            .field("span", self.span())
            .field("children", &self.data().children)
            .finish()
    }
}