ctb_formats_dcstring/navigator/
arena.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Syntax arena, byte spans, binary payload references, and frame stubs.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use super::{
30    BinaryChecksum, Cow, DCMM_MAGIC, DcCharExt, DcDocumentNavigator,
31    DcExpressionEvaluator, DcForgivingDefault, DcMixedDecode, DcMstr,
32    DcMstring, DcProjectionContext, DcProjectionPolicy, DcRole, DcStr,
33    DcString, DiagnosticAction, Digest, Range, Read, Seek, SeekFrom,
34    SharedValueContext, SyntaxDiagnostic, SyntaxRuleResolver, dc_char_dctf_len,
35    default_syntax_resolver,
36};
37
38/// Byte span in a source buffer or on-disk file.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40pub struct DcByteSpan {
41    /// Inclusive start byte offset.
42    pub start: u64,
43    /// Exclusive end byte offset.
44    pub end: u64,
45}
46
47impl DcByteSpan {
48    /// Creates a new byte span.
49    #[must_use]
50    pub const fn new(start: u64, end: u64) -> Self {
51        Self { start, end }
52    }
53
54    /// Returns the length in bytes.
55    #[must_use]
56    pub const fn len(&self) -> u64 {
57        self.end.saturating_sub(self.start)
58    }
59
60    /// Returns true if the span is empty.
61    #[must_use]
62    pub const fn is_empty(&self) -> bool {
63        self.end <= self.start
64    }
65
66    /// Converts to a `Range<usize>` for indexing in-memory buffers.
67    pub fn to_usize_range(self) -> Result<Range<usize>> {
68        Ok(usize::try_from(self.start)?..usize::try_from(self.end)?)
69    }
70}
71
72/// Reference to a binary payload inside a parsed Dc document.
73///
74/// For in-memory `.dcmm` buffers, payloads are borrowed zero-copy slices.
75/// For seekable on-disk `.dcmm` files, large payloads remain lazy file offsets
76/// (`FileSpan`) so multi-gigabyte binary regions are not read into RAM during
77/// parsing or tree navigation.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum BinaryPayloadRef<'a> {
80    /// Nonresident bytes identified by a caller-supplied encoding source.
81    /// This handle is never serialized; the encoder writes its actual bytes.
82    Source { source_id: u64, len: u64 },
83    /// Zero-copy slice borrowed from an in-memory `.dcmm` buffer.
84    Borrowed(&'a [u8]),
85    /// Decoded bytes from base64 `DcStr` or small inline payload ($\le 4\text{ KiB}$).
86    Inline(Vec<u8>),
87    /// Lazy file byte span inside an on-disk `.dcmm` file.
88    FileSpan {
89        /// Byte offset of the raw payload within the file.
90        file_offset: u64,
91        /// Length of the raw payload in bytes.
92        len: u64,
93        /// Expected encapsulation checksum, retained for deferred reads.
94        checksum: Option<BinaryChecksum>,
95        /// Caller-selected action for a checksum mismatch.
96        checksum_action: DiagnosticAction,
97    },
98}
99
100impl<'a> BinaryPayloadRef<'a> {
101    /// Returns the payload byte length.
102    #[must_use]
103    #[expect(
104        clippy::expect_used,
105        reason = "In-memory byte slice lengths fit within u64 on all supported platforms"
106    )]
107    pub fn len(&self) -> u64 {
108        match self {
109            Self::Borrowed(slice) => u64::try_from(slice.len())
110                .expect("Borrowed slice length fits in u64"),
111            Self::Inline(bytes) => u64::try_from(bytes.len())
112                .expect("Inline byte buffer length fits in u64"),
113            Self::FileSpan { len, .. } | Self::Source { len, .. } => *len,
114        }
115    }
116
117    /// Returns true if the payload has zero bytes.
118    #[must_use]
119    pub fn is_empty(&self) -> bool {
120        self.len() == 0
121    }
122
123    /// Returns the in-memory bytes if already resident (`Borrowed` or `Inline`).
124    #[must_use]
125    pub fn as_resident_bytes(&self) -> Option<&[u8]> {
126        match self {
127            Self::Borrowed(slice) => Some(slice),
128            Self::Inline(bytes) => Some(bytes.as_slice()),
129            Self::FileSpan { .. } | Self::Source { .. } => None,
130        }
131    }
132
133    /// Materializes the payload bytes, reading from `reader` if this is a `FileSpan`.
134    pub fn materialize<R: Read + Seek>(
135        &self,
136        reader: Option<&mut R>,
137    ) -> Result<Cow<'a, [u8]>> {
138        match self {
139            Self::Source { .. } => {
140                bail!("External binary data requires its encoding source")
141            }
142            Self::Borrowed(slice) => Ok(Cow::Borrowed(slice)),
143            Self::Inline(bytes) => Ok(Cow::Owned(bytes.clone())),
144            Self::FileSpan {
145                file_offset,
146                len,
147                checksum,
148                checksum_action,
149            } => {
150                let rdr = reader.context(
151                    "Cannot materialize on-disk FileSpan without a seekable reader",
152                )?;
153                let len_usize = usize::try_from(*len)
154                    .context("Binary FileSpan length exceeds usize")?;
155                let saved_pos = rdr.stream_position()?;
156                let result = (|| -> Result<Cow<'a, [u8]>> {
157                    rdr.seek(SeekFrom::Start(*file_offset))?;
158                    let mut buf = Vec::new();
159                    buf.try_reserve_exact(len_usize)?;
160                    buf.resize(len_usize, 0);
161                    rdr.read_exact(&mut buf)
162                        .context("Failed to read BinaryPayloadRef::FileSpan")?;
163                    if let Some(checksum) = checksum {
164                        if !checksum
165                            .matches_reader(&mut buf.as_slice(), *len)?
166                        {
167                            DcProjectionPolicy::strict().handle(
168                                *checksum_action,
169                                "Encapsulation checksum mismatch",
170                            )?;
171                        }
172                    }
173                    Ok(Cow::Owned(buf))
174                })();
175                rdr.seek(SeekFrom::Start(saved_pos)).context(
176                    "Failed to restore binary payload reader position",
177                )?;
178                result
179            }
180        }
181    }
182
183    /// Materializes in-memory bytes without requiring an on-disk reader.
184    ///
185    /// # Errors
186    /// Returns an error if the payload is an unmaterialized on-disk `FileSpan`.
187    pub fn materialize_bytes(&self) -> Result<Cow<'a, [u8]>> {
188        self.materialize(None::<&mut std::io::Cursor<&[u8]>>)
189    }
190}
191
192/// Resolver capable of materializing lazy [`BinaryPayloadRef::FileSpan`] payloads
193/// from an underlying seekable file during CST projection.
194pub trait DcBinaryResolver: std::fmt::Debug {
195    /// Materializes the raw bytes of `payload`, reading from the backing stream if lazy.
196    fn materialize_binary<'a>(
197        &mut self,
198        payload: &BinaryPayloadRef<'a>,
199    ) -> Result<Cow<'a, [u8]>>;
200}
201
202/// Index of a node inside a [`DcSyntaxArena`].
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
204pub struct NodeId(pub usize);
205
206/// Syntax node kind in a [`DcSyntaxArena`].
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub enum DcSyntaxKind<'a> {
209    /// Delimited container (`opener .. closer`, with optional header and trailing suffix).
210    Container {
211        opener: DcChar,
212        closer: DcChar,
213        header: Vec<NodeId>,
214        children: Vec<NodeId>,
215        trailing: Vec<NodeId>,
216        unclosed: bool,
217    },
218    /// Prefix-tagged or operator construct (`:~ <arg1> <arg2> ...`).
219    Tagged { tag: DcChar, args: Vec<NodeId> },
220    /// Binary encapsulation (`203 [type]? [number]? [checksum]? ... 204`).
221    Binary {
222        data_type: Option<DcString>,
223        checksum_format: Option<DcChar>,
224        payload: BinaryPayloadRef<'a>,
225    },
226    /// Standalone Document Character token (e.g. boolean `517`/`518`, `316`, `513`, enum tag).
227    Atom(DcChar),
228    /// Malformed or garbled span isolated during resilient recovery.
229    Malformed {
230        raw_tokens: Vec<DcChar>,
231        message: String,
232    },
233}
234
235/// A span-annotated CST node inside a [`DcSyntaxArena`].
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct DcSyntaxNode<'a> {
238    /// Source byte span of this node.
239    pub span: DcByteSpan,
240    /// Syntactic kind and payload.
241    pub kind: DcSyntaxKind<'a>,
242    /// True if this node is an `Atom` that was escaped by `Dc 255` (`Escape`).
243    pub escaped: bool,
244}
245
246impl DcSyntaxNode<'_> {
247    /// Returns the leading semantic token (`opener`, `tag`, or `Atom` value) of this node.
248    #[must_use]
249    pub fn semantic_token(&self) -> Option<u128> {
250        let token = match &self.kind {
251            DcSyntaxKind::Container { opener, .. } => opener,
252            DcSyntaxKind::Tagged { tag, .. } => tag,
253            DcSyntaxKind::Atom(token) => token,
254            _ => return None,
255        };
256        Some(token.to_u128())
257    }
258
259    /// Returns `(head_dc, child_slice)` for a `Container` or `Tagged` node.
260    #[must_use]
261    pub fn head_and_children(&self) -> Option<(DcChar, &[NodeId])> {
262        match &self.kind {
263            DcSyntaxKind::Container {
264                opener, children, ..
265            } => Some((*opener, children.as_slice())),
266            DcSyntaxKind::Tagged { tag, args } => {
267                Some((*tag, args.as_slice()))
268            }
269            _ => None,
270        }
271    }
272
273    /// Returns true if this container represents a leaf value construct using `resolver`.
274    #[must_use]
275    pub fn is_leaf_value_container_with(
276        &self,
277        resolver: &dyn SyntaxRuleResolver,
278    ) -> bool {
279        match &self.kind {
280            DcSyntaxKind::Container { opener, .. } => {
281                opener.fills_role_with(DcRole::BeginLiteral, resolver)
282                    || opener.fills_role_with(DcRole::BeginIdentifier, resolver)
283                    || opener.fills_role_with(DcRole::BeginNumber, resolver)
284            }
285            _ => false,
286        }
287    }
288
289    /// Returns true if this node is a structural (non-leaf) `Container` using `resolver`.
290    #[must_use]
291    pub fn is_structural_container_with(
292        &self,
293        resolver: &dyn SyntaxRuleResolver,
294    ) -> bool {
295        matches!(self.kind, DcSyntaxKind::Container { .. })
296            && !self.is_leaf_value_container_with(resolver)
297    }
298
299    /// Recognizes alternative-representation wrappers and equivalent tokens.
300    #[must_use]
301    pub fn is_representation_set(&self) -> bool {
302        self.semantic_token().is_some_and(|token| {
303            default_syntax_resolver().is_representation_set(token)
304        })
305    }
306
307    /// Recognizes wrapper markers, list headers, and representation separators.
308    #[must_use]
309    pub fn is_representation_scaffolding(&self) -> bool {
310        self.semantic_token().is_some_and(|token| {
311            let resolver = default_syntax_resolver();
312            resolver.is_representation_set(token)
313                || resolver.is_representation_header_or_separator(token)
314        })
315    }
316
317    /// Returns true if this node is an `Atom` that was escaped by `Dc 255` (`Escape`),
318    /// stripping one layer of syntactic role at the enclosing level.
319    #[must_use]
320    pub fn is_escaped_atom(&self) -> bool {
321        match self.kind {
322            DcSyntaxKind::Atom(ch) => {
323                self.escaped
324                    || self.span.len() >= dc_char_dctf_len(ch).saturating_add(4)
325            }
326            _ => false,
327        }
328    }
329
330    /// Returns the child node IDs if this node is a container or tagged construct.
331    #[must_use]
332    pub fn children(&self) -> &[NodeId] {
333        match &self.kind {
334            DcSyntaxKind::Container { children, .. } => children,
335            DcSyntaxKind::Tagged { args, .. } => args,
336            _ => &[],
337        }
338    }
339}
340
341/// Flat, reusable arena holding parsed [`DcSyntaxNode`]s for a frame or document.
342///
343/// Calling [`DcSyntaxArena::clear`] resets the arena between records while
344/// retaining allocated capacity, achieving $O(1)$ steady-state memory usage
345/// when streaming across multi-gigabyte documents or journals.
346#[derive(Debug, Clone, Default)]
347pub struct DcSyntaxArena<'a> {
348    nodes: Vec<DcSyntaxNode<'a>>,
349    roots: Vec<NodeId>,
350    diagnostics: Vec<SyntaxDiagnostic>,
351}
352
353impl<'a> DcSyntaxArena<'a> {
354    /// Creates an empty syntax arena.
355    #[must_use]
356    pub fn new() -> Self {
357        Self::default()
358    }
359
360    /// Resets the arena for reuse without releasing heap capacity.
361    pub fn clear(&mut self) {
362        self.nodes.clear();
363        self.roots.clear();
364        self.diagnostics.clear();
365    }
366
367    /// Allocates a node in the arena and returns its [`NodeId`].
368    pub fn alloc(
369        &mut self,
370        span: DcByteSpan,
371        kind: DcSyntaxKind<'a>,
372    ) -> NodeId {
373        let id = NodeId(self.nodes.len());
374        self.nodes.push(DcSyntaxNode {
375            span,
376            kind,
377            escaped: false,
378        });
379        id
380    }
381
382    /// Allocates an escaped atom node in the arena and returns its [`NodeId`].
383    pub fn alloc_escaped_atom(
384        &mut self,
385        span: DcByteSpan,
386        ch: DcChar,
387    ) -> NodeId {
388        let id = NodeId(self.nodes.len());
389        self.nodes.push(DcSyntaxNode {
390            span,
391            kind: DcSyntaxKind::Atom(ch),
392            escaped: true,
393        });
394        id
395    }
396
397    fn alloc_atoms(&mut self, span: DcByteSpan, chars: &[DcChar]) -> Vec<NodeId> {
398        chars
399            .iter()
400            .copied()
401            .map(|ch| self.alloc(span, DcSyntaxKind::Atom(ch)))
402            .collect()
403    }
404
405    fn alloc_mstr_atoms(
406        &mut self,
407        span: DcByteSpan,
408        mstr: &DcMstr,
409    ) -> Vec<NodeId> {
410        let mut children = Vec::new();
411        for chunk in mstr.chunks() {
412            if let Some(text) = chunk.as_text() {
413                for ch in text.chars() {
414                    children.push(self.alloc(span, DcSyntaxKind::Atom(ch)));
415                }
416            }
417        }
418        children
419    }
420
421    fn collect_atoms(&self, ids: &[NodeId]) -> Option<Vec<DcChar>> {
422        let mut out = Vec::with_capacity(ids.len());
423        for &id in ids {
424            let DcSyntaxKind::Atom(ch) = self.get(id)?.kind else {
425                return None;
426            };
427            out.push(ch);
428        }
429        Some(out)
430    }
431
432    fn collect_mstring(&self, ids: &[NodeId]) -> Option<DcMstring> {
433        let mut out = DcMstring::new();
434        for &id in ids {
435            let DcSyntaxKind::Atom(ch) = self.get(id)?.kind else {
436                return None;
437            };
438            out.push_char(ch);
439        }
440        Some(out)
441    }
442
443    /// Allocates a framed literal container node (`Dc 260..261`).
444    pub fn alloc_literal(
445        &mut self,
446        span: DcByteSpan,
447        opener: DcChar,
448        closer: DcChar,
449        type_header: &[DcChar],
450        decoded: &DcMstr,
451    ) -> NodeId {
452        let header = self.alloc_atoms(span, type_header);
453        let children = self.alloc_mstr_atoms(span, decoded);
454        self.alloc(
455            span,
456            DcSyntaxKind::Container {
457                opener,
458                closer,
459                header,
460                children,
461                trailing: Vec::new(),
462                unclosed: false,
463            },
464        )
465    }
466
467    /// Allocates a framed identifier container node (`Dc 270..271`).
468    pub fn alloc_identifier(
469        &mut self,
470        span: DcByteSpan,
471        opener: DcChar,
472        closer: DcChar,
473        name: &DcMstr,
474    ) -> NodeId {
475        let children = self.alloc_mstr_atoms(span, name);
476        self.alloc(
477            span,
478            DcSyntaxKind::Container {
479                opener,
480                closer,
481                header: Vec::new(),
482                children,
483                trailing: Vec::new(),
484                unclosed: false,
485            },
486        )
487    }
488
489    /// Allocates a framed number container node (`Dc 6..7`).
490    pub fn alloc_number(
491        &mut self,
492        span: DcByteSpan,
493        opener: DcChar,
494        closer: DcChar,
495        format: DcChar,
496        digits: &[DcChar],
497    ) -> NodeId {
498        let header = vec![self.alloc(span, DcSyntaxKind::Atom(format))];
499        let children = self.alloc_atoms(span, digits);
500        self.alloc(
501            span,
502            DcSyntaxKind::Container {
503                opener,
504                closer,
505                header,
506                children,
507                trailing: Vec::new(),
508                unclosed: false,
509            },
510        )
511    }
512
513    /// Returns true if `id` is a `Container` whose opener fills `role` using `resolver`.
514    #[must_use]
515    pub fn has_opener_role_with_resolver(
516        &self,
517        id: NodeId,
518        role: DcRole,
519        resolver: &dyn SyntaxRuleResolver,
520    ) -> bool {
521        matches!(
522            self.get(id).map(|n| &n.kind),
523            Some(DcSyntaxKind::Container { opener, .. })
524                if opener.fills_role_with(role, resolver)
525        )
526    }
527
528    /// Returns true if `id` is a framed literal container (`Dc 260..261`) using `resolver`.
529    #[must_use]
530    pub fn is_literal_with_resolver(
531        &self,
532        id: NodeId,
533        resolver: &dyn SyntaxRuleResolver,
534    ) -> bool {
535        self.has_opener_role_with_resolver(id, DcRole::BeginLiteral, resolver)
536    }
537
538    /// Decodes a framed literal container (`Dc 260..261`) into `(type_header, decoded)` using `resolver`.
539    #[must_use]
540    pub fn decode_literal_with_resolver(
541        &self,
542        id: NodeId,
543        resolver: &dyn SyntaxRuleResolver,
544    ) -> Option<(Vec<DcChar>, DcMstring)> {
545        let DcSyntaxKind::Container {
546            opener,
547            header,
548            children,
549            ..
550        } = &self.get(id)?.kind
551        else {
552            return None;
553        };
554        if !opener.fills_role_with(DcRole::BeginLiteral, resolver) {
555            return None;
556        }
557        Some((self.collect_atoms(header)?, self.collect_mstring(children)?))
558    }
559
560    /// Returns true if `id` is a framed identifier container (`Dc 270..271`) using `resolver`.
561    #[must_use]
562    pub fn is_identifier_with_resolver(
563        &self,
564        id: NodeId,
565        resolver: &dyn SyntaxRuleResolver,
566    ) -> bool {
567        self.has_opener_role_with_resolver(id, DcRole::BeginIdentifier, resolver)
568    }
569
570    /// Decodes a framed identifier container (`Dc 270..271`) into its `DcMstring` name using `resolver`.
571    #[must_use]
572    pub fn decode_identifier_with_resolver(
573        &self,
574        id: NodeId,
575        resolver: &dyn SyntaxRuleResolver,
576    ) -> Option<DcMstring> {
577        let DcSyntaxKind::Container {
578            opener, children, ..
579        } = &self.get(id)?.kind
580        else {
581            return None;
582        };
583        if !opener.fills_role_with(DcRole::BeginIdentifier, resolver) {
584            return None;
585        }
586        self.collect_mstring(children)
587    }
588
589    /// Returns true if `id` is a framed number container (`Dc 6..7`) using `resolver`.
590    #[must_use]
591    pub fn is_number_with_resolver(
592        &self,
593        id: NodeId,
594        resolver: &dyn SyntaxRuleResolver,
595    ) -> bool {
596        self.has_opener_role_with_resolver(id, DcRole::BeginNumber, resolver)
597    }
598
599    /// Decodes a framed number container (`Dc 6..7`) into `(format, digits)` using `resolver`.
600    #[must_use]
601    pub fn decode_number_with_resolver(
602        &self,
603        id: NodeId,
604        resolver: &dyn SyntaxRuleResolver,
605    ) -> Option<(DcChar, Vec<DcChar>)> {
606        let DcSyntaxKind::Container {
607            opener,
608            header,
609            children,
610            ..
611        } = &self.get(id)?.kind
612        else {
613            return None;
614        };
615        if !opener.fills_role_with(DcRole::BeginNumber, resolver) {
616            return None;
617        }
618        let (fmt_id, digit_ids) = if let Some(&fmt_id) = header.first() {
619            (fmt_id, children.as_slice())
620        } else {
621            let (&fmt_id, rest) = children.split_first()?;
622            (fmt_id, rest)
623        };
624        let DcSyntaxKind::Atom(fmt) = self.get(fmt_id)?.kind else {
625            return None;
626        };
627        Some((fmt, self.collect_atoms(digit_ids)?))
628    }
629
630    /// Decodes an assignment construct (`Dc 269` or `Dc 268`) into `(ident_name, value_node_id)` using `resolver`.
631    #[must_use]
632    pub fn decode_assignment_with_resolver(
633        &self,
634        id: NodeId,
635        resolver: &dyn SyntaxRuleResolver,
636    ) -> Option<(DcMstring, NodeId)> {
637        let DcSyntaxKind::Tagged { tag, args } = &self.get(id)?.kind else {
638            return None;
639        };
640        if !resolver.is_assignment_construct(tag.to_u128()) {
641            return None;
642        }
643        let [raw_ident_id, raw_val_id] = args.as_slice() else {
644            return None;
645        };
646        let unwrap_param = |param_id: NodeId| -> NodeId {
647            if let Some(DcSyntaxKind::Container {
648                opener, children, ..
649            }) = self.get(param_id).map(|n| &n.kind)
650                && opener.fills_role_with(DcRole::BeginParameter, resolver)
651                && let [single] = children.as_slice()
652            {
653                *single
654            } else {
655                param_id
656            }
657        };
658        let ident_id = unwrap_param(*raw_ident_id);
659        let val_id = unwrap_param(*raw_val_id);
660        let ident = self.decode_identifier_with_resolver(ident_id, resolver)?;
661        Some((ident, val_id))
662    }
663
664    /// Appends a root node ID.
665    pub fn push_root(&mut self, id: NodeId) {
666        self.roots.push(id);
667    }
668
669    /// Returns the top-level root nodes in the arena.
670    #[must_use]
671    pub fn roots(&self) -> &[NodeId] {
672        &self.roots
673    }
674
675    /// Borrows a node by its [`NodeId`].
676    #[must_use]
677    pub fn get(&self, id: NodeId) -> Option<&DcSyntaxNode<'a>> {
678        self.nodes.get(id.0)
679    }
680
681    /// Borrows a node by its [`NodeId`] (alias for [`Self::get`]).
682    #[must_use]
683    pub fn node(&self, id: NodeId) -> Option<&DcSyntaxNode<'a>> {
684        self.get(id)
685    }
686
687    /// Returns all nodes in the arena.
688    #[must_use]
689    pub fn nodes(&self) -> &[DcSyntaxNode<'a>] {
690        &self.nodes
691    }
692
693    /// Records a syntax diagnostic encountered while parsing.
694    pub fn push_diagnostic(&mut self, diagnostic: SyntaxDiagnostic) {
695        self.diagnostics.push(diagnostic);
696    }
697
698    /// Returns all diagnostics recorded in this arena.
699    #[must_use]
700    pub fn diagnostics(&self) -> &[SyntaxDiagnostic] {
701        &self.diagnostics
702    }
703
704    /// Splits a sequence of child [`NodeId`]s on [`DC_LIST_ELEMENT_SEPARATOR`] (`Dc 312`).
705    #[must_use]
706    pub fn split_operands(&self, nodes: &[NodeId]) -> Vec<Vec<NodeId>> {
707        self.split_operands_with_resolver(
708            nodes,
709            default_syntax_resolver().as_ref(),
710        )
711    }
712
713    /// Splits a sequence of child [`NodeId`]s on [`DC_LIST_ELEMENT_SEPARATOR`] using the provided resolver.
714    #[must_use]
715    pub fn split_operands_with_resolver(
716        &self,
717        nodes: &[NodeId],
718        resolver: &dyn SyntaxRuleResolver,
719    ) -> Vec<Vec<NodeId>> {
720        let mut result = Vec::new();
721        let mut current = Vec::new();
722        for &id in nodes {
723            if self.get(id).is_some_and(|n| {
724                !n.is_escaped_atom()
725                    && matches!(
726                        n.kind,
727                        DcSyntaxKind::Atom(ch)
728                            if ch.fills_role_with(DcRole::ListElementSeparator, resolver)
729                    )
730            }) {
731                result.push(std::mem::take(&mut current));
732            } else {
733                current.push(id);
734            }
735        }
736        result.push(current);
737        result
738    }
739
740    /// Extracts operands for each entry in a key-value map container using the
741    /// provided [`SyntaxRuleResolver`].
742    pub fn extract_kv_map_operand_entries_with_resolver(
743        &self,
744        id: NodeId,
745        require_object_headers: bool,
746        resolver: &dyn SyntaxRuleResolver,
747    ) -> Result<(DcChar, Vec<NodeId>, Vec<(Vec<NodeId>, Vec<NodeId>)>)> {
748        let node = self.get(id).context("NodeId must exist in arena")?;
749        let DcSyntaxKind::Container {
750            opener,
751            children,
752            unclosed,
753            ..
754        } = &node.kind
755        else {
756            bail!("Expected key-value map container, found {:?}", node.kind);
757        };
758        ensure!(!*unclosed, "Unclosed key-value map container ({opener})");
759        let is_pairs = opener.fills_role_with(DcRole::BeginKvMap, resolver);
760        let is_legacy =
761            opener.fills_role_with(DcRole::BeginLegacyKvMap, resolver);
762        ensure!(
763            is_pairs || is_legacy,
764            "Expected map container (Dc 559 or Dc 313), found opener {opener}"
765        );
766        let header =
767            children.get(..2).context("Missing map type declarations")?;
768        if require_object_headers {
769            ensure!(
770                header.iter().all(|&child| {
771                    self.get(child).is_some_and(
772                        |cn| matches!(cn.kind, DcSyntaxKind::Atom(ch) if ch.fills_role_with(DcRole::TypeAny, resolver)),
773                    )
774                }),
775                "Source-backed typed map editing requires uncounted Object/Object headers"
776            );
777        } else {
778            ensure!(
779                header.iter().all(|&child| {
780                    self.get(child).is_some_and(|cn| {
781                        matches!(
782                            cn.kind,
783                            DcSyntaxKind::Atom(ch)
784                                if ch.fills_role_with(DcRole::TypeAny, resolver)
785                                    || ch.fills_role_with(DcRole::TypeToken, resolver)
786                        )
787                    })
788                }),
789                "Missing or invalid map type header tokens"
790            );
791        }
792        let body = children.get(2..).context("Missing map body")?;
793        let mut entries = Vec::new();
794        if is_legacy {
795            if !body.is_empty() {
796                let operands =
797                    self.split_operands_with_resolver(body, resolver);
798                for pair in operands.chunks(2) {
799                    let [key, value] = pair else {
800                        bail!("Unpaired legacy map operand");
801                    };
802                    ensure!(
803                        !key.is_empty() && !value.is_empty(),
804                        "Empty legacy map operand"
805                    );
806                    entries.push((key.clone(), value.clone()));
807                }
808            }
809        } else {
810            for &pair_id in body {
811                let pair_node = self
812                    .get(pair_id)
813                    .context("Pair NodeId must exist in arena")?;
814                let (pair_opener, pair_children, pair_unclosed) =
815                    match &pair_node.kind {
816                        DcSyntaxKind::Container {
817                            opener,
818                            children,
819                            unclosed,
820                            ..
821                        } => (*opener, children, *unclosed),
822                        other => bail!(
823                            "Expected explicitly framed map entry (Dc 514), found {other:?}"
824                        ),
825                    };
826                ensure!(
827                    pair_opener.fills_role_with(DcRole::BeginKvPair, resolver)
828                        && !pair_unclosed,
829                    "Expected explicitly framed map entry (Dc 514..515)"
830                );
831                let operands =
832                    self.split_operands_with_resolver(pair_children, resolver);
833                let [key, value] = operands.as_slice() else {
834                    bail!("Expected two pair operands");
835                };
836                ensure!(
837                    !key.is_empty() && !value.is_empty(),
838                    "Empty pair operand"
839                );
840                entries.push((key.clone(), value.clone()));
841            }
842        }
843        Ok((*opener, header.to_vec(), entries))
844    }
845
846    /// Extracts single-node `(key_id, value_id)` pairs from a map container
847    /// (`Dc 559..560` or `Dc 313..314`) using the provided [`SyntaxRuleResolver`].
848    pub fn extract_kv_map_node_pairs_with_resolver(
849        &self,
850        id: NodeId,
851        resolver: &dyn SyntaxRuleResolver,
852    ) -> Result<(DcChar, Vec<(NodeId, NodeId)>)> {
853        let (opener, _, operand_entries) = self
854            .extract_kv_map_operand_entries_with_resolver(
855                id, false, resolver,
856            )?;
857        let mut pairs = Vec::with_capacity(operand_entries.len());
858        for (key_nodes, val_nodes) in operand_entries {
859            let [k_id] = key_nodes.as_slice() else {
860                bail!(
861                    "Expected single key node in map entry, found {}",
862                    key_nodes.len()
863                );
864            };
865            let [v_id] = val_nodes.as_slice() else {
866                bail!(
867                    "Expected single value node in map entry, found {}",
868                    val_nodes.len()
869                );
870            };
871            pairs.push((*k_id, *v_id));
872        }
873        Ok((opener, pairs))
874    }
875}
876
877/// Lightweight header summary attached to a [`DcFrameStub`] during shallow
878/// level navigation.
879#[derive(Debug, Clone, PartialEq, Eq, Default)]
880pub enum DcFrameHeaderInfo {
881    /// Standard frame or statement without specialized header metadata.
882    #[default]
883    None,
884    /// Container whose closer delimiter was produced by stream splicing.
885    SplicedCloser,
886    /// Binary encapsulation (`203..204`) with payload byte span and optional data type.
887    Binary {
888        data_type: Option<DcString>,
889        payload_span: Option<DcByteSpan>,
890        payload_len: u64,
891        checksum: Option<BinaryChecksum>,
892    },
893    /// Checksummed document section (`543..544` + `545` digest).
894    ChecksummedSection {
895        /// Optional leading `546` sequence identifier inside the section.
896        sequence_id: Option<u64>,
897        /// Byte span of the `543..544` body covered by the SHA-256 digest.
898        body_span: DcByteSpan,
899        /// True if the trailing `545` SHA-256 digest matched the body bytes.
900        digest_valid: bool,
901    },
902    /// Format representation (`511 [format] ... 512`).
903    FormatRepresentation { format: DcChar },
904    /// Spliced leaf container tokens (`260..261`, `270..271`, `6..7`).
905    SplicedTokens(Vec<DcChar>),
906    /// Character whose syntactic role at this level was escaped by `Dc 255`.
907    Escaped,
908}
909
910/// Lightweight descriptor for a single sibling frame or statement at the
911/// navigator's current tree depth, produced without allocating child AST nodes.
912#[derive(Debug, Clone, PartialEq, Eq)]
913pub struct DcFrameStub {
914    /// Leading Document Character of this frame or statement.
915    pub head_dc: DcChar,
916    /// Matching closing delimiter if this frame is a container.
917    pub closer_dc: Option<DcChar>,
918    /// Full byte span of the frame (including opener, closer, and any trailing suffix such as `545`).
919    pub outer_span: DcByteSpan,
920    /// Interior byte span (between opener and closer) that `enter_frame` drills into.
921    pub inner_span: Option<DcByteSpan>,
922    /// Lightweight header metadata (e.g., checksummed section verification or binary span).
923    pub header_info: DcFrameHeaderInfo,
924}
925
926impl DcFrameStub {
927    /// Returns true if this container frame reached the end of the active span
928    /// before its closing delimiter was encountered.
929    #[must_use]
930    pub const fn is_unclosed(&self) -> bool {
931        if matches!(self.header_info, DcFrameHeaderInfo::SplicedCloser) {
932            return false;
933        }
934        match (self.closer_dc, self.inner_span) {
935            (Some(_), Some(inner)) => inner.end >= self.outer_span.end,
936            _ => false,
937        }
938    }
939}
940
941impl<'a> DcDocumentNavigator<'a> {
942    fn from_bytes_with_policy(
943        bytes: &'a [u8],
944        policy: &DcProjectionPolicy,
945    ) -> Result<Self> {
946        if bytes.starts_with(&DCMM_MAGIC) {
947            Ok(Self::from_mstr_with_policy(
948                DcMstr::from_bytes_with_policy(bytes, policy)?,
949                policy,
950            ))
951        } else {
952            Ok(Self::from_dc_str_with_policy(
953                DcStr::from_bytes(bytes)?,
954                policy,
955            ))
956        }
957    }
958
959    /// Decodes a [`DcFrameStub`] into a typed Rust value `T` using the given
960    /// [`SharedValueContext`] and [`DcProjectionPolicy`], reusing the provided
961    /// [`DcSyntaxArena`].
962    pub fn decode_frame_with_arena<T: DcMixedDecode>(
963        &mut self,
964        stub: &DcFrameStub,
965        arena: &mut DcSyntaxArena<'a>,
966        context: Option<&SharedValueContext>,
967        policy: &DcProjectionPolicy,
968    ) -> Result<T> {
969        let resolver = self.effective_resolver();
970        let root_id = self.expand_frame(stub, arena, policy)?;
971        let (result, projection_diagnostics) = {
972            let mut ctx = DcProjectionContext::with_all_resolvers(
973                arena,
974                policy,
975                context,
976                Some(self),
977                Some(resolver.as_ref()),
978                None,
979            );
980            let res = T::decode_dc_node(&mut ctx, root_id);
981            (res, ctx.diagnostics().to_vec())
982        };
983        for diagnostic in projection_diagnostics {
984            arena.push_diagnostic(diagnostic);
985        }
986        result
987    }
988
989    /// Decodes a [`DcFrameStub`] into a typed Rust value `T` using the given
990    /// [`SharedValueContext`] and [`DcProjectionPolicy`].
991    pub fn decode_frame<T: DcMixedDecode>(
992        &mut self,
993        stub: &DcFrameStub,
994        context: Option<&SharedValueContext>,
995        policy: &DcProjectionPolicy,
996    ) -> Result<T> {
997        let mut arena = DcSyntaxArena::new();
998        self.decode_frame_with_arena(stub, &mut arena, context, policy)
999    }
1000
1001    /// Expands a [`DcFrameStub`] into a full CST inside the reusable [`DcSyntaxArena`].
1002    pub fn expand_frame(
1003        &mut self,
1004        stub: &DcFrameStub,
1005        arena: &mut DcSyntaxArena<'a>,
1006        policy: &DcProjectionPolicy,
1007    ) -> Result<NodeId> {
1008        let saved_cursor = self.cursor;
1009        let saved_span = self.active_span;
1010        self.active_span = stub.outer_span;
1011        self.cursor = stub.outer_span.start;
1012        let res = self.parse_node_into_arena(arena, policy);
1013        self.active_span = saved_span;
1014        let _ = self.seek_to_offset(saved_cursor.min(saved_span.end));
1015        res
1016    }
1017
1018    /// Parses all sibling constructs in the active span into `arena`.
1019    pub fn parse_document_into_arena(
1020        &mut self,
1021        arena: &mut DcSyntaxArena<'a>,
1022        policy: &DcProjectionPolicy,
1023    ) -> Result<()> {
1024        let mut raw_roots = Vec::new();
1025        let res = (|| -> Result<()> {
1026            self.ensure_root_pin_or_fallback(policy, None)?;
1027            while let Some(stub) = self.next_sibling_stub(policy)? {
1028                let resolver = self.effective_resolver();
1029                let id = self.build_arena_node_from_stub_with_resolver(
1030                    &stub,
1031                    arena,
1032                    policy,
1033                    resolver.as_ref(),
1034                )?;
1035                raw_roots.push(id);
1036                for diagnostic in self.diagnostics.drain(..) {
1037                    arena.push_diagnostic(diagnostic);
1038                }
1039            }
1040            Ok(())
1041        })();
1042        for diagnostic in self.diagnostics.drain(..) {
1043            arena.push_diagnostic(diagnostic);
1044        }
1045        res?;
1046        let resolver = self.effective_resolver();
1047        for id in Self::normalize_field_nodes_with_resolver(
1048            raw_roots,
1049            arena,
1050            resolver.as_ref(),
1051        ) {
1052            arena.push_root(id);
1053        }
1054        Ok(())
1055    }
1056
1057    /// Parses all sibling constructs in the active span into `arena` using the
1058    /// provided [`SyntaxRuleResolver`].
1059    pub fn parse_document_into_arena_with_resolver(
1060        &mut self,
1061        arena: &mut DcSyntaxArena<'a>,
1062        policy: &DcProjectionPolicy,
1063        resolver: &dyn SyntaxRuleResolver,
1064    ) -> Result<()> {
1065        let mut raw_roots = Vec::new();
1066        let res = (|| -> Result<()> {
1067            self.ensure_root_pin_or_fallback(policy, Some(resolver))?;
1068            loop {
1069                let pinned_arc = self.pinned_resolver.clone();
1070                let active_res: &dyn SyntaxRuleResolver =
1071                    if let Some(ref r) = pinned_arc {
1072                        r.as_ref()
1073                    } else {
1074                        resolver
1075                    };
1076                let Some(stub) =
1077                    self.next_sibling_stub_with_resolver(policy, active_res)?
1078                else {
1079                    break;
1080                };
1081                let post_pinned_arc = self.pinned_resolver.clone();
1082                let build_res: &dyn SyntaxRuleResolver =
1083                    if let Some(ref r) = post_pinned_arc {
1084                        r.as_ref()
1085                    } else {
1086                        resolver
1087                    };
1088                let id = self.build_arena_node_from_stub_with_resolver(
1089                    &stub, arena, policy, build_res,
1090                )?;
1091                raw_roots.push(id);
1092                for diagnostic in self.diagnostics.drain(..) {
1093                    arena.push_diagnostic(diagnostic);
1094                }
1095            }
1096            Ok(())
1097        })();
1098        for diagnostic in self.diagnostics.drain(..) {
1099            arena.push_diagnostic(diagnostic);
1100        }
1101        res?;
1102        let final_pinned = self.pinned_resolver.clone();
1103        let norm_res: &dyn SyntaxRuleResolver =
1104            if let Some(ref r) = final_pinned {
1105                r.as_ref()
1106            } else {
1107                resolver
1108            };
1109        for id in Self::normalize_field_nodes_with_resolver(
1110            raw_roots, arena, norm_res,
1111        ) {
1112            arena.push_root(id);
1113        }
1114        Ok(())
1115    }
1116
1117    /// Parses the next statement or container at the current cursor into `arena`.
1118    pub fn parse_node_into_arena(
1119        &mut self,
1120        arena: &mut DcSyntaxArena<'a>,
1121        policy: &DcProjectionPolicy,
1122    ) -> Result<NodeId> {
1123        let resolver = self.effective_resolver();
1124        let start = self.cursor;
1125        let res = (|| -> Result<NodeId> {
1126            let Some(stub) =
1127                self.next_sibling_stub_with_resolver(policy, resolver.as_ref())?
1128            else {
1129                bail!("Unexpected end of stream at offset {start}");
1130            };
1131            self.build_arena_node_from_stub_with_resolver(
1132                &stub,
1133                arena,
1134                policy,
1135                resolver.as_ref(),
1136            )
1137        })();
1138        for diagnostic in self.diagnostics.drain(..) {
1139            arena.push_diagnostic(diagnostic);
1140        }
1141        res
1142    }
1143
1144    pub(super) fn is_separator_with(
1145        ch: DcChar,
1146        resolver: &dyn SyntaxRuleResolver,
1147    ) -> bool {
1148        ch.fills_role_with(DcRole::ListElementSeparator, resolver)
1149            || ch.fills_role_with(DcRole::TypeAny, resolver)
1150            || ch.fills_role_with(DcRole::Escape, resolver)
1151            || ch.fills_role_with(DcRole::FilePathDelimiter, resolver)
1152    }
1153
1154    pub(super) fn is_primitive_value_atom_with(
1155        ch: DcChar,
1156        resolver: &dyn SyntaxRuleResolver,
1157    ) -> bool {
1158        ch.fills_role_with(DcRole::OptionalAbsent, resolver)
1159            || ch.fills_role_with(DcRole::BooleanTrue, resolver)
1160            || ch.fills_role_with(DcRole::BooleanFalse, resolver)
1161            || ch.fills_role_with(DcRole::Positive, resolver)
1162            || ch.fills_role_with(DcRole::Negative, resolver)
1163    }
1164
1165    pub(super) fn is_value_atom_with(
1166        ch: DcChar,
1167        resolver: &dyn SyntaxRuleResolver,
1168    ) -> bool {
1169        let code = ch.to_u128();
1170        Self::is_primitive_value_atom_with(ch, resolver)
1171            || ch.fills_role_with(DcRole::FilePathDelimiter, resolver)
1172            || (ctb_formats_dcdata::global_graph_layout::SYSTEM_REGION_START
1173                ..=ctb_formats_dcdata::global_graph_layout::SYSTEM_REGION_END)
1174                .contains(&code)
1175            || (resolver.matches_script(".Semantic", code)
1176                && !resolver.matches_script(".Semantic:fileflag", code)
1177                && resolver.framing_shape(code)
1178                    == ctb_formats_dcdata::syntax::FramingShape::Atom)
1179    }
1180
1181    pub(super) fn is_transparent_wrapper_tag_with(
1182        ch: DcChar,
1183        resolver: &dyn SyntaxRuleResolver,
1184    ) -> bool {
1185        ch.fills_role_with(DcRole::OptionalPresent, resolver)
1186            || resolver.is_representation_set(ch.to_u128())
1187    }
1188
1189    pub(super) fn is_pairable_kind_with(
1190        kind: &DcSyntaxKind<'_>,
1191        resolver: &dyn SyntaxRuleResolver,
1192    ) -> bool {
1193        match kind {
1194            DcSyntaxKind::Binary { .. } | DcSyntaxKind::Container { .. } => {
1195                true
1196            }
1197            DcSyntaxKind::Atom(ch) => {
1198                Self::is_primitive_value_atom_with(*ch, resolver)
1199            }
1200            DcSyntaxKind::Tagged { tag, .. } => {
1201                Self::is_transparent_wrapper_tag_with(*tag, resolver)
1202                    || resolver.is_assignment_construct(tag.to_u128())
1203            }
1204            DcSyntaxKind::Malformed { .. } => false,
1205        }
1206    }
1207
1208    pub(crate) fn normalize_field_nodes_with_resolver(
1209        nodes: Vec<NodeId>,
1210        arena: &mut DcSyntaxArena<'a>,
1211        resolver: &dyn SyntaxRuleResolver,
1212    ) -> Vec<NodeId> {
1213        if nodes.len() <= 1 {
1214            return nodes;
1215        }
1216
1217        // Right-to-left pairing of atom tags with their immediate values into Tagged nodes.
1218        let mut stack: Vec<NodeId> = Vec::with_capacity(nodes.len());
1219        for &node_id in nodes.iter().rev() {
1220            let Some(node) = arena.get(node_id) else {
1221                continue;
1222            };
1223            if let DcSyntaxKind::Atom(ch) = node.kind
1224                && !node.is_escaped_atom()
1225            {
1226                if !Self::is_separator_with(ch, resolver)
1227                    && !Self::is_value_atom_with(ch, resolver)
1228                {
1229                    if let Some(&top_id) = stack.last() {
1230                        if let Some(top_node) = arena.get(top_id)
1231                            && (Self::is_pairable_kind_with(
1232                                &top_node.kind,
1233                                resolver,
1234                            ) || top_node.is_escaped_atom())
1235                        {
1236                            let start = node.span.start;
1237                            let end = top_node.span.end;
1238                            stack.pop();
1239                            let span = DcByteSpan::new(start, start.max(end));
1240                            let tagged_id = arena.alloc(
1241                                span,
1242                                DcSyntaxKind::Tagged {
1243                                    tag: ch,
1244                                    args: vec![top_id],
1245                                },
1246                            );
1247                            stack.push(tagged_id);
1248                            continue;
1249                        }
1250                    }
1251                }
1252            }
1253            stack.push(node_id);
1254        }
1255        stack.reverse();
1256        stack
1257    }
1258
1259    /// Parses a single root node from `bytes` into `arena` using `policy`.
1260    pub fn parse_arena(
1261        bytes: &'a [u8],
1262        arena: &mut DcSyntaxArena<'a>,
1263        policy: &DcProjectionPolicy,
1264    ) -> Result<NodeId> {
1265        Self::parse_document_arena(bytes, arena, policy)?;
1266        arena
1267            .roots()
1268            .first()
1269            .copied()
1270            .ok_or_else(|| anyhow::anyhow!("Empty document or node stream"))
1271    }
1272
1273    /// Parses all document root nodes from `bytes` into `arena` using `policy` and `resolver`.
1274    pub fn parse_document_arena_with_resolver(
1275        bytes: &'a [u8],
1276        arena: &mut DcSyntaxArena<'a>,
1277        policy: &DcProjectionPolicy,
1278        resolver: &dyn SyntaxRuleResolver,
1279    ) -> Result<()> {
1280        let mut nav = Self::from_bytes_with_policy(bytes, policy)?;
1281        nav.parse_document_into_arena_with_resolver(arena, policy, resolver)
1282    }
1283
1284    /// Parses all document root nodes from `bytes` into `arena` using `policy`.
1285    pub fn parse_document_arena(
1286        bytes: &'a [u8],
1287        arena: &mut DcSyntaxArena<'a>,
1288        policy: &DcProjectionPolicy,
1289    ) -> Result<()> {
1290        let mut nav = Self::from_bytes_with_policy(bytes, policy)?;
1291        nav.parse_document_into_arena(arena, policy)
1292    }
1293
1294    pub(super) fn build_arena_node_from_stub_with_resolver(
1295        &mut self,
1296        root_stub: &DcFrameStub,
1297        arena: &mut DcSyntaxArena<'a>,
1298        policy: &DcProjectionPolicy,
1299        resolver: &dyn SyntaxRuleResolver,
1300    ) -> Result<NodeId> {
1301        enum ArenaBuildFrame {
1302            Infix {
1303                outer_span: DcByteSpan,
1304                tag: DcChar,
1305                lhs_id: NodeId,
1306                rhs: Option<NodeId>,
1307            },
1308            Container {
1309                outer_span: DcByteSpan,
1310                opener: DcChar,
1311                closer: DcChar,
1312                unclosed: bool,
1313                children: Vec<NodeId>,
1314            },
1315            Tagged {
1316                outer_span: DcByteSpan,
1317                tag: DcChar,
1318                args: Vec<NodeId>,
1319            },
1320        }
1321
1322        impl ArenaBuildFrame {
1323            fn push_child(&mut self, child_id: NodeId) {
1324                match self {
1325                    Self::Infix { rhs, .. } => *rhs = Some(child_id),
1326                    Self::Container { children, .. } => children.push(child_id),
1327                    Self::Tagged { args, .. } => args.push(child_id),
1328                }
1329            }
1330        }
1331
1332        enum StubStep {
1333            Leaf(NodeId),
1334            Push(ArenaBuildFrame),
1335        }
1336
1337        let base_level_depth = self.level_stack.len();
1338
1339        let check_depth_exceeded_leaf = |nav: &mut Self,
1340                                         stub: &DcFrameStub,
1341                                         current_depth: usize,
1342                                         arena: &mut DcSyntaxArena<'a>|
1343         -> Result<Option<StubStep>> {
1344            if current_depth < policy.max_depth {
1345                return Ok(None);
1346            }
1347            let msg = format!(
1348                "Document nesting depth exceeds maximum limit ({}) at offset {}",
1349                policy.max_depth, stub.outer_span.start
1350            );
1351            nav.record_diagnostic(
1352                policy,
1353                policy.depth_limit_exceeded,
1354                stub.outer_span.start,
1355                msg.clone(),
1356            )?;
1357            Ok(Some(StubStep::Leaf(arena.alloc(
1358                stub.outer_span,
1359                DcSyntaxKind::Malformed {
1360                    raw_tokens: Vec::new(),
1361                    message: msg,
1362                },
1363            ))))
1364        };
1365
1366        let classify_stub = |nav: &mut Self,
1367                             stub: &DcFrameStub,
1368                             current_depth: usize,
1369                             arena: &mut DcSyntaxArena<'a>,
1370                             cur_resolver: &dyn SyntaxRuleResolver|
1371         -> Result<StubStep> {
1372            if matches!(stub.header_info, DcFrameHeaderInfo::Escaped) {
1373                return Ok(StubStep::Leaf(
1374                    arena.alloc_escaped_atom(stub.outer_span, stub.head_dc),
1375                ));
1376            }
1377            let head = stub.head_dc;
1378            if head.fills_role_with(
1379                DcRole::StartEncapsulationBinary,
1380                cur_resolver,
1381            ) && matches!(stub.header_info, DcFrameHeaderInfo::Binary { .. })
1382            {
1383                let node = nav.parse_binary_arena_node(
1384                    stub.outer_span,
1385                    policy,
1386                    cur_resolver,
1387                )?;
1388                return Ok(StubStep::Leaf(arena.alloc(stub.outer_span, node)));
1389            }
1390            if head.fills_role_with(DcRole::BeginLiteral, cur_resolver) {
1391                let (type_header, decoded) = nav
1392                    .decode_literal_stub_with_resolver(
1393                        stub,
1394                        policy,
1395                        cur_resolver,
1396                    )?;
1397                // Reason for fallback: literal closer defaults to DC_END_LITERAL.
1398                let closer =
1399                    stub.closer_dc.unwrap_or(ctb_formats_dcdata::dc::DC_END_LITERAL);
1400                return Ok(StubStep::Leaf(arena.alloc_literal(
1401                    stub.outer_span,
1402                    head,
1403                    closer,
1404                    &type_header,
1405                    decoded.as_mstr(),
1406                )));
1407            }
1408            if head.fills_role_with(DcRole::BeginIdentifier, cur_resolver) {
1409                let name = nav.decode_identifier_stub_with_resolver(
1410                    stub,
1411                    policy,
1412                    cur_resolver,
1413                )?;
1414                // Reason for fallback: identifier closer defaults to DC_END_IDENTIFIER.
1415                let closer = stub
1416                    .closer_dc
1417                    .unwrap_or(ctb_formats_dcdata::dc::DC_END_IDENTIFIER);
1418                return Ok(StubStep::Leaf(arena.alloc_identifier(
1419                    stub.outer_span,
1420                    head,
1421                    closer,
1422                    name.as_mstr(),
1423                )));
1424            }
1425            if head.fills_role_with(DcRole::BeginNumber, cur_resolver) {
1426                let (format, digits) = nav.decode_number_stub_with_resolver(
1427                    stub,
1428                    cur_resolver,
1429                )?;
1430                // Reason for fallback: number closer defaults to DC_END_NUMBER.
1431                let closer =
1432                    stub.closer_dc.unwrap_or(ctb_formats_dcdata::dc::DC_END_NUMBER);
1433                return Ok(StubStep::Leaf(arena.alloc_number(
1434                    stub.outer_span,
1435                    head,
1436                    closer,
1437                    format,
1438                    &digits,
1439                )));
1440            }
1441            if cur_resolver.resolve_infix_rule(head.to_u128()).is_some() {
1442                if let Some(inner) = stub.inner_span {
1443                    if let Some(step) = check_depth_exceeded_leaf(
1444                        nav,
1445                        stub,
1446                        current_depth,
1447                        arena,
1448                    )? {
1449                        return Ok(step);
1450                    }
1451                    let ident_span = DcByteSpan::new(
1452                        stub.outer_span.start,
1453                        inner.start.saturating_sub(nav.char_encoded_len(head)),
1454                    );
1455                    let ident = nav.decode_identifier_span_with_resolver(
1456                        ident_span,
1457                        policy,
1458                        cur_resolver,
1459                    )?;
1460                    let lhs_id = arena.alloc_identifier(
1461                        ident_span,
1462                        ctb_formats_dcdata::dc::DC_BEGIN_IDENTIFIER,
1463                        ctb_formats_dcdata::dc::DC_END_IDENTIFIER,
1464                        ident.as_mstr(),
1465                    );
1466                    nav.enter_frame_with_policy(stub, policy, cur_resolver)?;
1467                    return Ok(StubStep::Push(ArenaBuildFrame::Infix {
1468                        outer_span: stub.outer_span,
1469                        tag: head,
1470                        lhs_id,
1471                        rhs: None,
1472                    }));
1473                }
1474            }
1475            if let Some(closer) = stub.closer_dc {
1476                let unclosed = stub.is_unclosed();
1477                if stub.inner_span.is_some()
1478                    && !cur_resolver.is_opaque_container(head.to_u128())
1479                {
1480                    if let Some(step) = check_depth_exceeded_leaf(
1481                        nav,
1482                        stub,
1483                        current_depth,
1484                        arena,
1485                    )? {
1486                        return Ok(step);
1487                    }
1488                    nav.enter_frame_with_policy(stub, policy, cur_resolver)?;
1489                    return Ok(StubStep::Push(ArenaBuildFrame::Container {
1490                        outer_span: stub.outer_span,
1491                        opener: head,
1492                        closer,
1493                        unclosed,
1494                        children: Vec::new(),
1495                    }));
1496                }
1497                return Ok(StubStep::Leaf(arena.alloc(
1498                    stub.outer_span,
1499                    DcSyntaxKind::Container {
1500                        opener: head,
1501                        closer,
1502                        header: Vec::new(),
1503                        children: Vec::new(),
1504                        trailing: Vec::new(),
1505                        unclosed,
1506                    },
1507                )));
1508            }
1509            if stub.inner_span.is_some() {
1510                if let Some(step) =
1511                    check_depth_exceeded_leaf(nav, stub, current_depth, arena)?
1512                {
1513                    return Ok(step);
1514                }
1515                nav.enter_frame_with_policy(stub, policy, cur_resolver)?;
1516                return Ok(StubStep::Push(ArenaBuildFrame::Tagged {
1517                    outer_span: stub.outer_span,
1518                    tag: head,
1519                    args: Vec::new(),
1520                }));
1521            }
1522            Ok(StubStep::Leaf(
1523                arena.alloc(stub.outer_span, DcSyntaxKind::Atom(head)),
1524            ))
1525        };
1526
1527        let mut work_stack: Vec<ArenaBuildFrame> = Vec::new();
1528        let root_pinned = self.pinned_resolver.clone();
1529        let root_res: &dyn SyntaxRuleResolver =
1530            if let Some(ref r) = root_pinned {
1531                r.as_ref()
1532            } else {
1533                resolver
1534            };
1535        match classify_stub(self, root_stub, 0, arena, root_res)? {
1536            StubStep::Leaf(id) => return Ok(id),
1537            StubStep::Push(frame) => work_stack.push(frame),
1538        }
1539
1540        let res = (|| -> Result<NodeId> {
1541            loop {
1542                let current_depth = work_stack.len();
1543                let need_assignment_rhs = matches!(
1544                    work_stack.last(),
1545                    Some(ArenaBuildFrame::Infix { rhs: None, .. })
1546                );
1547                let finished_assignment = matches!(
1548                    work_stack.last(),
1549                    Some(ArenaBuildFrame::Infix { rhs: Some(_), .. })
1550                );
1551
1552                if finished_assignment {
1553                    let Some(ArenaBuildFrame::Infix {
1554                        outer_span,
1555                        tag,
1556                        lhs_id,
1557                        rhs: Some(val_id),
1558                    }) = work_stack.pop()
1559                    else {
1560                        unreachable!()
1561                    };
1562                    self.exit_frame()?;
1563                    let node_id = arena.alloc(
1564                        outer_span,
1565                        DcSyntaxKind::Tagged {
1566                            tag,
1567                            args: vec![lhs_id, val_id],
1568                        },
1569                    );
1570                    if let Some(parent) = work_stack.last_mut() {
1571                        parent.push_child(node_id);
1572                        continue;
1573                    }
1574                    return Ok(node_id);
1575                }
1576
1577                let start = self.cursor;
1578                let step_pinned = self.pinned_resolver.clone();
1579                let step_res: &dyn SyntaxRuleResolver =
1580                    if let Some(ref r) = step_pinned {
1581                        r.as_ref()
1582                    } else {
1583                        resolver
1584                    };
1585                if let Some(child_stub) =
1586                    self.next_sibling_stub_with_resolver(policy, step_res)?
1587                {
1588                    let post_pinned = self.pinned_resolver.clone();
1589                    let classify_res: &dyn SyntaxRuleResolver =
1590                        if let Some(ref r) = post_pinned {
1591                            r.as_ref()
1592                        } else {
1593                            resolver
1594                        };
1595                    match classify_stub(
1596                        self,
1597                        &child_stub,
1598                        current_depth,
1599                        arena,
1600                        classify_res,
1601                    )? {
1602                        StubStep::Leaf(child_id) => {
1603                            if let Some(top) = work_stack.last_mut() {
1604                                top.push_child(child_id);
1605                            }
1606                        }
1607                        StubStep::Push(child_frame) => {
1608                            work_stack.push(child_frame);
1609                        }
1610                    }
1611                } else {
1612                    if need_assignment_rhs {
1613                        bail!("Unexpected end of stream at offset {start}");
1614                    }
1615                    let Some(finished_frame) = work_stack.pop() else {
1616                        bail!("Internal error: empty arena work stack");
1617                    };
1618                    let frame_pinned = self.pinned_resolver.clone();
1619                    let frame_res: &dyn SyntaxRuleResolver =
1620                        if let Some(ref r) = frame_pinned {
1621                            r.as_ref()
1622                        } else {
1623                            resolver
1624                        };
1625                    self.exit_frame()?;
1626                    let node_id = match finished_frame {
1627                        ArenaBuildFrame::Container {
1628                            outer_span,
1629                            opener,
1630                            closer,
1631                            unclosed,
1632                            children,
1633                        } => {
1634                            let is_format_or_temporal = opener.fills_role_with(
1635                                DcRole::BeginFormatRepresentation,
1636                                frame_res,
1637                            ) || frame_res
1638                                .matches_script(".WASM", opener.to_u128());
1639                            let normalized_children = if is_format_or_temporal {
1640                                children
1641                            } else {
1642                                Self::normalize_field_nodes_with_resolver(
1643                                    children, arena, frame_res,
1644                                )
1645                            };
1646                            arena.alloc(
1647                                outer_span,
1648                                DcSyntaxKind::Container {
1649                                    opener,
1650                                    closer,
1651                                    header: Vec::new(),
1652                                    children: normalized_children,
1653                                    trailing: Vec::new(),
1654                                    unclosed,
1655                                },
1656                            )
1657                        }
1658                        ArenaBuildFrame::Tagged {
1659                            outer_span,
1660                            tag,
1661                            args,
1662                        } => {
1663                            let normalized_args =
1664                                Self::normalize_field_nodes_with_resolver(
1665                                    args, arena, frame_res,
1666                                );
1667                            arena.alloc(
1668                                outer_span,
1669                                DcSyntaxKind::Tagged {
1670                                    tag,
1671                                    args: normalized_args,
1672                                },
1673                            )
1674                        }
1675                        ArenaBuildFrame::Infix { .. } => unreachable!(),
1676                    };
1677                    if let Some(parent) = work_stack.last_mut() {
1678                        parent.push_child(node_id);
1679                    } else {
1680                        return Ok(node_id);
1681                    }
1682                }
1683            }
1684        })();
1685
1686        while self.level_stack.len() > base_level_depth {
1687            let _ = self.exit_frame();
1688        }
1689        res
1690    }
1691}