ctb_formats_dcstring/
dc_mixed_serde.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//! Serialization and deserialization infrastructure for `DcMixed` documents.
21//!
22//! Provides the [`DcMixedEncode`] and [`DcMixedDecode`] traits,
23//! [`DcProjectionContext`], primitive codec implementations, and universal
24//! roundtrip verification.
25
26#[allow(
27    unused_imports,
28    clippy::wildcard_imports,
29    reason = "Standard workspace module prelude"
30)]
31use crate::utilities::*;
32use anyhow::anyhow;
33
34use std::borrow::Cow;
35use std::collections::BTreeMap;
36use std::fmt::{self, Write as _};
37use std::net::{Ipv4Addr, Ipv6Addr};
38use std::ops::Range;
39use std::path::PathBuf;
40use std::sync::Arc;
41use std::time::{Duration, SystemTime};
42
43use ctb_formats_utilities::FormatId;
44
45use ctb_formats_dcdata::dc::{
46    DC_BEGIN_DATE_DURATION, DC_BEGIN_DATE_MAGNITUDE,
47    DC_BEGIN_FORMAT_REPRESENTATION, DC_BEGIN_KV_MAP, DC_BEGIN_KV_PAIR,
48    DC_BEGIN_LEGACY_KV_MAP, DC_BEGIN_LIST, DC_BEGIN_LITERAL,
49    DC_BEGIN_TIME_MOMENT, DC_BEGIN_TUPLE, DC_BEGIN_TYPE_DEF, DC_BOOLEAN_FALSE,
50    DC_BOOLEAN_TRUE, DC_END_DATE_DURATION, DC_END_DATE_MAGNITUDE,
51    DC_END_FORMAT_REPRESENTATION, DC_END_KV_MAP, DC_END_KV_PAIR, DC_END_LIST,
52    DC_END_LITERAL, DC_END_TIME_MOMENT, DC_END_TUPLE, DC_END_TYPE_DEF,
53    DC_EQUIVALENT_REPRESENTATIONS, DC_FILE_PATH_DELIMITER,
54    DC_LIST_ELEMENT_SEPARATOR, DC_NEGATIVE, DC_OPTIONAL_ABSENT,
55    DC_OPTIONAL_PRESENT, DC_PARTIALLY_EQUIVALENT_REPRESENTATIONS, DC_POSITIVE,
56    DC_REFERENCE_BOUND_VALUE, DC_REFERENCE_NAMED_OBJECT,
57    DC_START_ENCAPSULATION_BINARY, DC_TYPE_ANY, DC_TYPE_INTERSECTION,
58    DC_TYPE_STRING, DC_TYPE_UNION,
59};
60
61use ctb_formats_dcdata::syntax::{
62    DcRole, SyntaxRuleResolver, default_syntax_resolver,
63};
64
65use crate::dc_mixed::{DcMixed, DcMixedChunks, DcMstr, DcMstring};
66use crate::dc_source::DcFieldAnnotation;
67use crate::navigator::{
68    DcBinaryResolver, DcDocumentNavigator, DcExpressionEvaluator,
69    DcForgivingDefault, DcProjectionPolicy, DcSyntaxArena, DcSyntaxKind,
70    NodeId,
71};
72use crate::shared::SharedValueContext;
73use crate::{DcChar, DcChars};
74
75// STYLE NOTE TO LLM TOOLS: This file (tests excepted) MUST use Dc roles for parsing, not consts or numbers, so that aliases and expressions are resolved correctly. Consts may be used in encoders.
76
77/// Serializes values to DcMM through a shared, fallible streaming encoder.
78pub trait DcMixedEncode {
79    fn encode_dc_mixed(&self, mst: &mut DcMstring) -> Result<()> {
80        self.encode_dc_mixed_to(&mut mst.writer())
81    }
82
83    fn encode_dc_mixed_with_context(
84        &self,
85        mst: &mut DcMstring,
86        context: &SharedValueContext,
87    ) -> Result<()> {
88        self.encode_dc_mixed_to_with_context(&mut mst.writer(), context)
89    }
90
91    fn encode_format_elements_with_context(
92        &self,
93        format: DcChar,
94        mst: &mut DcMstring,
95        context: &SharedValueContext,
96    ) -> Result<()> {
97        self.encode_format_elements_to_with_context(
98            format,
99            &mut mst.writer(),
100            context,
101        )
102    }
103
104    /// Writes a complete DcMM document, including its header.
105    fn write_dc_mixed(&self, output: &mut dyn std::io::Write) -> Result<()> {
106        output.write_all(DcMstring::new().as_bytes())?;
107        self.encode_dc_mixed_to(&mut crate::DcWriter::new(output))
108    }
109
110    /// Encodes a new mixed-mode string, not a preserved source string.
111    fn to_dc_mixed(&self) -> Result<DcMstring> {
112        let mut source = DcMstring::new();
113        self.encode_dc_mixed(&mut source)?;
114        Ok(source)
115    }
116
117    /// Encodes a new DcUtf string, explicitly converting any encapsulations.
118    fn to_dc_string(&self) -> Result<crate::DcString> {
119        DcMstr::to_dc_string(&self.to_dc_mixed()?)
120    }
121
122    /// Serializes a record without a document header.
123    ///
124    /// # Errors
125    /// Returns an error if serialization fails.
126    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()>;
127
128    /// Encodes with explicit definitions already persisted by the caller.
129    fn encode_dc_mixed_to_with_context(
130        &self,
131        mst: &mut crate::DcWriter<'_>,
132        _context: &crate::SharedValueContext,
133    ) -> Result<()> {
134        self.encode_dc_mixed_to(mst)
135    }
136
137    /// Encodes this value inside a `Dc 511 [format] ... Dc 512` format representation container.
138    fn encode_format_elements_to_with_context(
139        &self,
140        format: DcChar,
141        mst: &mut crate::DcWriter<'_>,
142        context: &crate::SharedValueContext,
143    ) -> Result<()> {
144        let _ = format;
145        self.encode_dc_mixed_to_with_context(mst, context)
146    }
147}
148
149/// Trait for types that can be projected from a parsed [`NodeId`] in a [`DcSyntaxArena`].
150pub trait DcMixedDecode: Sized {
151    /// Projects a document and returns the number of roots consumed.
152    ///
153    /// Node projection must remain local; only this entrypoint may use a
154    /// document's root sequence. The caller reports any remaining roots.
155    ///
156    /// # Errors
157    /// Returns an error if the document is empty or projection fails.
158    fn decode_dc_document(
159        ctx: &mut DcProjectionContext<'_, '_>,
160        roots: &[NodeId],
161    ) -> Result<(Self, usize)> {
162        let root = roots
163            .first()
164            .copied()
165            .context("Empty document cannot be decoded into typed value")?;
166        Ok((Self::decode_dc_node(ctx, root)?, 1))
167    }
168
169    /// Projects an instance from the given syntax `node_id` under `ctx`.
170    ///
171    /// # Errors
172    /// Returns an error if unexpected characters, malformed data, or missing
173    /// required fields are encountered and `ctx.policy` specifies an error action.
174    fn decode_dc_node(
175        ctx: &mut DcProjectionContext<'_, '_>,
176        node_id: NodeId,
177    ) -> Result<Self>;
178}
179
180/// Normalized field input shared by ordinary and flattened record projection.
181#[derive(Debug, Clone, Copy)]
182pub struct FieldProjectionSpec {
183    /// Semantic field tag selected by the containing record.
184    pub tag: u128,
185    /// Parsed node containing the field's value.
186    pub value_node: NodeId,
187    /// Original field node retained for annotations and diagnostics.
188    pub source_node: NodeId,
189}
190
191/// Trait for types whose fields can be serialized or deserialized in a flattened context.
192pub trait DcMixedFlattened: Sized {
193    type State: Default;
194    fn encode_flattened_fields(
195        &self,
196        mst: &mut crate::DcWriter<'_>,
197        context: &SharedValueContext,
198    ) -> Result<()>;
199    fn encode_empty_flattened_marker(
200        &self,
201        _mst: &mut crate::DcWriter<'_>,
202        _context: &SharedValueContext,
203    ) -> Result<()> {
204        Ok(())
205    }
206    fn decode_flattened_field(
207        state: &mut Self::State,
208        tag: u128,
209        ctx: &mut DcProjectionContext<'_, '_>,
210        val_id: NodeId,
211        source_node: NodeId,
212    ) -> Result<bool>;
213    fn finish_flattened(
214        state: Self::State,
215        ctx: &mut DcProjectionContext<'_, '_>,
216    ) -> Result<Self>;
217}
218
219/// Finalizes a flattened field using the containing record's recovery policy.
220///
221/// A recovered malformed field is absent, just like a failed ordinary field.
222///
223/// # Errors
224/// Returns the finalization error when malformed fields are errors.
225pub fn finish_flattened_field<T: DcMixedFlattened>(
226    state: T::State,
227    ctx: &mut DcProjectionContext<'_, '_>,
228    field: &str,
229) -> Result<Option<T>> {
230    let diagnostic_start = ctx.diagnostics().len();
231    match T::finish_flattened(state, ctx) {
232        Ok(value) => Ok(Some(value)),
233        Err(error) => {
234            if ctx
235                .diagnostics()
236                .iter()
237                .skip(diagnostic_start)
238                .any(|diagnostic| diagnostic.is_error)
239            {
240                return Err(error);
241            }
242            ctx.handle_diagnostic(
243                ctx.policy.malformed_field,
244                format!("Malformed flattened field `{field}`: {error:#}"),
245            )?;
246            Ok(None)
247        }
248    }
249}
250
251/// Trait indicating whether an alternative representation is lossless given serialization context.
252pub trait LosslessWithContext {
253    /// Returns true if this representation is completely lossless in the current context.
254    fn is_lossless(&self, _context: &crate::SharedValueContext) -> bool {
255        true
256    }
257}
258
259impl crate::DcMstr {
260    /// Interprets the entire string as a typed value without changing source.
261    ///
262    /// # Errors
263    /// Returns an error on unsupported syntax, missing fields, or trailing data.
264    pub fn decode<T: DcMixedDecode>(
265        &self,
266        policy: &crate::DcProjectionPolicy,
267    ) -> Result<T> {
268        let nav = crate::DcDocumentNavigator::from_mstr(self);
269        let resolver = nav.effective_resolver();
270        self.decode_with_resolver_and_context(resolver.as_ref(), None, policy)
271    }
272
273    /// Interprets the whole string with explicitly supplied outer bindings.
274    ///
275    /// # Errors
276    /// Returns an error if interpretation fails or trailing content remains.
277    pub fn decode_with_context<T: DcMixedDecode>(
278        &self,
279        context: &crate::SharedValueContext,
280        policy: &crate::DcProjectionPolicy,
281    ) -> Result<T> {
282        let nav = crate::DcDocumentNavigator::from_mstr(self);
283        let resolver = nav.effective_resolver();
284        self.decode_with_resolver_and_context(
285            resolver.as_ref(),
286            Some(context),
287            policy,
288        )
289    }
290
291    /// Interprets the string using a custom [`SyntaxRuleResolver`].
292    ///
293    /// # Errors
294    /// Returns an error if interpretation fails or trailing content remains.
295    pub fn decode_with_resolver<T: DcMixedDecode>(
296        &self,
297        resolver: &dyn SyntaxRuleResolver,
298        policy: &crate::DcProjectionPolicy,
299    ) -> Result<T> {
300        self.decode_with_resolver_and_context(resolver, None, policy)
301    }
302
303    /// Interprets the string using a custom [`SyntaxRuleResolver`] and optional
304    /// outer shared context.
305    ///
306    /// # Errors
307    /// Returns an error if interpretation fails or trailing content remains.
308    pub fn decode_with_resolver_and_context<T: DcMixedDecode>(
309        &self,
310        resolver: &dyn SyntaxRuleResolver,
311        context: Option<&crate::SharedValueContext>,
312        policy: &crate::DcProjectionPolicy,
313    ) -> Result<T> {
314        let mut nav = crate::DcDocumentNavigator::from_mstr(self);
315        let mut arena = crate::DcSyntaxArena::new();
316        nav.parse_document_into_arena_with_resolver(
317            &mut arena, policy, resolver,
318        )?;
319        let mut ctx = DcProjectionContext::with_all_resolvers(
320            &arena,
321            policy,
322            context,
323            Some(&mut nav),
324            Some(resolver),
325            None,
326        );
327        let roots = ctx.strip_leading_document_most_recent_root(arena.roots());
328        let (res, consumed) = T::decode_dc_document(&mut ctx, roots)?;
329        ctx.handle_remaining_nodes(
330            roots
331                .get(consumed..)
332                .context("Invalid document root consumption")?,
333        )?;
334        Ok(res)
335    }
336}
337
338/// Trait for types that can convert to and from a numeric Dc representation.
339/// Used for fields with equivalent numeric representations (`equivalents = (..., number)`).
340pub trait DcMixedNumber: Sized {
341    /// Serializes this instance as a Dc number.
342    ///
343    /// # Errors
344    /// Returns an error if serialization fails.
345    fn encode_dc_number(&self, mst: &mut crate::DcWriter<'_>) -> Result<()>;
346
347    /// Deserializes an instance from a numeric Dc representation.
348    ///
349    /// # Errors
350    /// Returns an error if decoding fails or the number cannot be converted.
351    fn decode_dc_number(
352        ctx: &mut DcProjectionContext<'_, '_>,
353        node_id: NodeId,
354    ) -> Result<Self>;
355}
356
357macro_rules! impl_dc_mixed_number_primitive {
358    ($($t:ty),*) => {
359        $(
360            impl DcMixedNumber for $t {
361                fn encode_dc_number(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
362                    self.encode_dc_mixed_to(mst)
363                }
364                fn decode_dc_number(
365                    ctx: &mut DcProjectionContext<'_, '_>,
366                    node_id: NodeId,
367                ) -> Result<Self> {
368                    Self::decode_dc_node(ctx, node_id)
369                }
370            }
371        )*
372    };
373}
374
375impl_dc_mixed_number_primitive!(
376    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize
377);
378
379/// Wrapper for raw binary byte buffers serialized via `TYPE_BINARY_SHA256`
380/// encapsulation (`Dc 203` .. `Dc 204`).
381#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
382pub struct BinaryPayload(pub Vec<u8>);
383
384impl BinaryPayload {
385    /// Wraps a byte vector into a `BinaryPayload`.
386    #[must_use]
387    pub const fn new(bytes: Vec<u8>) -> Self {
388        Self(bytes)
389    }
390
391    /// Unwraps the underlying byte vector.
392    #[must_use]
393    pub fn into_inner(self) -> Vec<u8> {
394        self.0
395    }
396}
397
398impl AsRef<[u8]> for BinaryPayload {
399    fn as_ref(&self) -> &[u8] {
400        &self.0
401    }
402}
403
404impl From<&[u8]> for BinaryPayload {
405    fn from(bytes: &[u8]) -> Self {
406        Self(bytes.to_vec())
407    }
408}
409
410impl From<Vec<u8>> for BinaryPayload {
411    fn from(bytes: Vec<u8>) -> Self {
412        Self(bytes)
413    }
414}
415
416impl From<BinaryPayload> for Vec<u8> {
417    fn from(payload: BinaryPayload) -> Self {
418        payload.0
419    }
420}
421
422impl DcMixedEncode for BinaryPayload {
423    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
424        mst.push_binary_with_sha256(&self.0)
425    }
426}
427
428impl DcMixedDecode for BinaryPayload {
429    fn decode_dc_node(
430        ctx: &mut DcProjectionContext<'_, '_>,
431        node_id: NodeId,
432    ) -> Result<Self> {
433        ctx.decode_transparent(node_id, |ctx, node_id| {
434            let payload = match &ctx.node(node_id)?.kind {
435                DcSyntaxKind::Binary { payload, .. } => payload.clone(),
436                other => bail!(
437                    "Expected Binary node for BinaryPayload, found {other:?}"
438                ),
439            };
440            let bytes = ctx.materialize_binary(&payload).context(
441                "Failed to materialize binary payload in DcSyntaxNode",
442            )?;
443            Ok(Self(bytes.into_owned()))
444        })
445    }
446}
447
448/// Binary data retained as an owned buffer or an offset in a backing document.
449#[derive(Debug, Clone, PartialEq, Eq)]
450pub struct LazyBinaryPayload(pub crate::navigator::BinaryPayloadRef<'static>);
451
452impl DcMixedEncode for LazyBinaryPayload {
453    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
454        mst.push_binary_ref(&self.0)
455    }
456}
457
458impl DcMixedDecode for LazyBinaryPayload {
459    fn decode_dc_node(
460        ctx: &mut DcProjectionContext<'_, '_>,
461        node_id: NodeId,
462    ) -> Result<Self> {
463        use crate::navigator::BinaryPayloadRef;
464        ctx.decode_transparent(node_id, |ctx, node_id| {
465            let payload = match &ctx.node(node_id)?.kind {
466                DcSyntaxKind::Binary { payload, .. } => payload,
467                other => bail!("Expected binary payload, found {other:?}"),
468            };
469            let owned = match payload {
470                BinaryPayloadRef::Source { source_id, len } => {
471                    BinaryPayloadRef::Source {
472                        source_id: *source_id,
473                        len: *len,
474                    }
475                }
476                BinaryPayloadRef::Borrowed(bytes) => {
477                    BinaryPayloadRef::Inline(bytes.to_vec())
478                }
479                BinaryPayloadRef::Inline(bytes) => {
480                    BinaryPayloadRef::Inline(bytes.clone())
481                }
482                BinaryPayloadRef::FileSpan {
483                    file_offset,
484                    len,
485                    checksum,
486                    checksum_action,
487                } => BinaryPayloadRef::FileSpan {
488                    file_offset: *file_offset,
489                    len: *len,
490                    checksum: checksum.clone(),
491                    checksum_action: *checksum_action,
492                },
493            };
494            Ok(Self(owned))
495        })
496    }
497}
498
499/// A general, struct-agnostic mixed-mode raw value representation.
500#[derive(Debug, Clone, PartialEq, Eq)]
501pub enum DcRawValue {
502    String(String),
503    Binary {
504        format: Option<FormatId>,
505        with_sha256: bool,
506        bytes: Vec<u8>,
507    },
508    FilePathSegments(Vec<Vec<u8>>),
509    U16List(Vec<u16>),
510    PartiallyEquivalent(Vec<DcRawValue>),
511}
512
513impl DcForgivingDefault for DcRawValue {
514    fn dc_forgiving_default() -> Self {
515        Self::Binary {
516            format: None,
517            with_sha256: false,
518            bytes: Vec::new(),
519        }
520    }
521}
522
523impl DcMixedEncode for DcRawValue {
524    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
525        self.encode_dc_mixed_to_with_context(
526            mst,
527            &SharedValueContext::default(),
528        )
529    }
530
531    fn encode_dc_mixed_to_with_context(
532        &self,
533        mst: &mut crate::DcWriter<'_>,
534        context: &SharedValueContext,
535    ) -> Result<()> {
536        match self {
537            Self::String(s) => s.encode_dc_mixed_to_with_context(mst, context),
538            Self::Binary {
539                format: Some(fmt),
540                bytes,
541                ..
542            } => {
543                let mut metadata = crate::DcString::new();
544                metadata.push(DcChar::from_u128(
545                    fmt.dc_id().context("Missing format Dc ID")?,
546                ));
547                mst.push_binary_with_metadata(bytes, &metadata)
548            }
549            Self::Binary {
550                format: None,
551                with_sha256: true,
552                bytes,
553            } => mst.push_binary_with_sha256(bytes),
554            Self::Binary {
555                format: None,
556                with_sha256: false,
557                bytes,
558            } => {
559                mst.push_binary(bytes)?;
560                Ok(())
561            }
562            Self::FilePathSegments(segments) => {
563                encode_filepath_segments_to(segments, mst)
564            }
565            Self::U16List(units) => {
566                units.encode_dc_mixed_to_with_context(mst, context)
567            }
568            Self::PartiallyEquivalent(items) => {
569                mst.push_char(DC_PARTIALLY_EQUIVALENT_REPRESENTATIONS)?;
570                mst.push_char(DC_BEGIN_LIST)?;
571                mst.push_char(DC_TYPE_ANY)?;
572                let mut iter = items.iter().peekable();
573                while let Some(item) = iter.next() {
574                    item.encode_dc_mixed_to_with_context(mst, context)?;
575                    if iter.peek().is_some() {
576                        mst.push_char(DC_LIST_ELEMENT_SEPARATOR)?;
577                    }
578                }
579                mst.push_char(DC_END_LIST)?;
580                Ok(())
581            }
582        }
583    }
584}
585
586impl DcMixedDecode for DcRawValue {
587    fn decode_dc_node(
588        ctx: &mut DcProjectionContext<'_, '_>,
589        node_id: NodeId,
590    ) -> Result<Self> {
591        ctx.with_projection_depth(node_id, |ctx| {
592            let mut curr_id = node_id;
593            while let Ok(node) = ctx.node(curr_id)
594                && let Some((head, children)) = node.head_and_children()
595                && ctx.token_fills_role(head, DcRole::OptionalPresent)
596            {
597                curr_id = *children
598                    .first()
599                    .context("Empty optional construct (Dc 315)")?;
600            }
601
602            let node = ctx.node(curr_id)?;
603            let candidate_children: Option<Vec<NodeId>> =
604                if let Some((head, children)) = node.head_and_children()
605                    && ctx.token_fills_role(
606                        head,
607                        DcRole::PartiallyEquivalentRepresentations,
608                    )
609                {
610                    if let [first_id] = children {
611                        let first_child = ctx.node(*first_id)?;
612                        if let DcSyntaxKind::Container {
613                            opener: child_opener,
614                            children: inner,
615                            ..
616                        } = &first_child.kind
617                            && ctx.token_fills_role(
618                                *child_opener,
619                                DcRole::BeginList,
620                            )
621                        {
622                            Some(inner.clone())
623                        } else {
624                            Some(children.to_vec())
625                        }
626                    } else {
627                        Some(children.to_vec())
628                    }
629                } else {
630                    None
631                };
632
633            if let Some(child_ids) = candidate_children {
634                let mut items = Vec::new();
635                for cid in child_ids {
636                    let cnode = ctx.node(cid)?;
637                    match &cnode.kind {
638                        DcSyntaxKind::Atom(ch) if ctx.token_fills_role(*ch, DcRole::TypeAny) || ctx.token_fills_role(*ch, DcRole::ListElementSeparator) => continue,
639                        DcSyntaxKind::Tagged { tag, .. } if ctx.token_fills_role(*tag, DcRole::TypeAny) || ctx.token_fills_role(*tag, DcRole::ListElementSeparator) => continue,
640                        _ => {}
641                    }
642                    items.push(Self::decode_dc_node(ctx, cid)?);
643                }
644                return Ok(Self::PartiallyEquivalent(items));
645            }
646
647            let unwrap_id = ctx.unwrap_transparent(curr_id)?;
648            if let Some((fmt, _)) = ctx.unwrap_format_representation(unwrap_id)? {
649                let path_fmt = format_dc_char(FormatId::FilePath)?;
650                if ctx.tokens_equivalent(fmt, path_fmt) {
651                    let segments = decode_filepath_segments(ctx, unwrap_id)?;
652                    return Ok(Self::FilePathSegments(segments));
653                }
654            }
655
656            let unwrap_node = ctx.node(unwrap_id)?;
657            match &unwrap_node.kind {
658                DcSyntaxKind::Binary { checksum_format, payload, .. } => {
659                    let bytes = ctx.materialize_binary(payload)?.into_owned();
660                    let format = checksum_format
661                        .map(|dc| {
662                            let canon = ctx.canonical_token(dc);
663                            FormatId::from_dc_id(canon.to_u128()).context("Unsupported binary format identifier")
664                        })
665                        .transpose()?;
666                    Ok(Self::Binary {
667                        format,
668                        with_sha256: false,
669                        bytes,
670                    })
671                }
672                DcSyntaxKind::Container { opener, .. } if ctx.token_fills_role(*opener, DcRole::BeginList) => {
673                    let units = Vec::<u16>::decode_dc_node(ctx, unwrap_id)?;
674                    Ok(Self::U16List(units))
675                }
676                DcSyntaxKind::Container { .. }
677                    if ctx
678                        .arena
679                        .is_literal_with_resolver(unwrap_id, ctx.resolver())
680                        || ctx.arena.is_identifier_with_resolver(
681                            unwrap_id,
682                            ctx.resolver(),
683                        ) =>
684                {
685                    let s = String::decode_dc_node(ctx, unwrap_id)?;
686                    Ok(Self::String(s))
687                }
688                other => bail!("Unsupported syntax node kind for DcRawValue: {other:?}"),
689            }
690        })
691    }
692}
693
694fn decode_integer_node(
695    ctx: &mut DcProjectionContext<'_, '_>,
696    node_id: NodeId,
697) -> Result<malachite::Integer> {
698    ctx.decode_transparent(node_id, |ctx, node_id| {
699        if let Some((_format, digits)) =
700            ctx.arena.decode_number_with_resolver(node_id, ctx.resolver())
701        {
702            crate::dc_number::parse_dc_number_digits_with_resolver(
703                &digits,
704                ctx.resolver(),
705            )
706        } else {
707            let node = ctx.node(node_id)?;
708            bail!("Expected Number node for integer, found {:?}", node.kind)
709        }
710    })
711}
712
713fn decode_natural_node(
714    ctx: &mut DcProjectionContext<'_, '_>,
715    node_id: NodeId,
716) -> Result<malachite::Natural> {
717    ctx.decode_transparent(node_id, |ctx, node_id| {
718        let int_val = decode_integer_node(ctx, node_id)?;
719        ensure!(
720            int_val >= 0,
721            "Expected non-negative integer for Natural, found negative"
722        );
723        Ok(int_val.unsigned_abs_ref().clone())
724    })
725}
726
727/// Execution context for projecting typed values from parsed syntax nodes in a [`DcSyntaxArena`].
728pub struct DcProjectionContext<'a, 'ctx> {
729    /// Borrowed syntax arena containing all parsed CST nodes for the document or frame.
730    pub arena: &'a DcSyntaxArena<'a>,
731    /// Active policy dictating diagnostics, strictness, and error recovery actions.
732    pub policy: &'ctx DcProjectionPolicy,
733    /// Optional enclosing document context for lexical identifier resolution.
734    pub shared_context: Option<&'ctx SharedValueContext>,
735    /// Document-local lexical scope tracking scoped definitions (`Dc 541..542`).
736    pub reference_scope: SharedValueContext,
737    /// Accumulated field annotations produced during projection.
738    pub annotations: Vec<DcFieldAnnotation>,
739    /// Flag indicating whether field annotations should be recorded.
740    pub annotating: bool,
741    /// Current record nesting depth.
742    pub record_depth: usize,
743    /// Current non-record container projection nesting depth.
744    pub container_depth: usize,
745    /// Current stream or node byte offset for diagnostics.
746    pub current_position: u64,
747    diagnostics: Vec<ctb_formats_dcdata::syntax::SyntaxDiagnostic>,
748    /// Optional stream-backed resolver for `DeferredStream` binary payloads.
749    pub binary_resolver: Option<&'ctx mut dyn DcBinaryResolver>,
750    /// Optional syntax rule resolver overlay for character classification and equivalence.
751    pub resolver: Option<&'a dyn SyntaxRuleResolver>,
752    /// Optional expression evaluator for dynamic/Scheme/Lisp-like expression resolution.
753    pub evaluator: Option<&'a dyn DcExpressionEvaluator>,
754}
755
756impl fmt::Debug for DcProjectionContext<'_, '_> {
757    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
758        f.debug_struct("DcProjectionContext")
759            .field("arena", &self.arena)
760            .field("policy", &self.policy)
761            .field("shared_context", &self.shared_context)
762            .field("reference_scope", &self.reference_scope)
763            .field("annotations", &self.annotations)
764            .field("annotating", &self.annotating)
765            .field("record_depth", &self.record_depth)
766            .field("current_position", &self.current_position)
767            .field("diagnostics", &self.diagnostics)
768            .field("has_binary_resolver", &self.binary_resolver.is_some())
769            .field("has_resolver", &self.resolver.is_some())
770            .field("has_evaluator", &self.evaluator.is_some())
771            .finish()
772    }
773}
774
775impl<'a, 'ctx> DcProjectionContext<'a, 'ctx> {
776    /// Creates a new projection context over the given arena and policy.
777    #[must_use]
778    pub fn new(
779        arena: &'a DcSyntaxArena<'a>,
780        policy: &'ctx DcProjectionPolicy,
781    ) -> Self {
782        Self::with_all_resolvers(arena, policy, None, None, None, None)
783    }
784
785    /// Returns the active syntax rule resolver.
786    #[must_use]
787    pub fn resolver(&self) -> &dyn SyntaxRuleResolver {
788        if let Some(r) = self.resolver {
789            r
790        } else {
791            default_syntax_resolver().as_ref()
792        }
793    }
794
795    /// Returns the active expression evaluator, if configured.
796    #[must_use]
797    pub fn evaluator(&self) -> Option<&dyn DcExpressionEvaluator> {
798        self.evaluator
799    }
800
801    /// Sets a custom syntax rule resolver on this projection context.
802    #[must_use]
803    pub fn with_syntax_resolver(
804        mut self,
805        resolver: &'a dyn SyntaxRuleResolver,
806    ) -> Self {
807        self.resolver = Some(resolver);
808        self
809    }
810
811    /// Sets an expression evaluator on this projection context.
812    #[must_use]
813    pub fn with_evaluator(
814        mut self,
815        evaluator: &'a dyn DcExpressionEvaluator,
816    ) -> Self {
817        self.evaluator = Some(evaluator);
818        self
819    }
820
821    /// Sets a custom syntax rule resolver on this context in-place.
822    pub fn set_syntax_resolver(
823        &mut self,
824        resolver: &'a dyn SyntaxRuleResolver,
825    ) {
826        self.resolver = Some(resolver);
827    }
828
829    /// Sets an expression evaluator on this context in-place.
830    pub fn set_evaluator(&mut self, evaluator: &'a dyn DcExpressionEvaluator) {
831        self.evaluator = Some(evaluator);
832    }
833
834    /// Returns the canonical token representation for `token`.
835    #[must_use]
836    pub fn canonical_token(&self, token: DcChar) -> DcChar {
837        DcChar::from_u128(self.resolver().canonical_token(token.to_u128()))
838    }
839
840    /// Returns true if two tokens are identical or declared logically equivalent.
841    #[must_use]
842    pub fn tokens_equivalent(
843        &self,
844        a: impl Into<u128>,
845        b: impl Into<u128>,
846    ) -> bool {
847        let a_val = a.into();
848        let b_val = b.into();
849        a_val == b_val || self.resolver().is_equivalent_to(a_val, b_val)
850    }
851
852    /// Returns true if `token` is identical or declared logically equivalent to any
853    /// candidate in `candidates`.
854    #[must_use]
855    pub fn any_token_equivalent(
856        &self,
857        token: impl Into<u128>,
858        candidates: &[u128],
859    ) -> bool {
860        let tok = token.into();
861        for &cand in candidates {
862            if tok == cand || self.resolver().is_equivalent_to(tok, cand) {
863                return true;
864            }
865        }
866        false
867    }
868
869    /// Returns true if `token` fills `role`.
870    #[must_use]
871    pub fn token_fills_role(
872        &self,
873        token: impl Into<u128>,
874        role: DcRole,
875    ) -> bool {
876        self.resolver().token_fills_role(token.into(), role)
877    }
878
879    /// Creates a new projection context with an optional enclosing shared context.
880    #[must_use]
881    pub fn with_shared_context(
882        arena: &'a DcSyntaxArena<'a>,
883        policy: &'ctx DcProjectionPolicy,
884        shared_context: Option<&'ctx SharedValueContext>,
885    ) -> Self {
886        Self::with_shared_context_and_resolver(
887            arena,
888            policy,
889            shared_context,
890            None,
891        )
892    }
893
894    /// Creates a new projection context with an optional shared context and binary resolver.
895    #[must_use]
896    pub fn with_shared_context_and_resolver(
897        arena: &'a DcSyntaxArena<'a>,
898        policy: &'ctx DcProjectionPolicy,
899        shared_context: Option<&'ctx SharedValueContext>,
900        binary_resolver: Option<&'ctx mut dyn DcBinaryResolver>,
901    ) -> Self {
902        Self::with_all_resolvers(
903            arena,
904            policy,
905            shared_context,
906            binary_resolver,
907            None,
908            None,
909        )
910    }
911
912    /// Creates a new projection context with full shared context, binary resolver,
913    /// syntax rule resolver, and optional expression evaluator.
914    #[must_use]
915    pub fn with_all_resolvers(
916        arena: &'a DcSyntaxArena<'a>,
917        policy: &'ctx DcProjectionPolicy,
918        shared_context: Option<&'ctx SharedValueContext>,
919        binary_resolver: Option<&'ctx mut dyn DcBinaryResolver>,
920        resolver: Option<&'a dyn SyntaxRuleResolver>,
921        evaluator: Option<&'a dyn DcExpressionEvaluator>,
922    ) -> Self {
923        Self {
924            arena,
925            policy,
926            shared_context,
927            reference_scope: SharedValueContext::default(),
928            annotations: Vec::new(),
929            annotating: false,
930            record_depth: 0,
931            container_depth: 0,
932            current_position: 0,
933            diagnostics: Vec::new(),
934            binary_resolver,
935            resolver,
936            evaluator,
937        }
938    }
939
940    /// Creates a projection context inheriting the resolver and evaluator from a [`crate::navigator::SyntaxEvalContext`].
941    #[must_use]
942    pub fn from_eval_context(
943        arena: &'a DcSyntaxArena<'a>,
944        eval_ctx: &'a crate::navigator::SyntaxEvalContext<'a>,
945        policy: &'ctx DcProjectionPolicy,
946    ) -> Self {
947        Self::with_all_resolvers(
948            arena,
949            policy,
950            None,
951            None,
952            Some(eval_ctx.resolver),
953            eval_ctx.evaluator.as_deref(),
954        )
955    }
956
957    /// Materializes a [`crate::navigator::BinaryPayloadRef`] using the attached
958    /// [`DcBinaryResolver`] if available, or from in-memory bytes otherwise.
959    ///
960    /// # Errors
961    /// Returns an error if the payload is `DeferredStream` without a resolver,
962    /// or if reading/checksum verification fails.
963    pub fn materialize_binary(
964        &mut self,
965        payload: &crate::navigator::BinaryPayloadRef<'a>,
966    ) -> Result<Cow<'a, [u8]>> {
967        if let Some(resolver) = self.binary_resolver.as_deref_mut() {
968            resolver.materialize_binary(payload)
969        } else {
970            payload.materialize_bytes()
971        }
972    }
973
974    /// Returns a reference to the syntax node corresponding to `id`.
975    ///
976    /// # Errors
977    /// Returns an error if `id` is not present in the arena.
978    pub fn node(
979        &self,
980        id: NodeId,
981    ) -> Result<&'a crate::navigator::DcSyntaxNode<'a>> {
982        self.arena
983            .get(id)
984            .context("NodeId not found in DcSyntaxArena")
985    }
986
987    /// Reports parsed nodes left over after typed projection.
988    ///
989    /// # Errors
990    /// Returns an error for missing nodes or if the policy rejects leftovers.
991    pub fn handle_remaining_nodes(&mut self, nodes: &[NodeId]) -> Result<()> {
992        for &node_id in nodes {
993            let node = self.node(node_id)?;
994            self.current_position = node.span.start;
995            self.handle_unconsumed_or_incomplete(
996                &[format!("Unconsumed Dc node: {:?}", node.kind)],
997                &[],
998            )?;
999        }
1000        Ok(())
1001    }
1002
1003    /// Skips a leading `Dc 641 "Global graph system block most recent node ID at time of document creation"`
1004    /// or `Dc 340 "Begin execution environment description"` document header node when present before the payload root(s).
1005    #[must_use]
1006    pub fn strip_leading_document_most_recent_root<'r>(
1007        &self,
1008        roots: &'r [NodeId],
1009    ) -> &'r [NodeId] {
1010        if roots.len() > 1
1011            && let Some(&first_id) = roots.first()
1012            && let Ok(first_node) = self.node(first_id)
1013            && (matches!(
1014                &first_node.kind,
1015                DcSyntaxKind::Tagged { tag, .. }
1016                    if self.tokens_equivalent(
1017                        *tag,
1018                        ctb_formats_dcdata::dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID,
1019                    )
1020            ) || matches!(
1021                &first_node.kind,
1022                DcSyntaxKind::Container { opener, .. }
1023                    if self.tokens_equivalent(
1024                        *opener,
1025                        ctb_formats_dcdata::dc::DC_BEGIN_ENVIRONMENT_DESCRIPTION,
1026                    )
1027            ))
1028            && let Some(tail) = roots.get(1..)
1029        {
1030            return tail;
1031        }
1032        roots
1033    }
1034
1035    /// Returns anomalies retained during projection, including quiet recovery.
1036    #[must_use]
1037    pub fn diagnostics(
1038        &self,
1039    ) -> &[ctb_formats_dcdata::syntax::SyntaxDiagnostic] {
1040        &self.diagnostics
1041    }
1042
1043    /// Records a projection anomaly and applies the caller's chosen action.
1044    ///
1045    /// # Errors
1046    /// Returns an error when the action rejects the anomaly.
1047    pub fn handle_diagnostic(
1048        &mut self,
1049        action: crate::DiagnosticAction,
1050        message: impl Into<String>,
1051    ) -> Result<()> {
1052        let message = message.into();
1053        self.diagnostics
1054            .push(ctb_formats_dcdata::syntax::SyntaxDiagnostic {
1055                message: message.clone(),
1056                token_offset: self.current_position,
1057                is_error: action == crate::DiagnosticAction::Error,
1058            });
1059        self.policy.handle(action, message)
1060    }
1061
1062    /// Checks for unconsumed Dc elements or missing required fields after decoding
1063    /// a container or document, consulting the projection policy in a single place.
1064    ///
1065    /// # Errors
1066    /// Returns an error if the active policy rejects unconsumed elements or missing fields.
1067    pub fn handle_unconsumed_or_incomplete(
1068        &mut self,
1069        unconsumed_descriptions: &[String],
1070        missing_fields: &[&'static str],
1071    ) -> Result<()> {
1072        for desc in unconsumed_descriptions {
1073            self.handle_diagnostic(self.policy.unknown_field, desc.as_str())?;
1074        }
1075        for field in missing_fields {
1076            self.handle_diagnostic(
1077                self.policy.missing_required_field,
1078                format!("Missing required field `{field}`"),
1079            )?;
1080        }
1081        Ok(())
1082    }
1083
1084    #[doc(hidden)]
1085    pub fn enter_record(&mut self) {
1086        self.record_depth = self.record_depth.saturating_add(1);
1087    }
1088
1089    #[doc(hidden)]
1090    pub fn leave_record(&mut self) {
1091        self.record_depth = self.record_depth.saturating_sub(1);
1092    }
1093
1094    /// Executes `f` while tracking projection recursion depth against `policy.max_depth`.
1095    pub fn with_projection_depth<R>(
1096        &mut self,
1097        node_id: NodeId,
1098        f: impl FnOnce(&mut Self) -> Result<R>,
1099    ) -> Result<R> {
1100        let total_depth =
1101            self.record_depth.saturating_add(self.container_depth);
1102        if total_depth >= self.policy.max_depth {
1103            if let Ok(node) = self.node(node_id) {
1104                self.current_position = node.span.start;
1105            }
1106            let msg = format!(
1107                "Projection nesting depth exceeds maximum limit ({}) at offset {}",
1108                self.policy.max_depth, self.current_position
1109            );
1110            self.handle_diagnostic(
1111                self.policy.depth_limit_exceeded,
1112                msg.clone(),
1113            )?;
1114            bail!("{msg}");
1115        }
1116        self.container_depth = self.container_depth.saturating_add(1);
1117        let res = f(self);
1118        self.container_depth = self.container_depth.saturating_sub(1);
1119        res
1120    }
1121
1122    #[doc(hidden)]
1123    pub fn annotate_field(
1124        &mut self,
1125        owner: &'static str,
1126        field: &'static str,
1127        span: Range<usize>,
1128    ) {
1129        if self.annotating {
1130            self.annotations.push(DcFieldAnnotation::new(
1131                owner,
1132                field,
1133                span,
1134                self.record_depth,
1135            ));
1136        }
1137    }
1138
1139    #[doc(hidden)]
1140    pub fn annotate_node_field(
1141        &mut self,
1142        owner: &'static str,
1143        field: &'static str,
1144        node_id: NodeId,
1145    ) {
1146        if self.annotating {
1147            if let Ok(node) = self.node(node_id) {
1148                if let Ok(range) = node.span.to_usize_range() {
1149                    self.annotate_field(owner, field, range);
1150                }
1151            }
1152        }
1153    }
1154
1155    #[doc(hidden)]
1156    pub fn annotate_map_field(
1157        &mut self,
1158        owner: &'static str,
1159        field: &'static str,
1160        span: Range<usize>,
1161        encoding: crate::DcKvMapEncoding,
1162    ) {
1163        if self.annotating {
1164            self.annotations.push(
1165                DcFieldAnnotation::new(owner, field, span, self.record_depth)
1166                    .with_map_encoding(encoding),
1167            );
1168        }
1169    }
1170
1171    #[doc(hidden)]
1172    pub fn annotate_node_map_field(
1173        &mut self,
1174        owner: &'static str,
1175        field: &'static str,
1176        node_id: NodeId,
1177        encoding: crate::DcKvMapEncoding,
1178    ) {
1179        if self.annotating {
1180            if let Ok(node) = self.node(node_id) {
1181                if let Ok(range) = node.span.to_usize_range() {
1182                    self.annotate_map_field(owner, field, range, encoding);
1183                }
1184            }
1185        }
1186    }
1187
1188    /// Resolves a shared reference name against the local or outer shared context.
1189    pub fn resolve_shared<T: std::any::Any + Send + Sync>(
1190        &self,
1191        binding: impl Into<crate::DcMstring>,
1192    ) -> Result<Arc<T>> {
1193        let binding = binding.into();
1194        if self.reference_scope.contains(&binding) {
1195            return self.reference_scope.resolve(binding);
1196        }
1197        self.shared_context
1198            .context("Shared reference requires a document context")?
1199            .resolve(binding)
1200    }
1201
1202    /// Enters a local lexical scope (`Dc 541`).
1203    pub fn enter_reference_scope(&mut self) {
1204        self.reference_scope.enter_scope();
1205    }
1206
1207    /// Exits a local lexical scope (`Dc 542`).
1208    pub fn exit_reference_scope(&mut self) -> Result<()> {
1209        self.reference_scope.exit_scope()
1210    }
1211
1212    /// Decodes an assignment declaration (`Dc 269`) and registers it in the local reference scope.
1213    pub fn decode_declaration<
1214        T: std::any::Any + Send + Sync + DcMixedDecode + 'static,
1215    >(
1216        &mut self,
1217        node_id: NodeId,
1218    ) -> Result<Arc<T>> {
1219        if let Some((ident_mstr, value)) =
1220            self.arena.decode_assignment_with_resolver(node_id, self.resolver())
1221        {
1222            let decoded = T::decode_dc_node(self, value)?;
1223            let arc = Arc::new(decoded);
1224            self.reference_scope.insert(ident_mstr, Arc::clone(&arc))?;
1225            Ok(arc)
1226        } else {
1227            let node = self.node(node_id)?;
1228            bail!(
1229                "Expected assignment declaration (Dc 269), found {:?}",
1230                node.kind
1231            )
1232        }
1233    }
1234
1235    /// Returns true if `token` represents a full or partial alternative-representation wrapper.
1236    #[must_use]
1237    pub fn is_representation_set_token(&self, token: u128) -> bool {
1238        self.resolver().is_representation_set(token)
1239            || self.token_fills_role(
1240                DcChar::from_u128(token),
1241                DcRole::EquivalentRepresentations,
1242            )
1243            || self.token_fills_role(
1244                DcChar::from_u128(token),
1245                DcRole::PartiallyEquivalentRepresentations,
1246            )
1247    }
1248
1249    /// Returns true if `node` is an alternative-representation container or tagged construct.
1250    #[must_use]
1251    pub fn is_representation_set_node(
1252        &self,
1253        node: &crate::navigator::DcSyntaxNode<'_>,
1254    ) -> bool {
1255        node.semantic_token()
1256            .is_some_and(|token| self.is_representation_set_token(token))
1257    }
1258
1259    /// Finds an assignment declaration (`ident = value` or `lang.assign(ident, value)`) in the arena
1260    /// by its identifier name, searching in reverse document order.
1261    #[must_use]
1262    pub fn find_bound_assignment(
1263        &self,
1264        name: &crate::DcMstr,
1265    ) -> Option<NodeId> {
1266        let last_idx = self.arena.nodes().len().checked_sub(1)?;
1267        self.find_bound_assignment_at(name, NodeId(last_idx))
1268    }
1269
1270    /// Finds an assignment declaration (`ident = value` or `lang.assign(ident, value)`) visible
1271    /// at `at_node_id`, honoring `Dc 541 "Enter identifier scope"` .. `Dc 542 "Exit identifier scope"`
1272    /// lexical scope boundaries and reverse-chronological shadowing prior to `at_node_id`.
1273    #[must_use]
1274    pub fn find_bound_assignment_at(
1275        &self,
1276        name: &crate::DcMstr,
1277        at_node_id: NodeId,
1278    ) -> Option<NodeId> {
1279        let resolver = self.resolver();
1280        let ref_span = self.arena.get(at_node_id)?.span;
1281        let nodes = self.arena.nodes();
1282
1283        let is_in_scope_for_ref = |assign_idx: usize| -> bool {
1284            let Some(assign_node) = nodes.get(assign_idx) else {
1285                return false;
1286            };
1287            let assign_span = assign_node.span;
1288            for scope_node in nodes {
1289                if let DcSyntaxKind::Container { opener, .. } = &scope_node.kind
1290                    && self.token_fills_role(*opener, DcRole::EnterIdentifierScope)
1291                {
1292                    let scope_span = scope_node.span;
1293                    let encloses_assign = scope_span.start <= assign_span.start
1294                        && assign_span.end <= scope_span.end;
1295                    if encloses_assign {
1296                        let encloses_ref = scope_span.start <= ref_span.start
1297                            && ref_span.end <= scope_span.end;
1298                        if !encloses_ref {
1299                            return false;
1300                        }
1301                    }
1302                }
1303            }
1304            true
1305        };
1306
1307        let upper_preceding = at_node_id.0.min(nodes.len().saturating_sub(1));
1308        for idx in (0..=upper_preceding).rev() {
1309            if !is_in_scope_for_ref(idx) {
1310                continue;
1311            }
1312            if let Some((ident, value)) =
1313                self.arena.decode_assignment_with_resolver(NodeId(idx), resolver)
1314            {
1315                let ident_mstr: &crate::DcMstr = ident.as_ref();
1316                if ident_mstr == name {
1317                    return Some(value);
1318                }
1319            }
1320        }
1321
1322        for idx in (upper_preceding.saturating_add(1)..nodes.len()).rev() {
1323            if !is_in_scope_for_ref(idx) {
1324                continue;
1325            }
1326            if let Some((ident, value)) =
1327                self.arena.decode_assignment_with_resolver(NodeId(idx), resolver)
1328            {
1329                let ident_mstr: &crate::DcMstr = ident.as_ref();
1330                if ident_mstr == name {
1331                    return Some(value);
1332                }
1333            }
1334        }
1335        None
1336    }
1337
1338    /// Resolves a bound or named reference to its value's CST `NodeId` if possible.
1339    pub fn resolve_expression_node(
1340        &self,
1341        node_id: NodeId,
1342    ) -> Result<Option<NodeId>> {
1343        if let Some(ident_name) = self.unwrap_bound_reference(node_id)? {
1344            if let Some(assigned_id) =
1345                self.find_bound_assignment_at(&ident_name, node_id)
1346            {
1347                return Ok(Some(assigned_id));
1348            }
1349        }
1350        Ok(None)
1351    }
1352
1353    /// Resolves an expression node to its target `NodeId`, or returns `node_id` unchanged.
1354    pub fn resolve_expression_or_self(
1355        &self,
1356        node_id: NodeId,
1357    ) -> Result<NodeId> {
1358        if let Some(resolved) = self.resolve_expression_node(node_id)? {
1359            if resolved != node_id {
1360                return Ok(resolved);
1361            }
1362        }
1363        Ok(node_id)
1364    }
1365
1366    fn collect_transparent_candidates(
1367        &self,
1368        node_id: NodeId,
1369        unwrap_optional: bool,
1370        visited: &mut Vec<NodeId>,
1371        out: &mut Vec<NodeId>,
1372    ) -> Result<()> {
1373        if visited.contains(&node_id) {
1374            bail!(
1375                "Cycle detected while unwrapping transparent Dc wrappers at {node_id:?}"
1376            );
1377        }
1378        visited.push(node_id);
1379        let node = self.node(node_id)?;
1380        if self.is_representation_set_node(node) {
1381            let raw_children = match &node.kind {
1382                DcSyntaxKind::Container { children, .. } => children.as_slice(),
1383                DcSyntaxKind::Tagged { args, .. } => {
1384                    if let Some(&first_arg) = args.first() {
1385                        let arg_node = self.node(first_arg)?;
1386                        if arg_node.is_structural_container_with(self.resolver())
1387                            && let DcSyntaxKind::Container { children, .. } =
1388                                &arg_node.kind
1389                        {
1390                            children.as_slice()
1391                        } else {
1392                            args.as_slice()
1393                        }
1394                    } else {
1395                        &[]
1396                    }
1397                }
1398                _ => &[],
1399            };
1400            let mut found_any = false;
1401            for &child_id in raw_children {
1402                let child = self.node(child_id)?;
1403                if let DcSyntaxKind::Atom(ch) = child.kind {
1404                    if self.token_fills_role(ch, DcRole::TypeAny)
1405                        || self
1406                            .token_fills_role(ch, DcRole::ListElementSeparator)
1407                        || self
1408                            .resolver()
1409                            .is_representation_header_or_separator(ch.to_u128())
1410                    {
1411                        continue;
1412                    }
1413                }
1414                found_any = true;
1415                self.collect_transparent_candidates(
1416                    child_id,
1417                    unwrap_optional,
1418                    visited,
1419                    out,
1420                )?;
1421            }
1422            visited.pop();
1423            ensure!(found_any, "Empty equivalent representations list");
1424            return Ok(());
1425        }
1426
1427        if unwrap_optional
1428            && let Some((head, children)) = node.head_and_children()
1429            && self.token_fills_role(head, DcRole::OptionalPresent)
1430        {
1431            let inner_id = *children
1432                .first()
1433                .context("Empty optional construct (Dc 315)")?;
1434            let res = self.collect_transparent_candidates(
1435                inner_id,
1436                unwrap_optional,
1437                visited,
1438                out,
1439            );
1440            visited.pop();
1441            return res;
1442        }
1443
1444        if let Some(resolved) = self.resolve_expression_node(node_id)? {
1445            if resolved != node_id {
1446                let res = self.collect_transparent_candidates(
1447                    resolved,
1448                    unwrap_optional,
1449                    visited,
1450                    out,
1451                );
1452                visited.pop();
1453                return res;
1454            }
1455        }
1456
1457        out.push(node_id);
1458        visited.pop();
1459        Ok(())
1460    }
1461
1462    /// Extracts all concrete candidate node IDs after unwrapping optional (`Dc 315`),
1463    /// expression (`Dc 540`, `Dc 276`, `Dc 279`), and equivalent/partially-equivalent
1464    /// (`Dc 397`, `Dc 538`) wrappers.
1465    pub fn transparent_candidates(
1466        &self,
1467        node_id: NodeId,
1468    ) -> Result<Vec<NodeId>> {
1469        let mut visited = Vec::new();
1470        let mut out = Vec::new();
1471        self.collect_transparent_candidates(
1472            node_id,
1473            true,
1474            &mut visited,
1475            &mut out,
1476        )?;
1477        ensure!(!out.is_empty(), "Empty equivalent representations list");
1478        Ok(out)
1479    }
1480
1481    /// Extracts all candidate representation node IDs from an equivalent or partially
1482    /// equivalent representations container (`Dc 397` or `Dc 398`), filtering out
1483    /// type headers and list element separators.
1484    ///
1485    /// If `node_id` is not an equivalent representation set, returns a single-element
1486    /// vector containing `node_id`.
1487    pub fn equivalent_candidates(
1488        &self,
1489        node_id: NodeId,
1490    ) -> Result<Vec<NodeId>> {
1491        let mut visited = Vec::new();
1492        let mut out = Vec::new();
1493        self.collect_transparent_candidates(
1494            node_id,
1495            false,
1496            &mut visited,
1497            &mut out,
1498        )?;
1499        ensure!(!out.is_empty(), "Empty equivalent representations list");
1500        Ok(out)
1501    }
1502
1503    /// Unwraps equivalent representation containers (`Dc 397` or `Dc 398`) to a child
1504    /// matching the predicate, or the first valid candidate if none or no predicate given.
1505    pub fn unwrap_equivalent_matching<F>(
1506        &self,
1507        node_id: NodeId,
1508        mut predicate: F,
1509    ) -> Result<NodeId>
1510    where
1511        F: FnMut(NodeId) -> bool,
1512    {
1513        let candidates = self.equivalent_candidates(node_id)?;
1514        for &cand_id in &candidates {
1515            if predicate(cand_id)
1516                || self.unwrap_transparent(cand_id).is_ok_and(|unwrapped| {
1517                    unwrapped != cand_id && predicate(unwrapped)
1518                })
1519            {
1520                return Ok(cand_id);
1521            }
1522        }
1523        candidates
1524            .first()
1525            .copied()
1526            .context("Empty equivalent representations list")
1527    }
1528
1529    /// Unwraps equivalent representation containers (`Dc 397` or `Dc 398`) or expression
1530    /// nodes (`Dc 540`, `Dc 276`, `Dc 279`) to their primary child.
1531    pub fn unwrap_equivalent_or_self(&self, node_id: NodeId) -> Result<NodeId> {
1532        let candidates = self.equivalent_candidates(node_id)?;
1533        candidates
1534            .first()
1535            .copied()
1536            .context("Empty equivalent representations list")
1537    }
1538
1539    fn decode_candidates<T, F>(
1540        &mut self,
1541        candidates: &[NodeId],
1542        mut decode_fn: F,
1543    ) -> Result<T>
1544    where
1545        F: FnMut(&mut Self, NodeId) -> Result<T>,
1546    {
1547        if candidates.is_empty() {
1548            bail!("Empty equivalent representations candidate set");
1549        }
1550        if let [single] = candidates {
1551            return decode_fn(self, *single);
1552        }
1553        let mut first_recovered: Option<(
1554            T,
1555            Vec<ctb_formats_dcdata::syntax::SyntaxDiagnostic>,
1556            Vec<DcFieldAnnotation>,
1557            u64,
1558        )> = None;
1559        let mut last_err = None;
1560        for &cand_id in candidates {
1561            let saved_diag_len = self.diagnostics.len();
1562            let saved_ann_len = self.annotations.len();
1563            let saved_pos = self.current_position;
1564            match decode_fn(self, cand_id) {
1565                Ok(val) if self.diagnostics.len() == saved_diag_len => {
1566                    return Ok(val);
1567                }
1568                Ok(val) => {
1569                    if first_recovered.is_none() {
1570                        let new_diags =
1571                            self.diagnostics.split_off(saved_diag_len);
1572                        let new_anns =
1573                            self.annotations.split_off(saved_ann_len);
1574                        first_recovered = Some((
1575                            val,
1576                            new_diags,
1577                            new_anns,
1578                            self.current_position,
1579                        ));
1580                    } else {
1581                        self.diagnostics.truncate(saved_diag_len);
1582                        self.annotations.truncate(saved_ann_len);
1583                    }
1584                    self.current_position = saved_pos;
1585                }
1586                Err(err) => {
1587                    self.diagnostics.truncate(saved_diag_len);
1588                    self.annotations.truncate(saved_ann_len);
1589                    self.current_position = saved_pos;
1590                    last_err = Some(err);
1591                }
1592            }
1593        }
1594        if let Some((val, diags, anns, pos)) = first_recovered {
1595            self.diagnostics.extend(diags);
1596            self.annotations.extend(anns);
1597            self.current_position = pos;
1598            return Ok(val);
1599        }
1600        if let Some(err) = last_err {
1601            Err(err)
1602        } else {
1603            bail!("Empty equivalent representations candidate set")
1604        }
1605    }
1606
1607    /// Attempts to decode a typed value from an equivalent representation set by
1608    /// testing candidate representation children in sequence and selecting the first
1609    /// candidate that decodes cleanly without error.
1610    pub fn decode_equivalent<T, F>(
1611        &mut self,
1612        node_id: NodeId,
1613        decode_fn: F,
1614    ) -> Result<T>
1615    where
1616        F: FnMut(&mut Self, NodeId) -> Result<T>,
1617    {
1618        let candidates = self.equivalent_candidates(node_id)?;
1619        self.decode_candidates(&candidates, decode_fn)
1620    }
1621
1622    /// Transparently decodes a target type from `node_id`, unwrapping optionals (`Dc 315`),
1623    /// resolving bound references (`Dc 540`, `Dc 276`) and routine invocations (`Dc 279`),
1624    /// and selecting a candidate from equivalent or partially equivalent representation sets
1625    /// (`Dc 397`, `Dc 398`) that decodes cleanly.
1626    pub fn decode_transparent<T, F>(
1627        &mut self,
1628        node_id: NodeId,
1629        decode_fn: F,
1630    ) -> Result<T>
1631    where
1632        F: FnMut(&mut Self, NodeId) -> Result<T>,
1633    {
1634        let candidates = self.transparent_candidates(node_id)?;
1635        self.decode_candidates(&candidates, decode_fn)
1636    }
1637
1638    /// Extracts the field tag, value node, and source node for a struct or variant child node.
1639    pub fn extract_field_projection_spec(
1640        &self,
1641        child_id: NodeId,
1642    ) -> Result<FieldProjectionSpec> {
1643        let child_node = self.node(child_id)?;
1644        let (tag, value_node) = match &child_node.kind {
1645            DcSyntaxKind::Tagged { tag, args } => {
1646                if self.resolver().is_assignment_construct(tag.to_u128()) {
1647                    (crate::dc::DC_ASSIGN.to_u128(), child_id)
1648                } else {
1649                    let arg_id = match args.as_slice() {
1650                        [single_arg] => *single_arg,
1651                        _ => child_id,
1652                    };
1653                    (tag.to_u128(), arg_id)
1654                }
1655            }
1656            DcSyntaxKind::Container { opener, .. } => {
1657                (opener.to_u128(), child_id)
1658            }
1659            DcSyntaxKind::Atom(ch) => (ch.to_u128(), child_id),
1660            _ => (0, child_id),
1661        };
1662        Ok(FieldProjectionSpec {
1663            tag,
1664            value_node,
1665            source_node: child_id,
1666        })
1667    }
1668
1669    /// Evaluates a field-decoding closure across transparent candidates (`Dc 397`, `Dc 398`,
1670    /// `Dc 315`) when a struct or enum-variant field entry is wrapped in a representation set.
1671    pub fn decode_field_candidates<F>(
1672        &mut self,
1673        spec: FieldProjectionSpec,
1674        mut decode_fn: F,
1675    ) -> Result<(FieldProjectionSpec, Result<bool>)>
1676    where
1677        F: FnMut(&mut Self, FieldProjectionSpec) -> Result<bool>,
1678    {
1679        let raw_node = self.node(spec.source_node)?;
1680        let is_wrapped = self.is_representation_set_node(raw_node)
1681            || raw_node.head_and_children().is_some_and(|(opener, _)| {
1682                self.token_fills_role(opener, DcRole::OptionalPresent)
1683            });
1684        if !is_wrapped {
1685            let res = decode_fn(self, spec);
1686            return Ok((spec, res));
1687        }
1688        let candidates = self.transparent_candidates(spec.source_node)?;
1689        if let [single] = candidates.as_slice() {
1690            let resolved = self.extract_field_projection_spec(*single)?;
1691            let res = decode_fn(self, resolved);
1692            return Ok((resolved, res));
1693        }
1694        let mut fallback_spec = None;
1695        for &cand_id in &candidates {
1696            let cand_spec = self.extract_field_projection_spec(cand_id)?;
1697            if cand_spec.tag == 0 {
1698                continue;
1699            }
1700            let saved_diag_len = self.diagnostics.len();
1701            let saved_ann_len = self.annotations.len();
1702            let saved_pos = self.current_position;
1703            match decode_fn(self, cand_spec) {
1704                Ok(true) if self.diagnostics.len() == saved_diag_len => {
1705                    return Ok((cand_spec, Ok(true)));
1706                }
1707                Ok(true) => {
1708                    if fallback_spec.is_none() {
1709                        fallback_spec = Some(cand_spec);
1710                    }
1711                    self.diagnostics.truncate(saved_diag_len);
1712                    self.annotations.truncate(saved_ann_len);
1713                    self.current_position = saved_pos;
1714                }
1715                Ok(false) => {
1716                    self.diagnostics.truncate(saved_diag_len);
1717                    self.annotations.truncate(saved_ann_len);
1718                    self.current_position = saved_pos;
1719                }
1720                Err(_) => {
1721                    if fallback_spec.is_none() {
1722                        fallback_spec = Some(cand_spec);
1723                    }
1724                    self.diagnostics.truncate(saved_diag_len);
1725                    self.annotations.truncate(saved_ann_len);
1726                    self.current_position = saved_pos;
1727                }
1728            }
1729        }
1730        let chosen = if let Some(fb) = fallback_spec {
1731            fb
1732        } else if let Some(&first_id) = candidates.first() {
1733            self.extract_field_projection_spec(first_id)?
1734        } else {
1735            spec
1736        };
1737        let res = decode_fn(self, chosen);
1738        Ok((chosen, res))
1739    }
1740
1741    /// Unwraps an optional marker (`Dc 315` or `Dc 316`).
1742    /// Returns `Ok(None)` for absent, `Ok(Some(inner_id))` for present.
1743    pub fn unwrap_optional_node(
1744        &mut self,
1745        node_id: NodeId,
1746    ) -> Result<Option<NodeId>> {
1747        self.decode_equivalent(node_id, |ctx, cand_id| {
1748            // Reason for fallback: when candidate node is not an expression/reference or cannot be resolved, candidate node itself is used directly.
1749            let cand_id =
1750                ctx.resolve_expression_node(cand_id)?.unwrap_or(cand_id);
1751            let node = ctx.node(cand_id)?;
1752            if let Some((head, children)) = node.head_and_children()
1753                && ctx.token_fills_role(head, DcRole::OptionalPresent)
1754            {
1755                let inner = children
1756                    .first()
1757                    .copied()
1758                    .context("Empty optional construct (Dc 315)")?;
1759                return Ok(Some(inner));
1760            }
1761            match &node.kind {
1762                DcSyntaxKind::Atom(ch)
1763                    if ctx.token_fills_role(*ch, DcRole::OptionalAbsent) =>
1764                {
1765                    Ok(None)
1766                }
1767                _ => Ok(Some(cand_id)),
1768            }
1769        })
1770    }
1771
1772    /// Unwraps a format representation container (`511 [format] [payload] 512`).
1773    /// Returns `Ok(Some((format, payload_id)))` if this is a format representation.
1774    pub fn unwrap_format_representation(
1775        &self,
1776        node_id: NodeId,
1777    ) -> Result<Option<(DcChar, NodeId)>> {
1778        let node_id = self.unwrap_equivalent_matching(node_id, |cand_id| {
1779            if let Ok(cand) = self.node(cand_id) {
1780                if let DcSyntaxKind::Container { opener, .. } = &cand.kind {
1781                    self.token_fills_role(
1782                        *opener,
1783                        DcRole::BeginFormatRepresentation,
1784                    )
1785                } else {
1786                    false
1787                }
1788            } else {
1789                false
1790            }
1791        })?;
1792        let node = self.node(node_id)?;
1793        if let DcSyntaxKind::Container {
1794            opener, children, ..
1795        } = &node.kind
1796        {
1797            if self.token_fills_role(*opener, DcRole::BeginFormatRepresentation)
1798            {
1799                if let [single_child] = children.as_slice() {
1800                    let child_node = self.node(*single_child)?;
1801                    if let DcSyntaxKind::Tagged { tag, args } = &child_node.kind
1802                    {
1803                        let payload_id = if let [single_arg] = args.as_slice() {
1804                            *single_arg
1805                        } else {
1806                            *single_child
1807                        };
1808                        return Ok(Some((*tag, payload_id)));
1809                    }
1810                }
1811                if let (Some(&c0), Some(&c1)) =
1812                    (children.first(), children.get(1))
1813                {
1814                    let fmt_node = self.node(c0)?;
1815                    let format = match &fmt_node.kind {
1816                        DcSyntaxKind::Atom(ch) => *ch,
1817                        DcSyntaxKind::Tagged { tag, .. } => *tag,
1818                        other => bail!(
1819                            "Expected Atom for format token in Dc 511, found {other:?}"
1820                        ),
1821                    };
1822                    let canon_format = self.canonical_token(format);
1823                    let is_sequence_format =
1824                        FormatId::from_dc_id(canon_format.to_u128())
1825                            .and_then(|fid| {
1826                                self.resolver().format_rule_payload_arity(fid)
1827                            })
1828                            .is_some_and(|n| n >= 2);
1829                    let payload_id = if children.len() > 2 {
1830                        let c1_node = self.node(c1)?;
1831                        if let DcSyntaxKind::Atom(ch) = c1_node.kind {
1832                            if (self.token_fills_role(
1833                                ch,
1834                                DcRole::EquivalentRepresentations,
1835                            ) || self.token_fills_role(
1836                                ch,
1837                                DcRole::PartiallyEquivalentRepresentations,
1838                            )) && children.get(2).is_some()
1839                            {
1840                                *children.get(2).context(
1841                                    "Missing equivalent candidate payload",
1842                                )?
1843                            } else if is_sequence_format {
1844                                node_id
1845                            } else {
1846                                c1
1847                            }
1848                        } else if is_sequence_format {
1849                            node_id
1850                        } else {
1851                            c1
1852                        }
1853                    } else {
1854                        c1
1855                    };
1856                    return Ok(Some((format, payload_id)));
1857                }
1858                bail!(
1859                    "Format representation container (Dc 511) has fewer than 2 children"
1860                );
1861            }
1862        }
1863        Ok(None)
1864    }
1865
1866    /// Unwraps a bound reference (`Dc 540` or `Dc 276` + identifier).
1867    pub fn unwrap_bound_reference(
1868        &self,
1869        node_id: NodeId,
1870    ) -> Result<Option<crate::DcMstring>> {
1871        let node = self.node(node_id)?;
1872        let Some((head, children)) = node.head_and_children() else {
1873            return Ok(None);
1874        };
1875        if !self.token_fills_role(head, DcRole::ReferenceBoundValue)
1876            && !self.token_fills_role(head, DcRole::ReferenceNamedObject)
1877        {
1878            return Ok(None);
1879        }
1880        if let Some(&child_id) = children.first()
1881            && let Some(name) = self
1882                .arena
1883                .decode_identifier_with_resolver(child_id, self.resolver())
1884        {
1885            return Ok(Some(name));
1886        }
1887        bail!("Malformed bound reference under {head}")
1888    }
1889
1890    /// Repeatedly unwraps transparent wrappers (`397`/`398`/`561` equivalent lists,
1891    /// `315` optionals, and `540`/`276` reference nodes), using `predicate`
1892    /// to select a preferred candidate child from representation sets.
1893    pub fn unwrap_transparent_matching<F>(
1894        &self,
1895        mut node_id: NodeId,
1896        mut predicate: F,
1897    ) -> Result<NodeId>
1898    where
1899        F: FnMut(NodeId) -> bool,
1900    {
1901        let mut visited = Vec::new();
1902        loop {
1903            if visited.contains(&node_id) {
1904                bail!(
1905                    "Cycle detected while unwrapping transparent Dc wrappers at {node_id:?}"
1906                );
1907            }
1908            visited.push(node_id);
1909            let node = self.node(node_id)?;
1910            let next_id = if let Some((head, children)) =
1911                node.head_and_children()
1912                && (self.is_representation_set_token(head.to_u128())
1913                    || self.token_fills_role(head, DcRole::OptionalPresent))
1914            {
1915                if self.is_representation_set_token(head.to_u128()) {
1916                    let unwrapped = self
1917                        .unwrap_equivalent_matching(node_id, &mut predicate)?;
1918                    ensure!(
1919                        unwrapped != node_id,
1920                        "Empty equivalent representation construct (Dc {head})"
1921                    );
1922                    unwrapped
1923                } else {
1924                    *children
1925                        .first()
1926                        .context("Empty optional construct (Dc 315)")?
1927                }
1928            } else if let Some(resolved) =
1929                self.resolve_expression_node(node_id)?
1930            {
1931                if resolved == node_id {
1932                    return Ok(node_id);
1933                }
1934                resolved
1935            } else {
1936                return Ok(node_id);
1937            };
1938            node_id = next_id;
1939        }
1940    }
1941
1942    /// Repeatedly unwraps transparent wrappers (`397`/`398`/`561` equivalent lists,
1943    /// `315` optionals, and `540`/`276`/`279` expression nodes).
1944    pub fn unwrap_transparent(&self, node_id: NodeId) -> Result<NodeId> {
1945        self.unwrap_transparent_matching(node_id, |_| false)
1946    }
1947
1948    /// Extracts key-value map entries from a `Dc 559..560` or legacy `Dc 313..314`
1949    /// container, returning the map encoding and per-entry `(key_id, val_id, span, start_pos)`
1950    /// results so callers can process valid entries before reporting a later malformed entry.
1951    ///
1952    /// # Errors
1953    /// Returns an error if `node_id` is not a key-value map container.
1954    pub fn extract_kv_map_entries(
1955        &mut self,
1956        node_id: NodeId,
1957    ) -> Result<(
1958        crate::DcKvMapEncoding,
1959        Vec<Result<(NodeId, NodeId, Range<usize>, u64)>>,
1960    )> {
1961        let node = self.node(node_id)?;
1962        let (opener, children) = match &node.kind {
1963            DcSyntaxKind::Container {
1964                opener, children, ..
1965            } if self.token_fills_role(*opener, DcRole::BeginKvMap)
1966                || self.token_fills_role(*opener, DcRole::BeginLegacyKvMap) =>
1967            {
1968                (*opener, children)
1969            }
1970            other => bail!(
1971                "Expected KvMap container (Dc 559 or 313), found {other:?}"
1972            ),
1973        };
1974
1975        let encoding = if self.token_fills_role(opener, DcRole::BeginKvMap) {
1976            crate::DcKvMapEncoding::Pairs
1977        } else {
1978            crate::DcKvMapEncoding::Legacy
1979        };
1980
1981        let mut slice = children.as_slice();
1982        while let Some((&first_id, rest)) = slice.split_first() {
1983            let first_node = self.node(first_id)?;
1984            if let DcSyntaxKind::Atom(ch) = first_node.kind {
1985                if self.token_fills_role(ch, DcRole::TypeAny)
1986                    || self.token_fills_role(ch, DcRole::TypeToken)
1987                {
1988                    slice = rest;
1989                    continue;
1990                }
1991            }
1992            break;
1993        }
1994
1995        let mut entries = Vec::new();
1996        if encoding == crate::DcKvMapEncoding::Pairs {
1997            for &entry_id in slice {
1998                let entry_node = self.node(entry_id)?;
1999                if !entry_node.is_escaped_atom()
2000                    && let DcSyntaxKind::Atom(ch) = entry_node.kind
2001                {
2002                    if self.token_fills_role(ch, DcRole::ListElementSeparator) {
2003                        continue;
2004                    }
2005                }
2006                match &entry_node.kind {
2007                    DcSyntaxKind::Container {
2008                        opener: pair_opener,
2009                        children: pair_children,
2010                        unclosed,
2011                        ..
2012                    } if self.token_fills_role(
2013                        *pair_opener,
2014                        DcRole::BeginKvPair,
2015                    ) =>
2016                    {
2017                        if *unclosed {
2018                            entries.push(Err(anyhow::anyhow!(
2019                                "Unclosed key-value pair container (Dc 514)"
2020                            )));
2021                            continue;
2022                        }
2023                        let mut items = Vec::new();
2024                        for &pc_id in pair_children {
2025                            let pc_node = self.node(pc_id)?;
2026                            if !pc_node.is_escaped_atom()
2027                                && let DcSyntaxKind::Atom(ch) = pc_node.kind
2028                            {
2029                                if self.token_fills_role(
2030                                    ch,
2031                                    DcRole::ListElementSeparator,
2032                                ) {
2033                                    continue;
2034                                }
2035                            }
2036                            items.push(pc_id);
2037                        }
2038                        if let [k_id, val_id] = items.as_slice() {
2039                            let span = entry_node.span.to_usize_range()?;
2040                            entries.push(Ok((
2041                                *k_id,
2042                                *val_id,
2043                                span,
2044                                entry_node.span.start,
2045                            )));
2046                        } else {
2047                            entries.push(Err(anyhow::anyhow!(
2048                                "Key-value pair (Dc 514) must have 2 elements, found {}",
2049                                items.len()
2050                            )));
2051                        }
2052                    }
2053                    other => {
2054                        entries.push(Err(anyhow::anyhow!(
2055                            "Expected KvPair container (Dc 514) inside KvMap, found {other:?}"
2056                        )));
2057                    }
2058                }
2059            }
2060        } else {
2061            let mut items = Vec::new();
2062            for &ch_id in slice {
2063                let ch_node = self.node(ch_id)?;
2064                if !ch_node.is_escaped_atom()
2065                    && let DcSyntaxKind::Atom(ch) = ch_node.kind
2066                {
2067                    if self.token_fills_role(ch, DcRole::ListElementSeparator) {
2068                        continue;
2069                    }
2070                }
2071                items.push(ch_id);
2072            }
2073            for chunk in items.chunks(2) {
2074                if let [k_id, val_id] = chunk {
2075                    let k_span = self.node(*k_id)?.span;
2076                    let v_span = self.node(*val_id)?.span;
2077                    let span = usize::try_from(k_span.start)?
2078                        ..usize::try_from(v_span.end)?;
2079                    entries.push(Ok((*k_id, *val_id, span, k_span.start)));
2080                } else if let [k_id] = chunk {
2081                    let k_span = self.node(*k_id)?.span;
2082                    self.current_position = k_span.start;
2083                    entries.push(Err(anyhow::anyhow!(
2084                        "Uneven number of items in legacy map (Dc 313)"
2085                    )));
2086                }
2087            }
2088        }
2089
2090        Ok((encoding, entries))
2091    }
2092}
2093
2094// ----------------------------------------------------------------------------
2095// Primitive Implementations
2096// ----------------------------------------------------------------------------
2097
2098impl DcMixedEncode for String {
2099    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2100        self.as_str().encode_dc_mixed_to(mst)
2101    }
2102}
2103
2104impl<T: DcMixedEncode + ?Sized> DcMixedEncode for &T {
2105    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2106        (**self).encode_dc_mixed_to(mst)
2107    }
2108
2109    fn encode_dc_mixed_to_with_context(
2110        &self,
2111        mst: &mut crate::DcWriter<'_>,
2112        context: &SharedValueContext,
2113    ) -> Result<()> {
2114        (**self).encode_dc_mixed_to_with_context(mst, context)
2115    }
2116
2117    fn encode_format_elements_to_with_context(
2118        &self,
2119        format: DcChar,
2120        mst: &mut crate::DcWriter<'_>,
2121        context: &SharedValueContext,
2122    ) -> Result<()> {
2123        (**self).encode_format_elements_to_with_context(format, mst, context)
2124    }
2125}
2126
2127impl DcMixedDecode for crate::DcMstring {
2128    fn decode_dc_node(
2129        ctx: &mut DcProjectionContext<'_, '_>,
2130        node_id: NodeId,
2131    ) -> Result<Self> {
2132        ctx.decode_transparent(node_id, |ctx, node_id| {
2133            let resolver = ctx.resolver();
2134            if let Some((_header, decoded)) =
2135                ctx.arena.decode_literal_with_resolver(node_id, resolver)
2136            {
2137                Ok(decoded)
2138            } else if let Some(name) =
2139                ctx.arena.decode_identifier_with_resolver(node_id, resolver)
2140            {
2141                Ok(name)
2142            } else {
2143                let node = ctx.node(node_id)?;
2144                bail!(
2145                    "Expected Literal or Identifier node for DcMstring, found {:?}",
2146                    node.kind
2147                )
2148            }
2149        })
2150    }
2151}
2152
2153impl DcMixedEncode for crate::DcMstr {
2154    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2155        let dc_string = self.to_dc_string()?;
2156        dc_string.encode_dc_mixed_to(mst)
2157    }
2158}
2159
2160impl DcMixedEncode for crate::DcMstring {
2161    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2162        let mstr: &crate::DcMstr = self.as_ref();
2163        mstr.encode_dc_mixed_to(mst)
2164    }
2165}
2166
2167impl DcMixedDecode for crate::DcString {
2168    fn decode_dc_node(
2169        ctx: &mut DcProjectionContext<'_, '_>,
2170        node_id: NodeId,
2171    ) -> Result<Self> {
2172        ctx.decode_transparent(node_id, |ctx, node_id| {
2173            let mstr = crate::DcMstring::decode_dc_node(ctx, node_id)?;
2174            mstr.to_dc_string().map_err(|e| {
2175                anyhow::anyhow!("Failed to convert decoded literal/identifier to DcString: {e}")
2176            })
2177        })
2178    }
2179}
2180
2181impl DcMixedEncode for crate::DcStr {
2182    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2183        use ctb_formats_dcdata::DcCharExt;
2184        mst.push_char(DC_BEGIN_LITERAL)?;
2185        mst.push_char(DC_BEGIN_TYPE_DEF)?;
2186        mst.push_char(DC_TYPE_STRING)?;
2187        mst.push_char(DC_END_TYPE_DEF)?;
2188        for ch in self.chars() {
2189            if ch.fills_role(DcRole::Escape)
2190                || ch.fills_role(DcRole::EndLiteral)
2191            {
2192                mst.push_char(crate::dc::DC_ESCAPE)?;
2193            }
2194            mst.push_char(ch)?;
2195        }
2196        mst.push_char(DC_END_LITERAL)?;
2197        Ok(())
2198    }
2199}
2200
2201impl DcMixedEncode for crate::DcString {
2202    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2203        let dc_str: &crate::DcStr = self.as_ref();
2204        dc_str.encode_dc_mixed_to(mst)
2205    }
2206}
2207
2208impl DcMixedDecode for String {
2209    fn decode_dc_node(
2210        ctx: &mut DcProjectionContext<'_, '_>,
2211        node_id: NodeId,
2212    ) -> Result<Self> {
2213        ctx.decode_transparent(node_id, |ctx, node_id| {
2214            let mstr = crate::DcMstring::decode_dc_node(ctx, node_id)?;
2215            let dc_str = mstr.to_dc_string()?;
2216            let mut out = String::with_capacity(dc_str.len());
2217            for ch in dc_str.chars() {
2218                let c = ch.as_char().context(
2219                    "Cannot project non-Unicode DcMstr into a Rust String",
2220                )?;
2221                out.push(c);
2222            }
2223            Ok(out)
2224        })
2225    }
2226}
2227
2228impl DcMixedEncode for str {
2229    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2230        mst.push_char(DC_BEGIN_LITERAL)?;
2231        mst.push_char(DC_BEGIN_TYPE_DEF)?;
2232        mst.push_char(DC_TYPE_STRING)?;
2233        mst.push_char(DC_END_TYPE_DEF)?;
2234        mst.push_str(self)?;
2235        mst.push_char(DC_END_LITERAL)?;
2236        Ok(())
2237    }
2238}
2239
2240impl DcMixedEncode for bool {
2241    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2242        if *self {
2243            mst.push_char(DC_BOOLEAN_TRUE)?;
2244        } else {
2245            mst.push_char(DC_BOOLEAN_FALSE)?;
2246        }
2247        Ok(())
2248    }
2249}
2250
2251impl DcMixedDecode for bool {
2252    fn decode_dc_node(
2253        ctx: &mut DcProjectionContext<'_, '_>,
2254        node_id: NodeId,
2255    ) -> Result<Self> {
2256        ctx.decode_transparent(node_id, |ctx, node_id| {
2257            let node = ctx.node(node_id)?;
2258            match &node.kind {
2259                DcSyntaxKind::Atom(ch) => {
2260                    if ctx.token_fills_role(*ch, DcRole::BooleanTrue)
2261                        || ctx.token_fills_role(*ch, DcRole::Positive)
2262                    {
2263                        Ok(true)
2264                    } else if ctx.token_fills_role(*ch, DcRole::BooleanFalse)
2265                        || ctx.token_fills_role(*ch, DcRole::Negative)
2266                    {
2267                        Ok(false)
2268                    } else {
2269                        bail!("Expected boolean indicator (Dc 517, 518, 10, or 11), found {ch:?}")
2270                    }
2271                }
2272                other => bail!("Expected Atom node for bool, found {other:?}"),
2273            }
2274        })
2275    }
2276}
2277
2278macro_rules! impl_dc_mixed_integer_signed {
2279    ($($t:ty),*) => {
2280        $(
2281            impl DcMixedEncode for $t {
2282                fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2283                    let val_i128 = i128::try_from(*self)
2284                        .map_err(|e| anyhow!("Failed to convert integer to i128: {e}"))?;
2285                    let chars = crate::dc_number::i128_to_dc_number_chars(val_i128)?;
2286                    for ch in chars {
2287                        mst.push_char(ch)?;
2288                    }
2289                    Ok(())
2290                }
2291            }
2292
2293            impl DcMixedDecode for $t {
2294                fn decode_dc_node(
2295                    ctx: &mut DcProjectionContext<'_, '_>,
2296                    node_id: NodeId,
2297                ) -> Result<Self> {
2298                    ctx.decode_transparent(node_id, |ctx, node_id| {
2299                        let val = decode_integer_node(ctx, node_id)?;
2300                        <$t>::try_from(&val).map_err(|e| anyhow!("Value out of range for {}: {e:?}", stringify!($t)))
2301                    })
2302                }
2303            }
2304        )*
2305    };
2306}
2307
2308macro_rules! impl_dc_mixed_integer_unsigned {
2309    ($($t:ty),*) => {
2310        $(
2311            impl DcMixedEncode for $t {
2312                fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2313                    let val_u128 = u128::try_from(*self)
2314                        .map_err(|e| anyhow!("Failed to convert integer to u128: {e}"))?;
2315                    let chars = crate::dc_number::u128_to_dc_number_chars(val_u128)?;
2316                    for ch in chars {
2317                        mst.push_char(ch)?;
2318                    }
2319                    Ok(())
2320                }
2321            }
2322
2323            impl DcMixedDecode for $t {
2324                fn decode_dc_node(
2325                    ctx: &mut DcProjectionContext<'_, '_>,
2326                    node_id: NodeId,
2327                ) -> Result<Self> {
2328                    ctx.decode_transparent(node_id, |ctx, node_id| {
2329                        let val = decode_natural_node(ctx, node_id)?;
2330                        <$t>::try_from(&val).map_err(|e| anyhow!("Value out of range for {}: {e:?}", stringify!($t)))
2331                    })
2332                }
2333            }
2334        )*
2335    };
2336}
2337
2338impl_dc_mixed_integer_unsigned!(u8, u16, u32, u64, u128, usize);
2339impl_dc_mixed_integer_signed!(i8, i16, i32, i64, i128, isize);
2340
2341impl DcMixedEncode for malachite::Natural {
2342    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2343        let chars = crate::dc_number::natural_to_dc_number_chars(self, false)?;
2344        for ch in chars {
2345            mst.push_char(ch)?;
2346        }
2347        Ok(())
2348    }
2349}
2350
2351impl DcMixedDecode for malachite::Natural {
2352    fn decode_dc_node(
2353        ctx: &mut DcProjectionContext<'_, '_>,
2354        node_id: NodeId,
2355    ) -> Result<Self> {
2356        decode_natural_node(ctx, node_id)
2357    }
2358}
2359
2360impl DcMixedEncode for malachite::Integer {
2361    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2362        let chars = crate::dc_number::integer_to_dc_number_chars(self)?;
2363        for ch in chars {
2364            mst.push_char(ch)?;
2365        }
2366        Ok(())
2367    }
2368}
2369
2370impl DcMixedDecode for malachite::Integer {
2371    fn decode_dc_node(
2372        ctx: &mut DcProjectionContext<'_, '_>,
2373        node_id: NodeId,
2374    ) -> Result<Self> {
2375        decode_integer_node(ctx, node_id)
2376    }
2377}
2378
2379fn extract_tuple_element_nodes(
2380    ctx: &mut DcProjectionContext<'_, '_>,
2381    children: &[NodeId],
2382    expected_len: usize,
2383) -> Result<Vec<NodeId>> {
2384    let len_id = children
2385        .first()
2386        .copied()
2387        .context("Tuple container (Dc 2215) missing length number")?;
2388    let declared_len = usize::decode_dc_node(ctx, len_id)?;
2389    ensure!(
2390        declared_len == expected_len,
2391        "Tuple container (Dc 2215) length mismatch: expected {expected_len}, found {declared_len}"
2392    );
2393    let rest = children
2394        .get(1..)
2395        .context("Tuple container (Dc 2215) missing children slice")?;
2396    if expected_len == 0 {
2397        ctx.handle_remaining_nodes(rest)?;
2398        return Ok(Vec::new());
2399    }
2400    let mut groups: Vec<Vec<NodeId>> = vec![Vec::new()];
2401    for &child_id in rest {
2402        let child_node = ctx.node(child_id)?;
2403        if !child_node.is_escaped_atom()
2404            && let DcSyntaxKind::Atom(ch) = child_node.kind
2405            && ctx.token_fills_role(ch, DcRole::ListElementSeparator)
2406        {
2407            groups.push(Vec::new());
2408            continue;
2409        }
2410        if let Some(last_group) = groups.last_mut() {
2411            last_group.push(child_id);
2412        }
2413    }
2414    ensure!(
2415        groups.len() == expected_len,
2416        "Tuple container (Dc 2215) declared length {declared_len} but has {} element group(s)",
2417        groups.len()
2418    );
2419    let mut elem_ids = Vec::with_capacity(expected_len);
2420    for (group_idx, group) in groups.iter().enumerate() {
2421        if group_idx == 0 {
2422            let header_count = group.len().checked_sub(1).context(
2423                "Tuple container (Dc 2215) missing first element value",
2424            )?;
2425            ensure!(
2426                header_count == 0 || header_count == expected_len,
2427                "Tuple container (Dc 2215) expected 0 or {expected_len} slot type headers before element 0, found {header_count}"
2428            );
2429            let &first_elem =
2430                group.last().context("Missing first tuple element")?;
2431            elem_ids.push(first_elem);
2432        } else {
2433            let &[elem_id] = group.as_slice() else {
2434                bail!(
2435                    "Tuple container (Dc 2215) element {group_idx} expected 1 value node, found {}",
2436                    group.len()
2437                );
2438            };
2439            elem_ids.push(elem_id);
2440        }
2441    }
2442    Ok(elem_ids)
2443}
2444
2445impl DcMixedEncode for () {
2446    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2447        self.encode_dc_mixed_to_with_context(
2448            mst,
2449            &crate::SharedValueContext::default(),
2450        )
2451    }
2452
2453    fn encode_dc_mixed_to_with_context(
2454        &self,
2455        mst: &mut crate::DcWriter<'_>,
2456        context: &crate::SharedValueContext,
2457    ) -> Result<()> {
2458        mst.push_char(DC_BEGIN_TUPLE)?;
2459        0_u64.encode_dc_mixed_to_with_context(mst, context)?;
2460        mst.push_char(DC_END_TUPLE)?;
2461        Ok(())
2462    }
2463}
2464
2465impl DcMixedDecode for () {
2466    fn decode_dc_node(
2467        ctx: &mut DcProjectionContext<'_, '_>,
2468        node_id: NodeId,
2469    ) -> Result<Self> {
2470        ctx.decode_transparent(node_id, |ctx, mut node_id| {
2471            if let Ok(Some((_fmt, payload_id))) =
2472                ctx.unwrap_format_representation(node_id)
2473            {
2474                let candidate = ctx.unwrap_transparent(payload_id)?;
2475                let cand_node = ctx.node(candidate)?;
2476                if cand_node.is_structural_container_with(ctx.resolver()) {
2477                    node_id = candidate;
2478                }
2479            }
2480            let node = ctx.node(node_id)?;
2481            if let DcSyntaxKind::Container {
2482                opener, children, ..
2483            } = &node.kind
2484                && ctx.token_fills_role(*opener, DcRole::BeginTuple)
2485            {
2486                let children = children.clone();
2487                let _ = extract_tuple_element_nodes(ctx, &children, 0)?;
2488                return Ok(());
2489            }
2490            bail!(
2491                "Expected empty Tuple container (Dc 2215) for (), found {:?}",
2492                node.kind
2493            )
2494        })
2495    }
2496}
2497
2498impl<A: DcMixedEncode, B: DcMixedEncode> DcMixedEncode for (A, B) {
2499    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2500        self.encode_dc_mixed_to_with_context(
2501            mst,
2502            &crate::SharedValueContext::default(),
2503        )
2504    }
2505    fn encode_dc_mixed_to_with_context(
2506        &self,
2507        mst: &mut crate::DcWriter<'_>,
2508        context: &crate::SharedValueContext,
2509    ) -> Result<()> {
2510        mst.push_char(DC_BEGIN_KV_PAIR)?;
2511        self.0.encode_dc_mixed_to_with_context(mst, context)?;
2512        mst.push_char(DC_LIST_ELEMENT_SEPARATOR)?;
2513        self.1.encode_dc_mixed_to_with_context(mst, context)?;
2514        mst.push_char(DC_END_KV_PAIR)?;
2515        Ok(())
2516    }
2517    fn encode_format_elements_to_with_context(
2518        &self,
2519        format: DcChar,
2520        mst: &mut crate::DcWriter<'_>,
2521        context: &crate::SharedValueContext,
2522    ) -> Result<()> {
2523        let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
2524        let canon = resolver.canonical_token(format.to_u128());
2525        let is_seq_len_2 = FormatId::from_dc_id(canon)
2526            .and_then(|fid| resolver.format_rule_payload_arity(fid))
2527            == Some(2);
2528        if is_seq_len_2 {
2529            self.0.encode_dc_mixed_to_with_context(mst, context)?;
2530            self.1.encode_dc_mixed_to_with_context(mst, context)?;
2531            Ok(())
2532        } else {
2533            self.encode_dc_mixed_to_with_context(mst, context)
2534        }
2535    }
2536}
2537
2538impl<A: DcMixedDecode, B: DcMixedDecode> DcMixedDecode for (A, B) {
2539    fn decode_dc_document(
2540        ctx: &mut DcProjectionContext<'_, '_>,
2541        roots: &[NodeId],
2542    ) -> Result<(Self, usize)> {
2543        let root = roots
2544            .first()
2545            .copied()
2546            .context("Empty document cannot be decoded into pair")?;
2547        if let [first, second, ..] = roots {
2548            if let Ok(pair) = Self::decode_dc_node(ctx, *first) {
2549                return Ok((pair, 1));
2550            }
2551            let pair = (
2552                A::decode_dc_node(ctx, *first)?,
2553                B::decode_dc_node(ctx, *second)?,
2554            );
2555            return Ok((pair, 2));
2556        }
2557        Ok((Self::decode_dc_node(ctx, root)?, 1))
2558    }
2559
2560    fn decode_dc_node(
2561        ctx: &mut DcProjectionContext<'_, '_>,
2562        node_id: NodeId,
2563    ) -> Result<Self> {
2564        ctx.decode_transparent(node_id, |ctx, mut node_id| {
2565            if let Ok(Some((_fmt, payload_id))) = ctx.unwrap_format_representation(node_id) {
2566                let candidate = ctx.unwrap_transparent(payload_id)?;
2567                let cand_node = ctx.node(candidate)?;
2568                if cand_node.is_structural_container_with(ctx.resolver())
2569                    || matches!(cand_node.kind, DcSyntaxKind::Tagged { .. })
2570                {
2571                    node_id = candidate;
2572                }
2573            }
2574            let node = ctx.node(node_id)?;
2575            match &node.kind {
2576                DcSyntaxKind::Container { opener, children, .. }
2577                    if ctx.token_fills_role(*opener, DcRole::BeginTuple) =>
2578                {
2579                    let children = children.clone();
2580                    let elem_ids = extract_tuple_element_nodes(ctx, &children, 2)?;
2581                    let &[first, second] = elem_ids.as_slice() else {
2582                        bail!("Internal error: 2-tuple length mismatch");
2583                    };
2584                    let a = A::decode_dc_node(ctx, first)?;
2585                    let b = B::decode_dc_node(ctx, second)?;
2586                    return Ok((a, b));
2587                }
2588                DcSyntaxKind::Container { opener, children, .. }
2589                    if !node.is_leaf_value_container_with(ctx.resolver()) =>
2590                {
2591                    let child_slice = if ctx.token_fills_role(*opener, DcRole::BeginFormatRepresentation) && children.len() >= 3 {
2592                        children.get(1..).context("Format representation container missing payload children")?
2593                    } else {
2594                        children.as_slice()
2595                    };
2596                    let is_list = ctx.token_fills_role(*opener, DcRole::BeginList);
2597                    let filtered: Vec<NodeId> = child_slice
2598                        .iter()
2599                        .copied()
2600                        .filter(|&id| {
2601                            if let Ok(n) = ctx.node(id) {
2602                                !matches!(
2603                                    n.kind,
2604                                    DcSyntaxKind::Atom(ch)
2605                                        if ctx.token_fills_role(ch, DcRole::ListElementSeparator)
2606                                            || (is_list && ctx.token_fills_role(ch, DcRole::TypeToken))
2607                                )
2608                            } else {
2609                                true
2610                            }
2611                        })
2612                        .collect();
2613                    if let [single] = filtered.as_slice() {
2614                        return Self::decode_dc_node(ctx, *single);
2615                    }
2616                    if let (Some(&first), Some(&second)) = (filtered.first(), filtered.get(1)) {
2617                        let a = A::decode_dc_node(ctx, first)?;
2618                        let b = B::decode_dc_node(ctx, second)?;
2619                        ctx.handle_remaining_nodes(filtered.get(2..).context("Missing pair children")?)?;
2620                        return Ok((a, b));
2621                    }
2622                }
2623                DcSyntaxKind::Tagged { args, .. } => {
2624                    if let (Some(&first), Some(&second)) = (args.first(), args.get(1)) {
2625                        let a = A::decode_dc_node(ctx, first)?;
2626                        let b = B::decode_dc_node(ctx, second)?;
2627                        ctx.handle_remaining_nodes(args.get(2..).context("Missing pair arguments")?)?;
2628                        return Ok((a, b));
2629                    }
2630                }
2631                _ => {}
2632            }
2633            bail!("Expected Container or Tagged node with 2 elements for pair (A, B), found {:?}", node.kind)
2634        })
2635    }
2636}
2637
2638macro_rules! impl_dc_mixed_n_ary_tuple {
2639    ($len:literal : $( $idx:tt => $ty:ident ),+ $(,)?) => {
2640        impl<$( $ty: DcMixedEncode ),+> DcMixedEncode for ( $( $ty, )+ ) {
2641            fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2642                self.encode_dc_mixed_to_with_context(
2643                    mst,
2644                    &crate::SharedValueContext::default(),
2645                )
2646            }
2647
2648            fn encode_dc_mixed_to_with_context(
2649                &self,
2650                mst: &mut crate::DcWriter<'_>,
2651                context: &crate::SharedValueContext,
2652            ) -> Result<()> {
2653                mst.push_char(DC_BEGIN_TUPLE)?;
2654                let len_u64: u64 = $len;
2655                len_u64.encode_dc_mixed_to_with_context(mst, context)?;
2656                $(
2657                    let _ = stringify!($ty);
2658                    mst.push_char(DC_BEGIN_TYPE_DEF)?;
2659                    mst.push_char(DC_TYPE_ANY)?;
2660                    mst.push_char(DC_END_TYPE_DEF)?;
2661                )+
2662                let mut first = true;
2663                $(
2664                    if !first {
2665                        mst.push_char(DC_LIST_ELEMENT_SEPARATOR)?;
2666                    }
2667                    first = false;
2668                    self.$idx.encode_dc_mixed_to_with_context(mst, context)?;
2669                )+
2670                let _ = first;
2671                mst.push_char(DC_END_TUPLE)?;
2672                Ok(())
2673            }
2674
2675            fn encode_format_elements_to_with_context(
2676                &self,
2677                format: DcChar,
2678                mst: &mut crate::DcWriter<'_>,
2679                context: &crate::SharedValueContext,
2680            ) -> Result<()> {
2681                let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
2682                let canon = resolver.canonical_token(format.to_u128());
2683                let is_matching_arity = FormatId::from_dc_id(canon)
2684                    .and_then(|fid| resolver.format_rule_payload_arity(fid))
2685                    == Some($len);
2686                if is_matching_arity {
2687                    $(
2688                        self.$idx.encode_dc_mixed_to_with_context(mst, context)?;
2689                    )+
2690                    Ok(())
2691                } else {
2692                    self.encode_dc_mixed_to_with_context(mst, context)
2693                }
2694            }
2695        }
2696
2697        impl<$( $ty: DcMixedDecode ),+> DcMixedDecode for ( $( $ty, )+ ) {
2698            fn decode_dc_node(
2699                ctx: &mut DcProjectionContext<'_, '_>,
2700                node_id: NodeId,
2701            ) -> Result<Self> {
2702                ctx.with_projection_depth(node_id, |ctx| {
2703                    ctx.decode_transparent(node_id, |ctx, mut node_id| {
2704                        if let Ok(Some((_fmt, payload_id))) =
2705                            ctx.unwrap_format_representation(node_id)
2706                        {
2707                            let candidate = ctx.unwrap_transparent(payload_id)?;
2708                            let cand_node = ctx.node(candidate)?;
2709                            if cand_node.is_structural_container_with(ctx.resolver()) {
2710                                node_id = candidate;
2711                            }
2712                        }
2713                        let node = ctx.node(node_id)?;
2714                        if let DcSyntaxKind::Container {
2715                            opener, children, ..
2716                        } = &node.kind
2717                            && ctx.token_fills_role(*opener, DcRole::BeginTuple)
2718                        {
2719                            let children = children.clone();
2720                            let elem_ids = extract_tuple_element_nodes(ctx, &children, $len)?;
2721                            let mut iter = elem_ids.into_iter();
2722                            return Ok((
2723                                $(
2724                                    <$ty>::decode_dc_node(
2725                                        ctx,
2726                                        iter.next().context("Missing tuple element node")?,
2727                                    )?,
2728                                )+
2729                            ));
2730                        }
2731                        bail!(
2732                            "Expected Tuple container (Dc 2215) of length {} for tuple, found {:?}",
2733                            $len,
2734                            node.kind
2735                        )
2736                    })
2737                })
2738            }
2739        }
2740    };
2741}
2742
2743impl_dc_mixed_n_ary_tuple!(1 : 0 => T0);
2744impl_dc_mixed_n_ary_tuple!(3 : 0 => T0, 1 => T1, 2 => T2);
2745impl_dc_mixed_n_ary_tuple!(4 : 0 => T0, 1 => T1, 2 => T2, 3 => T3);
2746impl_dc_mixed_n_ary_tuple!(5 : 0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4);
2747impl_dc_mixed_n_ary_tuple!(6 : 0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5);
2748impl_dc_mixed_n_ary_tuple!(7 : 0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6);
2749impl_dc_mixed_n_ary_tuple!(8 : 0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7);
2750impl_dc_mixed_n_ary_tuple!(9 : 0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7, 8 => T8);
2751impl_dc_mixed_n_ary_tuple!(10 : 0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7, 8 => T8, 9 => T9);
2752impl_dc_mixed_n_ary_tuple!(11 : 0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7, 8 => T8, 9 => T9, 10 => T10);
2753impl_dc_mixed_n_ary_tuple!(12 : 0 => T0, 1 => T1, 2 => T2, 3 => T3, 4 => T4, 5 => T5, 6 => T6, 7 => T7, 8 => T8, 9 => T9, 10 => T10, 11 => T11);
2754
2755impl<T: DcMixedEncode> DcMixedEncode for Option<T> {
2756    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2757        self.encode_dc_mixed_to_with_context(
2758            mst,
2759            &crate::SharedValueContext::default(),
2760        )
2761    }
2762    fn encode_dc_mixed_to_with_context(
2763        &self,
2764        mst: &mut crate::DcWriter<'_>,
2765        context: &crate::SharedValueContext,
2766    ) -> Result<()> {
2767        if let Some(val) = self {
2768            mst.push_char(DC_OPTIONAL_PRESENT)?;
2769            val.encode_dc_mixed_to_with_context(mst, context)
2770        } else {
2771            mst.push_char(DC_OPTIONAL_ABSENT)?;
2772            Ok(())
2773        }
2774    }
2775}
2776
2777impl<T: DcMixedDecode> DcMixedDecode for Option<T> {
2778    fn decode_dc_node(
2779        ctx: &mut DcProjectionContext<'_, '_>,
2780        node_id: NodeId,
2781    ) -> Result<Self> {
2782        ctx.with_projection_depth(node_id, |ctx| {
2783            ctx.decode_equivalent(node_id, |ctx, cand_id| {
2784                let node_id = ctx.unwrap_equivalent_or_self(cand_id)?;
2785                let node = ctx.node(node_id)?;
2786                if let Some((head, children)) = node.head_and_children()
2787                    && ctx.token_fills_role(head, DcRole::OptionalPresent)
2788                {
2789                    let inner = children
2790                        .first()
2791                        .copied()
2792                        .context("Missing value in Dc 315 construct")?;
2793                    return T::decode_dc_node(ctx, inner).map(Some);
2794                }
2795                match &node.kind {
2796                    DcSyntaxKind::Atom(ch)
2797                        if ctx
2798                            .token_fills_role(*ch, DcRole::OptionalAbsent) =>
2799                    {
2800                        Ok(None)
2801                    }
2802                    _ => bail!(
2803                        "Expected Option marker (Dc 315 or 316), found {:?}",
2804                        node.kind
2805                    ),
2806                }
2807            })
2808        })
2809    }
2810}
2811
2812impl<T: DcMixedEncode> DcMixedEncode for Vec<T> {
2813    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2814        self.encode_dc_mixed_to_with_context(
2815            mst,
2816            &crate::SharedValueContext::default(),
2817        )
2818    }
2819    fn encode_dc_mixed_to_with_context(
2820        &self,
2821        mst: &mut crate::DcWriter<'_>,
2822        context: &crate::SharedValueContext,
2823    ) -> Result<()> {
2824        mst.push_char(DC_BEGIN_LIST)?;
2825        mst.push_char(DC_TYPE_ANY)?;
2826        for (idx, item) in self.iter().enumerate() {
2827            if idx > 0 {
2828                mst.push_char(DC_LIST_ELEMENT_SEPARATOR)?;
2829            }
2830            item.encode_dc_mixed_to_with_context(mst, context)?;
2831        }
2832        mst.push_char(DC_END_LIST)?;
2833        Ok(())
2834    }
2835}
2836
2837impl<T: DcMixedDecode> DcMixedDecode for Vec<T> {
2838    fn decode_dc_node(
2839        ctx: &mut DcProjectionContext<'_, '_>,
2840        node_id: NodeId,
2841    ) -> Result<Self> {
2842        ctx.with_projection_depth(node_id, |ctx| {
2843            ctx.decode_transparent(node_id, |ctx, mut node_id| {
2844                if let Ok(Some((_fmt, payload_id))) = ctx.unwrap_format_representation(node_id) {
2845                    node_id = ctx.unwrap_transparent(payload_id)?;
2846                }
2847                let node = ctx.node(node_id)?;
2848                let children = match &node.kind {
2849                    DcSyntaxKind::Container { opener, children, .. } if ctx.token_fills_role(*opener, DcRole::BeginList) => children,
2850                    other => bail!("Expected List container (Dc 310) for Vec, found {other:?}"),
2851                };
2852
2853                let mut iter = children.iter().copied().peekable();
2854
2855                if let Some(&first_id) = iter.peek() {
2856                    if ctx.arena.is_number_with_resolver(first_id, ctx.resolver()) {
2857                        let second_id = children.get(1).copied();
2858                        let is_followed_by_type = if let Some(sec_id) = second_id {
2859                            let sec_node = ctx.node(sec_id)?;
2860                            matches!(sec_node.kind, DcSyntaxKind::Atom(ch) if ctx.token_fills_role(ch, DcRole::TypeToken))
2861                        } else {
2862                            false
2863                        };
2864                        if is_followed_by_type {
2865                            let _ = iter.next();
2866                        }
2867                    }
2868                }
2869
2870                if let Some(&id) = iter.peek() {
2871                    let n = ctx.node(id)?;
2872                    if let DcSyntaxKind::Atom(ch) = &n.kind {
2873                        if ctx.token_fills_role(*ch, DcRole::TypeToken) {
2874                            let _ = iter.next();
2875                        }
2876                    }
2877                }
2878
2879                let mut list = Vec::new();
2880                for child_id in iter {
2881                    let child_node = ctx.node(child_id)?;
2882                    if let DcSyntaxKind::Atom(ch) = &child_node.kind {
2883                        if ctx.token_fills_role(*ch, DcRole::ListElementSeparator) {
2884                            continue;
2885                        }
2886                    }
2887                    list.push(T::decode_dc_node(ctx, child_id)?);
2888                }
2889
2890                Ok(list)
2891            })
2892        })
2893    }
2894}
2895
2896fn format_dc_char(fid: FormatId) -> Result<DcChar> {
2897    let dc_id = fid.dc_id().context("FormatId missing dc_id")?;
2898    Ok(DcChar::from_u128(dc_id))
2899}
2900
2901impl DcMixedEncode for Ipv4Addr {
2902    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2903        mst.push_char(DC_BEGIN_FORMAT_REPRESENTATION)?;
2904        mst.push_char(format_dc_char(FormatId::IpV4)?)?;
2905        let octets = u32::from_be_bytes(self.octets());
2906        octets.encode_dc_mixed_to(mst)?;
2907        mst.push_char(DC_END_FORMAT_REPRESENTATION)?;
2908        Ok(())
2909    }
2910}
2911
2912impl DcMixedDecode for Ipv4Addr {
2913    fn decode_dc_node(
2914        ctx: &mut DcProjectionContext<'_, '_>,
2915        node_id: NodeId,
2916    ) -> Result<Self> {
2917        let ipv4_fmt = format_dc_char(FormatId::IpV4)?;
2918        ctx.decode_transparent(node_id, |ctx, node_id| {
2919            if let Some((fmt, payload_id)) = ctx.unwrap_format_representation(node_id)? {
2920                if ctx.tokens_equivalent(fmt, ipv4_fmt) {
2921                    let val = u32::decode_dc_node(ctx, payload_id)?;
2922                    return Ok(Ipv4Addr::from(val));
2923                }
2924            }
2925            let node = ctx.node(node_id)?;
2926            bail!("Expected format representation (Dc 511 + f490) for IPv4 address, found {:?}", node.kind)
2927        })
2928    }
2929}
2930
2931impl DcMixedEncode for Ipv6Addr {
2932    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2933        mst.push_char(DC_BEGIN_FORMAT_REPRESENTATION)?;
2934        mst.push_char(format_dc_char(FormatId::IpV6)?)?;
2935        let octets = u128::from_be_bytes(self.octets());
2936        octets.encode_dc_mixed_to(mst)?;
2937        mst.push_char(DC_END_FORMAT_REPRESENTATION)?;
2938        Ok(())
2939    }
2940}
2941
2942impl DcMixedDecode for Ipv6Addr {
2943    fn decode_dc_node(
2944        ctx: &mut DcProjectionContext<'_, '_>,
2945        node_id: NodeId,
2946    ) -> Result<Self> {
2947        let ipv6_fmt = format_dc_char(FormatId::IpV6)?;
2948        ctx.decode_transparent(node_id, |ctx, node_id| {
2949            if let Some((fmt, payload_id)) = ctx.unwrap_format_representation(node_id)? {
2950                if ctx.tokens_equivalent(fmt, ipv6_fmt) {
2951                    let val = u128::decode_dc_node(ctx, payload_id)?;
2952                    return Ok(Ipv6Addr::from(val));
2953                }
2954            }
2955            let node = ctx.node(node_id)?;
2956            bail!("Expected format representation (Dc 511 + f491) for IPv6 address, found {:?}", node.kind)
2957        })
2958    }
2959}
2960
2961impl DcMixedEncode for std::net::IpAddr {
2962    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2963        match self {
2964            Self::V4(v4) => v4.encode_dc_mixed_to(mst),
2965            Self::V6(v6) => v6.encode_dc_mixed_to(mst),
2966        }
2967    }
2968}
2969
2970impl DcMixedDecode for std::net::IpAddr {
2971    fn decode_dc_node(
2972        ctx: &mut DcProjectionContext<'_, '_>,
2973        node_id: NodeId,
2974    ) -> Result<Self> {
2975        let ipv4_fmt = format_dc_char(FormatId::IpV4)?;
2976        let ipv6_fmt = format_dc_char(FormatId::IpV6)?;
2977        ctx.decode_transparent(node_id, |ctx, node_id| {
2978            if let Some((fmt, payload_id)) = ctx.unwrap_format_representation(node_id)? {
2979                if ctx.tokens_equivalent(fmt, ipv4_fmt) {
2980                    let val = u32::decode_dc_node(ctx, payload_id)?;
2981                    return Ok(Self::V4(Ipv4Addr::from(val)));
2982                } else if ctx.tokens_equivalent(fmt, ipv6_fmt) {
2983                    let val = u128::decode_dc_node(ctx, payload_id)?;
2984                    return Ok(Self::V6(Ipv6Addr::from(val)));
2985                }
2986            }
2987            let node = ctx.node(node_id)?;
2988            bail!("Expected format representation (Dc 511 + f490/f491) for IP address, found {:?}", node.kind)
2989        })
2990    }
2991}
2992
2993impl DcMixedEncode for ctb_formats_utilities::FormatId {
2994    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
2995        let dc_id = self.dc_id().context("FormatId missing dc_id")?;
2996        mst.push_char(DcChar::from_u128(dc_id))?;
2997        Ok(())
2998    }
2999}
3000
3001impl DcMixedDecode for ctb_formats_utilities::FormatId {
3002    fn decode_dc_node(
3003        ctx: &mut DcProjectionContext<'_, '_>,
3004        node_id: NodeId,
3005    ) -> Result<Self> {
3006        ctx.decode_transparent(node_id, |ctx, node_id| {
3007            let node = ctx.node(node_id)?;
3008            match &node.kind {
3009                DcSyntaxKind::Atom(ch) => {
3010                    let canon = ctx.canonical_token(*ch);
3011                    if let Some(fid) = Self::from_dc_id(canon.0) {
3012                        Ok(fid)
3013                    } else {
3014                        bail!("Unknown format DC character {ch:?}")
3015                    }
3016                }
3017                other => bail!("Expected Atom for FormatId, found {other:?}"),
3018            }
3019        })
3020    }
3021}
3022
3023impl<K, V> DcMixedEncode for BTreeMap<K, V>
3024where
3025    K: DcMixedEncode,
3026    V: DcMixedEncode,
3027{
3028    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3029        self.encode_dc_mixed_to_with_context(
3030            mst,
3031            &crate::SharedValueContext::default(),
3032        )
3033    }
3034    fn encode_dc_mixed_to_with_context(
3035        &self,
3036        mst: &mut crate::DcWriter<'_>,
3037        context: &crate::SharedValueContext,
3038    ) -> Result<()> {
3039        let encoding = crate::DcKvMapEncoding::Pairs;
3040        encoding.encode_header_to(mst)?;
3041        let mut first = true;
3042        for (k, v) in self {
3043            encoding.encode_entry_begin_to(mst, first)?;
3044            first = false;
3045            k.encode_dc_mixed_to_with_context(mst, context)?;
3046            mst.push_char(DC_LIST_ELEMENT_SEPARATOR)?;
3047            v.encode_dc_mixed_to_with_context(mst, context)?;
3048            encoding.encode_entry_end_to(mst)?;
3049        }
3050        encoding.encode_end_to(mst)?;
3051        Ok(())
3052    }
3053}
3054
3055impl<K, V> DcMixedDecode for BTreeMap<K, V>
3056where
3057    K: DcMixedDecode + Ord,
3058    V: DcMixedDecode,
3059{
3060    fn decode_dc_node(
3061        ctx: &mut DcProjectionContext<'_, '_>,
3062        node_id: NodeId,
3063    ) -> Result<Self> {
3064        ctx.with_projection_depth(node_id, |ctx| {
3065            ctx.decode_transparent(node_id, |ctx, node_id| {
3066                let (_opener, pairs) =
3067                    ctx.arena.extract_kv_map_node_pairs_with_resolver(
3068                        node_id,
3069                        ctx.resolver(),
3070                    )?;
3071
3072                let mut map = BTreeMap::new();
3073                for (k_node_id, v_node_id) in pairs {
3074                    let key = K::decode_dc_node(ctx, k_node_id)?;
3075                    let value = V::decode_dc_node(ctx, v_node_id)?;
3076                    ensure!(
3077                        map.insert(key, value).is_none(),
3078                        "Duplicate Dc map key"
3079                    );
3080                }
3081                Ok(map)
3082            })
3083        })
3084    }
3085}
3086
3087impl<T: DcMixedEncode + ?Sized> DcMixedEncode for Box<T> {
3088    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3089        (**self).encode_dc_mixed_to(mst)
3090    }
3091    fn encode_dc_mixed_to_with_context(
3092        &self,
3093        mst: &mut crate::DcWriter<'_>,
3094        context: &crate::SharedValueContext,
3095    ) -> Result<()> {
3096        (**self).encode_dc_mixed_to_with_context(mst, context)
3097    }
3098}
3099
3100impl<T: DcMixedDecode> DcMixedDecode for Box<T> {
3101    fn decode_dc_node(
3102        ctx: &mut DcProjectionContext<'_, '_>,
3103        node_id: NodeId,
3104    ) -> Result<Self> {
3105        let val = T::decode_dc_node(ctx, node_id)?;
3106        Ok(Box::new(val))
3107    }
3108}
3109
3110impl<T: DcMixedEncode + ?Sized> DcMixedEncode for Arc<T> {
3111    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3112        (**self).encode_dc_mixed_to(mst)
3113    }
3114    fn encode_dc_mixed_to_with_context(
3115        &self,
3116        mst: &mut crate::DcWriter<'_>,
3117        context: &crate::SharedValueContext,
3118    ) -> Result<()> {
3119        (**self).encode_dc_mixed_to_with_context(mst, context)
3120    }
3121}
3122
3123impl<T: DcMixedDecode> DcMixedDecode for Arc<T> {
3124    fn decode_dc_node(
3125        ctx: &mut DcProjectionContext<'_, '_>,
3126        node_id: NodeId,
3127    ) -> Result<Self> {
3128        let val = T::decode_dc_node(ctx, node_id)?;
3129        Ok(Arc::new(val))
3130    }
3131}
3132
3133impl DcMixedEncode for PathBuf {
3134    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3135        let segments: Vec<Vec<u8>> = self
3136            .as_os_str()
3137            .as_encoded_bytes()
3138            .split(|byte| *byte == b'/' || (cfg!(windows) && *byte == b'\\'))
3139            .map(<[u8]>::to_vec)
3140            .collect();
3141        encode_filepath_segments_to(&segments, mst)
3142    }
3143}
3144
3145/// Encodes raw filename segments as a typed filepath, retaining empty segments
3146/// for leading, repeated, and trailing delimiters.
3147///
3148/// # Errors
3149/// Returns an error if the segment list is empty, a segment contains `/`, or
3150/// serialization fails. An empty path is represented by one empty segment.
3151pub fn encode_filepath_segments(
3152    segments: &[Vec<u8>],
3153    mst: &mut DcMstring,
3154) -> Result<()> {
3155    encode_filepath_segments_to(segments, &mut mst.writer())
3156}
3157
3158pub fn encode_filepath_segments_to(
3159    segments: &[Vec<u8>],
3160    mst: &mut crate::DcWriter<'_>,
3161) -> Result<()> {
3162    ensure!(
3163        !segments.is_empty(),
3164        "Filepath requires at least one segment"
3165    );
3166    ensure!(
3167        segments.iter().all(|segment| !segment.contains(&b'/')),
3168        "Filename segment contains a path delimiter"
3169    );
3170    let path_format = DcChar::from_u128(
3171        FormatId::FilePath
3172            .dc_id()
3173            .context("Missing FilePath format identifier")?,
3174    );
3175    let filename_format = DcChar::from_u128(
3176        FormatId::FileName
3177            .dc_id()
3178            .context("Missing FileName format identifier")?,
3179    );
3180    mst.push_char(DC_BEGIN_FORMAT_REPRESENTATION)?;
3181    mst.push_char(path_format)?;
3182    mst.push_char(DC_BEGIN_LIST)?;
3183    mst.push_char(DC_TYPE_INTERSECTION)?;
3184    mst.push_char(filename_format)?;
3185    mst.push_char(DC_FILE_PATH_DELIMITER)?;
3186    let mut segments = segments.iter().peekable();
3187    while let Some(segment) = segments.next() {
3188        if !segment.is_empty() {
3189            mst.push_char(DC_BEGIN_FORMAT_REPRESENTATION)?;
3190            mst.push_char(filename_format)?;
3191            if let Ok(text) = std::str::from_utf8(segment) {
3192                mst.push_char(DC_EQUIVALENT_REPRESENTATIONS)?;
3193                mst.push_char(DC_BEGIN_LIST)?;
3194                mst.push_char(DC_TYPE_ANY)?;
3195                text.encode_dc_mixed_to(mst)?;
3196                mst.push_char(DC_LIST_ELEMENT_SEPARATOR)?;
3197                mst.push_binary_with_sha256(segment)?;
3198                mst.push_char(DC_END_LIST)?;
3199            } else {
3200                mst.push_binary_with_sha256(segment)?;
3201            }
3202            mst.push_char(DC_END_FORMAT_REPRESENTATION)?;
3203        }
3204        if segments.peek().is_some() {
3205            mst.push_char(DC_FILE_PATH_DELIMITER)?;
3206        }
3207    }
3208    mst.push_char(DC_END_LIST)?;
3209    mst.push_char(DC_END_FORMAT_REPRESENTATION)?;
3210    Ok(())
3211}
3212
3213impl DcMixedEncode for std::path::Path {
3214    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3215        self.to_path_buf().encode_dc_mixed_to(mst)
3216    }
3217}
3218
3219/// Encodes a value within the declared format representation boundaries.
3220pub fn encode_format_representation<T: DcMixedEncode + ?Sized>(
3221    value: &T,
3222    format: DcChar,
3223    mst: &mut DcMstring,
3224    context: &crate::SharedValueContext,
3225) -> Result<()> {
3226    encode_format_representation_to(value, format, &mut mst.writer(), context)
3227}
3228
3229pub fn encode_format_representation_to<T: DcMixedEncode + ?Sized>(
3230    value: &T,
3231    format: DcChar,
3232    mst: &mut crate::DcWriter<'_>,
3233    context: &crate::SharedValueContext,
3234) -> Result<()> {
3235    mst.push_char(DC_BEGIN_FORMAT_REPRESENTATION)?;
3236    mst.push_char(format)?;
3237    value.encode_format_elements_to_with_context(format, mst, context)?;
3238    mst.push_char(DC_END_FORMAT_REPRESENTATION)?;
3239    Ok(())
3240}
3241
3242/// Decodes a value within the declared format representation boundaries.
3243pub fn decode_format_representation<T: DcMixedDecode>(
3244    ctx: &mut DcProjectionContext<'_, '_>,
3245    node_id: NodeId,
3246    format: DcChar,
3247) -> Result<T> {
3248    ctx.decode_transparent(node_id, |ctx, node_id| {
3249        if let Some((fmt, payload_id)) = ctx.unwrap_format_representation(node_id)? {
3250            if ctx.tokens_equivalent(fmt, format) {
3251                return T::decode_dc_node(ctx, payload_id);
3252            }
3253            bail!("Format representation mismatch: expected {format:?}, found {fmt:?}");
3254        }
3255        let node = ctx.node(node_id)?;
3256        if let DcSyntaxKind::Container { opener, closer: _, header: _, children, trailing: _, unclosed: _ } = &node.kind {
3257            if ctx.token_fills_role(*opener, DcRole::BeginFormatRepresentation)
3258                && let Some(&first_child) = children.first()
3259            {
3260                let fmt_node = ctx.node(first_child)?;
3261                let fmt_matches = match &fmt_node.kind {
3262                    DcSyntaxKind::Atom(ch) => ctx.tokens_equivalent(*ch, format),
3263                    _ => false,
3264                };
3265                if fmt_matches {
3266                    return T::decode_dc_node(ctx, node_id);
3267                }
3268            }
3269        }
3270        // Direct or inline representation when not wrapped in a Dc 511 container:
3271        if let Ok(val) = T::decode_dc_node(ctx, node_id) {
3272            return Ok(val);
3273        }
3274        bail!("Expected format representation container (Dc 511 + {format:?}) or valid inline representation, found {:?}", node.kind)
3275    })
3276}
3277
3278/// Extracts flag items `(tag, item_id)` from a flags container node.
3279/// Handles:
3280/// - Empty container: returns `Ok(vec![])`
3281/// - List container (`310 275 ... 311`): extracts elements, ignoring separator tokens
3282/// - Bare atoms / tagged items in container
3283pub fn extract_flag_nodes(
3284    ctx: &DcProjectionContext<'_, '_>,
3285    node_id: NodeId,
3286) -> Result<Vec<(u128, NodeId)>> {
3287    let unwrap_id = ctx.unwrap_transparent(node_id)?;
3288    let unwrap_node = ctx.node(unwrap_id)?;
3289    let children = match &unwrap_node.kind {
3290        DcSyntaxKind::Container { children, .. } => children.as_slice(),
3291        _ => return Ok(vec![]),
3292    };
3293    if children.is_empty() {
3294        return Ok(vec![]);
3295    }
3296    // If the container has a single list container child (Dc 310)
3297    let candidate_children = if let [first_id] = children {
3298        let first_node = ctx.node(*first_id)?;
3299        if let DcSyntaxKind::Container {
3300            opener,
3301            children: lc,
3302            ..
3303        } = &first_node.kind
3304        {
3305            if ctx.token_fills_role(*opener, DcRole::BeginList) {
3306                lc.as_slice()
3307            } else {
3308                children
3309            }
3310        } else {
3311            children
3312        }
3313    } else {
3314        children
3315    };
3316
3317    let mut result = Vec::new();
3318    let mut iter = candidate_children.iter().copied().peekable();
3319    // If there is a leading Dc 275 (element separator / wildcard), consume it:
3320    if let Some(&first_id) = iter.peek() {
3321        let first_node = ctx.node(first_id)?;
3322        if let DcSyntaxKind::Atom(ch) = first_node.kind {
3323            if ctx.token_fills_role(ch, DcRole::TypeAny) {
3324                iter.next();
3325            }
3326        }
3327    }
3328
3329    for item_id in iter {
3330        let item_node = ctx.node(item_id)?;
3331        match &item_node.kind {
3332            DcSyntaxKind::Atom(ch) => {
3333                if ctx.token_fills_role(*ch, DcRole::ListElementSeparator)
3334                    || ctx.token_fills_role(*ch, DcRole::TypeAny)
3335                {
3336                    continue;
3337                }
3338                result.push((ctx.canonical_token(*ch).to_u128(), item_id));
3339            }
3340            DcSyntaxKind::Tagged { tag, .. } => {
3341                if ctx.token_fills_role(*tag, DcRole::ListElementSeparator)
3342                    || ctx.token_fills_role(*tag, DcRole::TypeAny)
3343                {
3344                    continue;
3345                }
3346                result.push((ctx.canonical_token(*tag).to_u128(), item_id));
3347            }
3348            DcSyntaxKind::Container { opener, .. } => {
3349                if ctx.token_fills_role(*opener, DcRole::BeginList) {
3350                    let inner = extract_flag_nodes(ctx, item_id)?;
3351                    result.extend(inner);
3352                } else {
3353                    result.push((
3354                        ctx.canonical_token(*opener).to_u128(),
3355                        item_id,
3356                    ));
3357                }
3358            }
3359            _ => {}
3360        }
3361    }
3362    Ok(result)
3363}
3364
3365/// Resolves native Unix bytes or canonical Windows WTF-8 without replacement.
3366///
3367/// # Errors
3368/// Returns an error if the bytes cannot be represented on the current OS.
3369pub fn path_from_native_bytes(bytes: &[u8]) -> Result<PathBuf> {
3370    #[cfg(unix)]
3371    {
3372        use std::os::unix::ffi::OsStrExt;
3373        Ok(PathBuf::from(std::ffi::OsStr::from_bytes(bytes)))
3374    }
3375    #[cfg(windows)]
3376    {
3377        use std::os::windows::ffi::OsStringExt;
3378        let wide = ctb_formats_wtf8::decode_wtf8_to_ucs2(bytes).context(
3379            "Path bytes cannot be represented losslessly on Windows",
3380        )?;
3381        let name = std::ffi::OsString::from_wide(&wide);
3382        ensure!(
3383            name.as_encoded_bytes() == bytes,
3384            "Path bytes are not canonical Windows WTF-8"
3385        );
3386        Ok(PathBuf::from(name))
3387    }
3388    #[cfg(not(any(unix, windows)))]
3389    {
3390        Ok(PathBuf::from(std::str::from_utf8(bytes).context(
3391            "Path bytes cannot be represented losslessly on this platform",
3392        )?))
3393    }
3394}
3395
3396fn decode_filename_bytes(
3397    ctx: &mut DcProjectionContext<'_, '_>,
3398    mut node_id: NodeId,
3399) -> Result<Vec<u8>> {
3400    while let Ok(node) = ctx.node(node_id) {
3401        match &node.kind {
3402            DcSyntaxKind::Container {
3403                opener, children, ..
3404            } if ctx.token_fills_role(*opener, DcRole::OptionalPresent) => {
3405                node_id = *children
3406                    .first()
3407                    .context("Empty optional container (Dc 315)")?;
3408            }
3409            DcSyntaxKind::Tagged { tag, args }
3410                if ctx.token_fills_role(*tag, DcRole::OptionalPresent) =>
3411            {
3412                node_id = *args
3413                    .first()
3414                    .context("Empty optional tagged construct (Dc 315)")?;
3415            }
3416            _ => break,
3417        }
3418    }
3419
3420    let node = ctx.node(node_id)?;
3421    match &node.kind {
3422        DcSyntaxKind::Container {
3423            opener, children, ..
3424        } if ctx
3425            .token_fills_role(*opener, DcRole::EquivalentRepresentations)
3426            || ctx.token_fills_role(
3427                *opener,
3428                DcRole::PartiallyEquivalentRepresentations,
3429            )
3430            || ctx.token_fills_role(*opener, DcRole::BeginList) =>
3431        {
3432            if let [single] = children.as_slice() {
3433                if let DcSyntaxKind::Container {
3434                    opener: inner_opener,
3435                    children: inner_children,
3436                    ..
3437                } = &ctx.node(*single)?.kind
3438                {
3439                    if ctx.token_fills_role(*inner_opener, DcRole::BeginList) {
3440                        return decode_equivalent_filename_candidates(
3441                            ctx,
3442                            inner_children,
3443                        );
3444                    }
3445                }
3446            }
3447            return decode_equivalent_filename_candidates(ctx, children);
3448        }
3449        DcSyntaxKind::Tagged { tag, args }
3450            if ctx
3451                .token_fills_role(*tag, DcRole::EquivalentRepresentations)
3452                || ctx.token_fills_role(
3453                    *tag,
3454                    DcRole::PartiallyEquivalentRepresentations,
3455                ) =>
3456        {
3457            let first = *args
3458                .first()
3459                .context("Empty equivalent representation tagged construct")?;
3460            let arg_node = ctx.node(first)?;
3461            if arg_node.is_structural_container_with(ctx.resolver())
3462                && let DcSyntaxKind::Container { children, .. } = &arg_node.kind
3463            {
3464                return decode_equivalent_filename_candidates(ctx, children);
3465            }
3466            return decode_equivalent_filename_candidates(ctx, args);
3467        }
3468        _ => {}
3469    }
3470
3471    let node_id = ctx.unwrap_transparent(node_id)?;
3472    let node = ctx.node(node_id)?;
3473    match &node.kind {
3474        DcSyntaxKind::Binary { payload, .. } => {
3475            let payload = payload.clone();
3476            Ok(ctx.materialize_binary(&payload)?.into_owned())
3477        }
3478        DcSyntaxKind::Container { .. }
3479            if ctx.arena.is_literal_with_resolver(node_id, ctx.resolver()) =>
3480        {
3481            Ok(String::decode_dc_node(ctx, node_id)?.into_bytes())
3482        }
3483        other => bail!(
3484            "Expected binary, string literal, or equivalent container for filename, found {other:?}"
3485        ),
3486    }
3487}
3488
3489fn decode_equivalent_filename_candidates(
3490    ctx: &mut DcProjectionContext<'_, '_>,
3491    candidates: &[NodeId],
3492) -> Result<Vec<u8>> {
3493    let mut text: Option<String> = None;
3494    let mut bytes: Option<Vec<u8>> = None;
3495    for &child_id in candidates {
3496        let child = ctx.node(child_id)?;
3497        if let DcSyntaxKind::Atom(ch) = child.kind {
3498            if ctx.token_fills_role(ch, DcRole::TypeAny)
3499                || ctx.token_fills_role(ch, DcRole::ListElementSeparator)
3500            {
3501                continue;
3502            }
3503        }
3504        if let DcSyntaxKind::Binary { payload, .. } = &child.kind {
3505            let payload = payload.clone();
3506            bytes = Some(ctx.materialize_binary(&payload)?.into_owned());
3507        } else if let Ok(s) = String::decode_dc_node(ctx, child_id) {
3508            text = Some(s);
3509        }
3510    }
3511    if let (Some(t), Some(b)) = (&text, &bytes) {
3512        ensure!(
3513            t.as_bytes() == b.as_slice(),
3514            "Conflicting filename representations"
3515        );
3516        let Some(b) = bytes else { unreachable!() };
3517        Ok(b)
3518    } else if let Some(b) = bytes {
3519        Ok(b)
3520    } else if let Some(t) = text {
3521        Ok(t.into_bytes())
3522    } else {
3523        bail!("Empty equivalent representation container for filename")
3524    }
3525}
3526
3527/// Decodes a typed filepath without interpreting its bytes on the host OS.
3528///
3529/// # Errors
3530/// Returns an error on malformed framing, conflicting filename representations,
3531/// or filenames containing `/`.
3532pub fn decode_filepath_segments(
3533    ctx: &mut DcProjectionContext<'_, '_>,
3534    node_id: NodeId,
3535) -> Result<Vec<Vec<u8>>> {
3536    let path_format = DcChar::from_u128(
3537        FormatId::FilePath
3538            .dc_id()
3539            .context("Missing FilePath format identifier")?,
3540    );
3541    let filename_format = DcChar::from_u128(
3542        FormatId::FileName
3543            .dc_id()
3544            .context("Missing FileName format identifier")?,
3545    );
3546    ctx.decode_transparent(node_id, |ctx, node_id| {
3547        let (fmt, inner_id) = ctx.unwrap_format_representation(node_id)?
3548            .context("Expected format representation container for FilePath")?;
3549        ensure!(ctx.tokens_equivalent(fmt, path_format), "Expected FilePath format identifier in Dc 511");
3550
3551        let inner_node = ctx.node(inner_id)?;
3552        let children = match &inner_node.kind {
3553            DcSyntaxKind::Container { opener, children, .. } if ctx.token_fills_role(*opener, DcRole::BeginList) => children,
3554            other => bail!("Expected List container inside FilePath format representation, found {other:?}"),
3555        };
3556
3557        let mut iter = children.iter().copied().peekable();
3558        if let Some(&first_id) = iter.peek() {
3559            let first_node = ctx.node(first_id)?;
3560            match &first_node.kind {
3561                DcSyntaxKind::Tagged { tag, .. }
3562                    if ctx.token_fills_role(*tag, DcRole::TypeUnion)
3563                        || ctx.token_fills_role(*tag, DcRole::TypeIntersection) =>
3564                {
3565                    let _ = iter.next();
3566                }
3567                DcSyntaxKind::Atom(ch)
3568                    if ctx.token_fills_role(*ch, DcRole::TypeUnion)
3569                        || ctx.token_fills_role(*ch, DcRole::TypeIntersection) =>
3570                {
3571                    let _ = iter.next();
3572                    if let Some(&next_id) = iter.peek() {
3573                        if let DcSyntaxKind::Atom(ch2) = ctx.node(next_id)?.kind {
3574                            if ctx.tokens_equivalent(ch2, filename_format) {
3575                                let _ = iter.next();
3576                                if let Some(&third_id) = iter.peek() {
3577                                    if let DcSyntaxKind::Atom(ch3) = ctx.node(third_id)?.kind {
3578                                        if ctx.token_fills_role(ch3, DcRole::FilePathDelimiter) {
3579                                            let _ = iter.next();
3580                                        }
3581                                    }
3582                                }
3583                            }
3584                        }
3585                    }
3586                }
3587                _ => {}
3588            }
3589        }
3590
3591        let mut segments = vec![Vec::new()];
3592        let mut previous_was_filename = false;
3593
3594        for child_id in iter {
3595            let child_node = ctx.node(child_id)?;
3596            if let DcSyntaxKind::Atom(ch) = child_node.kind {
3597                if ctx.token_fills_role(ch, DcRole::FilePathDelimiter) {
3598                    segments.push(Vec::new());
3599                    previous_was_filename = false;
3600                    continue;
3601                }
3602            }
3603            ensure!(!previous_was_filename, "Missing delimiter between filename segments");
3604            let (child_fmt, payload_id) = match ctx.unwrap_format_representation(child_id)? {
3605                Some(p) => p,
3606                None => bail!("Expected format representation for filename segment, found {:?}", ctx.node(child_id)?.kind),
3607            };
3608            ensure!(ctx.tokens_equivalent(child_fmt, filename_format), "Unexpected format for filename segment: {child_fmt:?}");
3609            let segment = decode_filename_bytes(ctx, payload_id)?;
3610            ensure!(!segment.is_empty(), "Empty filename segment");
3611            ensure!(!segment.contains(&b'/'), "Filename segment contains a path delimiter");
3612            *segments.last_mut().context("Missing filepath segment")? = segment;
3613            previous_was_filename = true;
3614        }
3615
3616        Ok(segments)
3617    })
3618}
3619
3620impl DcMixedDecode for PathBuf {
3621    fn decode_dc_node(
3622        ctx: &mut DcProjectionContext<'_, '_>,
3623        node_id: NodeId,
3624    ) -> Result<Self> {
3625        let path_format = DcChar::from_u128(
3626            FormatId::FilePath
3627                .dc_id()
3628                .context("Missing FilePath format identifier")?,
3629        );
3630        ctx.decode_transparent(node_id, |ctx, node_id| {
3631            if let Some((fmt, _)) = ctx.unwrap_format_representation(node_id)? {
3632                if ctx.tokens_equivalent(fmt, path_format) {
3633                    let segments = decode_filepath_segments(ctx, node_id)?;
3634                    ensure!(segments.iter().all(|segment| !(cfg!(windows) && segment.contains(&b'\\'))),
3635                        "Filename segment contains a path delimiter");
3636                    return path_from_native_bytes(&segments.join(&if cfg!(windows) { b'\\' } else { b'/' }));
3637                }
3638            }
3639            let node = ctx.node(node_id)?;
3640            bail!("Expected format representation (Dc 511 + f494) for PathBuf, found {:?}", node.kind)
3641        })
3642    }
3643}
3644
3645fn duration_from_nanos(nanos: u128) -> Result<Duration> {
3646    let secs = u64::try_from(
3647        nanos.checked_div(1_000_000_000).context("Division failed")?,
3648    )
3649    .context("secs")?;
3650    let sub_nanos = u32::try_from(
3651        nanos.checked_rem(1_000_000_000).context("Modulo failed")?,
3652    )
3653    .context("sub_nanos")?;
3654    Ok(Duration::new(secs, sub_nanos))
3655}
3656
3657fn system_time_from_signed_nanos(nanos: i128) -> Result<SystemTime> {
3658    let dur = duration_from_nanos(nanos.unsigned_abs())?;
3659    if nanos >= 0 {
3660        std::time::UNIX_EPOCH.checked_add(dur).context("SystemTime overflow")
3661    } else {
3662        std::time::UNIX_EPOCH.checked_sub(dur).context("SystemTime underflow")
3663    }
3664}
3665
3666fn extract_temporal_format_and_arg(
3667    ctx: &DcProjectionContext<'_, '_>,
3668    node_id: NodeId,
3669    roles: &[DcRole],
3670    label: &str,
3671) -> Result<(FormatId, NodeId)> {
3672    let node = ctx.node(node_id)?;
3673    if let DcSyntaxKind::Container {
3674        opener, children, ..
3675    } = &node.kind
3676        && roles.iter().any(|&r| ctx.token_fills_role(*opener, r))
3677    {
3678        let Some(&first_child) = children.first() else {
3679            bail!("Empty {label} ({opener})");
3680        };
3681        let first = ctx.node(first_child)?;
3682        let Some((tag_ch, arg_id)) = (match &first.kind {
3683            DcSyntaxKind::Tagged { tag, args } => {
3684                Some((*tag, args.first().copied()))
3685            }
3686            DcSyntaxKind::Atom(ch) => Some((*ch, children.get(1).copied())),
3687            _ => None,
3688        }) else {
3689            bail!("Expected format token in {label}");
3690        };
3691        let fid = FormatId::from_dc_id(ctx.canonical_token(tag_ch).0)
3692            .with_context(|| format!("Expected format token in {label}"))?;
3693        let num_id = arg_id.with_context(|| {
3694            format!("Missing number after format token in {label}")
3695        })?;
3696        return Ok((fid, num_id));
3697    }
3698    bail!("Expected {label}, found {:?}", node.kind)
3699}
3700
3701fn decode_temporal_with_preferred_format<T>(
3702    ctx: &mut DcProjectionContext<'_, '_>,
3703    node_id: NodeId,
3704    roles: &[DcRole],
3705    preferred_fid: FormatId,
3706    label: &str,
3707    mut decode_fn: impl FnMut(
3708        &mut DcProjectionContext<'_, '_>,
3709        FormatId,
3710        NodeId,
3711    ) -> Result<T>,
3712) -> Result<T> {
3713    let mut candidates = ctx.transparent_candidates(node_id)?;
3714    if candidates.len() > 1 {
3715        candidates.sort_by_key(|&cand_id| {
3716            let is_preferred =
3717                extract_temporal_format_and_arg(ctx, cand_id, roles, label)
3718                    .is_ok_and(|(fid, _)| fid == preferred_fid);
3719            u8::from(!is_preferred)
3720        });
3721    }
3722    ctx.decode_candidates(&candidates, |ctx, cand_id| {
3723        let (fid, num_id) =
3724            extract_temporal_format_and_arg(ctx, cand_id, roles, label)?;
3725        decode_fn(ctx, fid, num_id)
3726    })
3727}
3728
3729/// Platform-independent Unix epoch timestamp with exact 1-nanosecond
3730/// resolution (`sec` signed seconds since `1970-01-01T00:00:00Z` and `nsec`
3731/// in `0..1_000_000_000`).
3732///
3733/// Unlike [`SystemTime`], which on Windows wraps `FILETIME` (`100 ns`
3734/// resolution, `>= 1601-01-01`), `DcEpochTimestamp` preserves full nanosecond
3735/// precision and arbitrary `i64` epoch seconds across all host platforms when
3736/// serializing and deserializing `Dc 390..391` time moments.
3737#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
3738pub struct DcEpochTimestamp {
3739    pub sec: i64,
3740    pub nsec: u32,
3741}
3742
3743impl DcEpochTimestamp {
3744    pub const UNIX_EPOCH: Self = Self { sec: 0, nsec: 0 };
3745
3746    pub fn new(sec: i64, nsec: u32) -> Result<Self> {
3747        ensure!(nsec < 1_000_000_000, "Invalid timestamp nanoseconds: {nsec}");
3748        Ok(Self { sec, nsec })
3749    }
3750
3751    pub fn to_signed_nanos(self) -> Result<i128> {
3752        ensure!(
3753            self.nsec < 1_000_000_000,
3754            "Invalid timestamp nanoseconds: {}",
3755            self.nsec
3756        );
3757        i128::from(self.sec)
3758            .checked_mul(1_000_000_000)
3759            .and_then(|base| base.checked_add(i128::from(self.nsec)))
3760            .context("Timestamp nanoseconds overflow i128")
3761    }
3762
3763    pub fn from_signed_nanos(nanos: i128) -> Result<Self> {
3764        let sec_i128 = nanos
3765            .checked_div_euclid(1_000_000_000)
3766            .context("Timestamp seconds division overflow")?;
3767        let rem_i128 = nanos
3768            .checked_rem_euclid(1_000_000_000)
3769            .context("Timestamp nanoseconds remainder overflow")?;
3770        let sec = i64::try_from(sec_i128)
3771            .context("Timestamp seconds out of i64 range")?;
3772        let nsec = u32::try_from(rem_i128)
3773            .context("Timestamp subsecond nanoseconds out of u32 range")?;
3774        Ok(Self { sec, nsec })
3775    }
3776}
3777
3778impl DcForgivingDefault for DcEpochTimestamp {
3779    fn dc_forgiving_default() -> Self {
3780        Self::UNIX_EPOCH
3781    }
3782}
3783
3784fn encode_time_moment_signed_nanos(
3785    nanos: i128,
3786    mst: &mut crate::DcWriter<'_>,
3787) -> Result<()> {
3788    mst.push_char(DC_BEGIN_TIME_MOMENT)?;
3789    mst.push_char(format_dc_char(FormatId::NsSinceEpoch)?)?;
3790    nanos.encode_dc_mixed_to(mst)?;
3791    mst.push_char(DC_END_TIME_MOMENT)?;
3792    Ok(())
3793}
3794
3795fn decode_time_moment_signed_nanos(
3796    ctx: &mut DcProjectionContext<'_, '_>,
3797    node_id: NodeId,
3798    type_name: &str,
3799) -> Result<i128> {
3800    let label = format!("time moment container (Dc 390..391) for {type_name}");
3801    decode_temporal_with_preferred_format(
3802        ctx,
3803        node_id,
3804        &[DcRole::BeginTimeMoment],
3805        FormatId::NsSinceEpoch,
3806        &label,
3807        |ctx, fid, num_id| match fid {
3808            FormatId::SecondsSinceEpoch => {
3809                i128::from(i64::decode_dc_node(ctx, num_id)?)
3810                    .checked_mul(1_000_000_000)
3811                    .context("Seconds to nanoseconds overflow")
3812            }
3813            FormatId::NsSinceEpoch => i128::decode_dc_node(ctx, num_id),
3814            _ => bail!("Unsupported {type_name} format: {fid:?}"),
3815        },
3816    )
3817}
3818
3819impl DcMixedEncode for DcEpochTimestamp {
3820    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3821        encode_time_moment_signed_nanos(self.to_signed_nanos()?, mst)
3822    }
3823}
3824
3825impl DcMixedDecode for DcEpochTimestamp {
3826    fn decode_dc_node(
3827        ctx: &mut DcProjectionContext<'_, '_>,
3828        node_id: NodeId,
3829    ) -> Result<Self> {
3830        let nanos = decode_time_moment_signed_nanos(
3831            ctx,
3832            node_id,
3833            "DcEpochTimestamp",
3834        )?;
3835        Self::from_signed_nanos(nanos)
3836    }
3837}
3838
3839impl DcMixedEncode for SystemTime {
3840    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3841        let nanos: i128 = match self.duration_since(std::time::UNIX_EPOCH) {
3842            Ok(dur) => i128::try_from(dur.as_nanos())?,
3843            Err(err) => {
3844                let before = i128::try_from(err.duration().as_nanos())?;
3845                before.checked_neg().context("Timestamp underflow")?
3846            }
3847        };
3848        encode_time_moment_signed_nanos(nanos, mst)
3849    }
3850}
3851
3852impl DcMixedDecode for SystemTime {
3853    fn decode_dc_node(
3854        ctx: &mut DcProjectionContext<'_, '_>,
3855        node_id: NodeId,
3856    ) -> Result<Self> {
3857        let nanos =
3858            decode_time_moment_signed_nanos(ctx, node_id, "SystemTime")?;
3859        system_time_from_signed_nanos(nanos)
3860    }
3861}
3862
3863impl DcMixedEncode for Duration {
3864    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3865        mst.push_char(DC_BEGIN_DATE_MAGNITUDE)?;
3866        mst.push_char(format_dc_char(FormatId::Nanosecond)?)?;
3867        self.as_nanos().encode_dc_mixed_to(mst)?;
3868        mst.push_char(DC_END_DATE_MAGNITUDE)?;
3869        Ok(())
3870    }
3871}
3872
3873impl DcMixedDecode for Duration {
3874    fn decode_dc_node(
3875        ctx: &mut DcProjectionContext<'_, '_>,
3876        node_id: NodeId,
3877    ) -> Result<Self> {
3878        decode_temporal_with_preferred_format(
3879            ctx,
3880            node_id,
3881            &[DcRole::BeginDateMagnitude, DcRole::BeginDateDuration],
3882            FormatId::Nanosecond,
3883            "duration container (Dc 393..394 or 395..396) for Duration",
3884            |ctx, fid, num_id| match fid {
3885                FormatId::Second => {
3886                    Ok(Duration::from_secs(u64::decode_dc_node(ctx, num_id)?))
3887                }
3888                FormatId::Nanosecond => {
3889                    duration_from_nanos(u128::decode_dc_node(ctx, num_id)?)
3890                }
3891                _ => bail!("Unsupported Duration format: {fid:?}"),
3892            },
3893        )
3894    }
3895}
3896
3897impl<T: DcMixedEncode, const N: usize> DcMixedEncode for [T; N] {
3898    fn encode_dc_mixed_to(&self, mst: &mut crate::DcWriter<'_>) -> Result<()> {
3899        self.encode_dc_mixed_to_with_context(
3900            mst,
3901            &crate::SharedValueContext::default(),
3902        )
3903    }
3904    fn encode_dc_mixed_to_with_context(
3905        &self,
3906        mst: &mut crate::DcWriter<'_>,
3907        context: &crate::SharedValueContext,
3908    ) -> Result<()> {
3909        for elem in self {
3910            elem.encode_dc_mixed_to_with_context(mst, context)?;
3911        }
3912        Ok(())
3913    }
3914}
3915
3916impl<T: DcMixedDecode, const N: usize> DcMixedDecode for [T; N] {
3917    fn decode_dc_document(
3918        ctx: &mut DcProjectionContext<'_, '_>,
3919        roots: &[NodeId],
3920    ) -> Result<(Self, usize)> {
3921        let root = roots
3922            .first()
3923            .copied()
3924            .context("Empty document cannot be decoded into array")?;
3925        if roots.len() > 1 {
3926            if let Ok(arr) = Self::decode_dc_node(ctx, root) {
3927                return Ok((arr, 1));
3928            }
3929            let mut items = Vec::with_capacity(N);
3930            for &root in roots.iter().take(N) {
3931                items.push(T::decode_dc_node(ctx, root)?);
3932            }
3933            let array = items.try_into().map_err(|items: Vec<T>| {
3934                anyhow!(
3935                    "Array length mismatch: expected {N}, found {}",
3936                    items.len()
3937                )
3938            })?;
3939            return Ok((array, N));
3940        }
3941        Ok((Self::decode_dc_node(ctx, root)?, 1))
3942    }
3943
3944    fn decode_dc_node(
3945        ctx: &mut DcProjectionContext<'_, '_>,
3946        node_id: NodeId,
3947    ) -> Result<Self> {
3948        ctx.decode_transparent(node_id, |ctx, node_id| {
3949            let node = ctx.node(node_id)?;
3950            if let DcSyntaxKind::Container { opener, children, .. } = &node.kind {
3951                if ctx.token_fills_role(*opener, DcRole::BeginList)
3952                    || ctx.token_fills_role(*opener, DcRole::BeginFormatRepresentation)
3953                {
3954                    let child_slice: &[NodeId] = if ctx.token_fills_role(*opener, DcRole::BeginFormatRepresentation)
3955                        && children.len() == N.saturating_add(1)
3956                    {
3957                        match children.split_first() {
3958                            Some((_, rest)) => rest,
3959                            None => &[],
3960                        }
3961                    } else {
3962                        children.as_slice()
3963                    };
3964                    let mut items: Vec<T> = Vec::with_capacity(N);
3965                    for &child_id in child_slice {
3966                        let child = ctx.node(child_id)?;
3967                        if let DcSyntaxKind::Atom(ch) = child.kind {
3968                            if ctx.token_fills_role(ch, DcRole::ListElementSeparator) || ctx.token_fills_role(ch, DcRole::TypeToken) {
3969                                continue;
3970                            }
3971                        }
3972                        items.push(T::decode_dc_node(ctx, child_id)?);
3973                    }
3974                    return items.try_into().map_err(|_| anyhow::anyhow!("Array length mismatch: expected {N}"));
3975                }
3976            }
3977            if let DcSyntaxKind::Tagged { args, .. } = &node.kind {
3978                if args.len() == N {
3979                    let mut items: Vec<T> = Vec::with_capacity(N);
3980                    for &arg_id in args {
3981                        items.push(T::decode_dc_node(ctx, arg_id)?);
3982                    }
3983                    return items.try_into().map_err(|_| anyhow::anyhow!("Array length mismatch: expected {N}"));
3984                }
3985            }
3986            if N == 1 {
3987                let item = T::decode_dc_node(ctx, node_id)?;
3988                return vec![item].try_into().map_err(|_| anyhow::anyhow!("Array length mismatch"));
3989            }
3990            bail!("Expected container or {N} local elements for [T; {N}], found {:?}", node.kind)
3991        })
3992    }
3993}
3994
3995// ----------------------------------------------------------------------------
3996// Universal Verification Harness
3997// ----------------------------------------------------------------------------
3998
3999fn assert_dc_roundtrip_inner<T>(
4000    original: &T,
4001    strict_syntax: bool,
4002) -> Result<()>
4003where
4004    T: DcMixedEncode + DcMixedDecode + PartialEq + fmt::Debug,
4005{
4006    let mut mst = DcMstring::new();
4007    original.encode_dc_mixed(&mut mst)?;
4008
4009    if strict_syntax {
4010        crate::validate_dc_mixed_strict(&mst).context(
4011            "Strict Dc syntax validation failed during document roundtrip check",
4012        )?;
4013    }
4014
4015    let policy = crate::DcProjectionPolicy::strict();
4016    let decoded = mst.decode::<T>(&policy).context(
4017        "Failed to decode struct during DcMixed roundtrip verification",
4018    )?;
4019
4020    ensure!(
4021        *original == decoded,
4022        "DcMixed roundtrip value mismatch!\nOriginal: {original:#?}\nDecoded:  {decoded:#?}"
4023    );
4024
4025    let mut re_encoded = DcMstring::new();
4026    decoded.encode_dc_mixed(&mut re_encoded)?;
4027    ensure!(
4028        mst == re_encoded,
4029        "DcMixed serialization is not canonical (re-encoding produced different bytes)"
4030    );
4031
4032    Ok(())
4033}
4034
4035/// Asserts that serializing `original` to `DcMstring` and deserializing it produces
4036/// an identical instance, and that re-encoding produces byte-identical output.
4037///
4038/// Runs unconditionally in both debug and release mode to fail loudly on any
4039/// loss of semantic fidelity or non-canonical serialization.
4040///
4041/// # Errors
4042/// Returns an error if encoding, decoding, or verification fails.
4043pub fn assert_dc_roundtrip<T>(original: &T) -> Result<()>
4044where
4045    T: DcMixedEncode + DcMixedDecode + PartialEq + fmt::Debug,
4046{
4047    assert_dc_roundtrip_inner(original, false)
4048}
4049
4050/// Asserts that a document struct serializes into a valid `DcMixed` buffer,
4051/// conforms strictly to all documented syntax rules from the Dc database,
4052/// decodes to an identical instance, and re-encodes identically.
4053///
4054/// # Errors
4055/// Returns an error if encoding, syntax validation, decoding, or canonical
4056/// check fails.
4057pub fn assert_dc_document_roundtrip<T>(original: &T) -> Result<()>
4058where
4059    T: DcMixedEncode + DcMixedDecode + PartialEq + fmt::Debug,
4060{
4061    assert_dc_roundtrip_inner(original, true)
4062}
4063
4064#[cfg(test)]
4065#[allow(
4066    clippy::panic,
4067    clippy::expect_used,
4068    clippy::unwrap_used,
4069    clippy::unwrap_in_result,
4070    clippy::panic_in_result_fn,
4071    clippy::indexing_slicing,
4072    clippy::arithmetic_side_effects,
4073    reason = "Standard repository test boilerplate"
4074)]
4075mod tests {
4076    #[crate::ctb_test]
4077    fn test_whole_string_decode_preserves_source() -> Result<()> {
4078        let strict = crate::DcProjectionPolicy::strict();
4079        let mut source = 42_u64.to_dc_mixed()?;
4080        let original = source.clone();
4081        assert_eq!(source.decode::<u64>(&strict)?, 42);
4082        assert_eq!(source, original);
4083        source.push_str("unknown suffix");
4084        let original = source.clone();
4085        source.decode::<u64>(&strict).unwrap_err();
4086        assert_eq!(source, original);
4087        source.push_binary(b"suffix");
4088        source.decode::<u64>(&strict).unwrap_err();
4089        Ok(())
4090    }
4091    use super::*;
4092    use crate::DcMixed;
4093    use crate::{DcMixedFields, DcProjectionPolicy, DcSource};
4094
4095    fn sample_source_record(inode: u64) -> SampleFileRecord {
4096        SampleFileRecord {
4097            inode,
4098            path: "path".into(),
4099            is_directory: false,
4100            optional_size: Some(42),
4101        }
4102    }
4103
4104    #[crate::ctb_test]
4105    fn test_source_inspection_unknown_and_incomplete() -> Result<()> {
4106        let original = sample_source_record(42);
4107        let updated = sample_source_record(999);
4108        for unknown in [false, true] {
4109            let mut source = DcMstring::new();
4110            source.push_char(DcChar::from_short(317));
4111            original.encode_dc_field("inode", &mut source)?;
4112            let stop = source.len();
4113            if unknown {
4114                source.push_char(DcChar::from_short(600));
4115                source
4116                    .push_binary_with_sha256(b"unknown future syntax")
4117                    .unwrap();
4118                original.encode_dc_field("path", &mut source)?;
4119                source.push_char(DcChar::from_short(318));
4120            }
4121            let before = source.clone();
4122            let strict_view = source.inspect::<SampleFileRecord>();
4123            assert!(strict_view.value().is_none());
4124            assert!(strict_view.diagnostic().is_some());
4125            let quiet = DcProjectionPolicy::forgiving_quiet();
4126            let view = source.inspect_with_policy::<SampleFileRecord>(&quiet);
4127            assert!(view.value().is_some());
4128            assert!(!view.diagnostics().is_empty());
4129            if !unknown {
4130                assert!(view.diagnostics().iter().any(|diagnostic| {
4131                    diagnostic
4132                        .error()
4133                        .to_string()
4134                        .contains("Missing required field")
4135                }));
4136            }
4137            assert_eq!(view.fields().len(), if unknown { 2 } else { 1 });
4138            assert_eq!(view.fields()[0].field(), "inode");
4139            assert_eq!(view.source_bytes(), source.as_bytes());
4140            if unknown {
4141                assert_eq!(view.fields()[1].field(), "path");
4142                view.replace_field("path", &updated).unwrap();
4143            } else {
4144                view.replace_field("path", &updated).unwrap_err();
4145            }
4146            let revised = view.replace_field("inode", &updated)?;
4147            let replacement_end = revised
4148                .inspect_with_policy::<SampleFileRecord>(&quiet)
4149                .fields()[0]
4150                .range()
4151                .end;
4152            assert_eq!(
4153                revised.as_bytes().get(replacement_end..),
4154                source.as_bytes().get(stop..)
4155            );
4156            assert_eq!(source, before);
4157            let text = source.to_dc_string()?;
4158            let view = text.inspect_with_policy::<SampleFileRecord>(&quiet);
4159            let revised: crate::DcString =
4160                view.replace_field("inode", &updated)?;
4161            assert_eq!(
4162                revised
4163                    .inspect_with_policy::<SampleFileRecord>(&quiet)
4164                    .fields()[0]
4165                    .range()
4166                    .start,
4167                4
4168            );
4169        }
4170        Ok(())
4171    }
4172
4173    #[crate::ctb_test]
4174    fn test_source_inspection_complete_and_trailing() -> Result<()> {
4175        let strict = DcProjectionPolicy::strict();
4176        let original = sample_source_record(42);
4177        let updated = sample_source_record(999);
4178        let mut source = original.to_dc_mixed()?;
4179        let view = source.inspect::<SampleFileRecord>();
4180        assert_eq!(view.value(), Some(&original));
4181        assert!(view.diagnostic().is_none());
4182        assert_eq!(view.fields().len(), 4);
4183        let revised = view.replace_field("inode", &updated)?;
4184        assert_eq!(revised.decode::<SampleFileRecord>(&strict)?, updated);
4185        let text = original.to_dc_string()?;
4186        assert_eq!(text.decode::<SampleFileRecord>(&strict)?, original);
4187        let revised: crate::DcString = text
4188            .inspect::<SampleFileRecord>()
4189            .replace_field("inode", &updated)?;
4190        assert_eq!(revised.decode::<SampleFileRecord>(&strict)?, updated);
4191        source.push_binary(b"unknown suffix");
4192        let view = source.inspect::<SampleFileRecord>();
4193        assert_eq!(view.value(), Some(&original));
4194        assert!(view.diagnostic().is_some());
4195        source.decode::<SampleFileRecord>(&strict).unwrap_err();
4196        let revised = view.replace_field("inode", &updated)?;
4197        assert_eq!(revised.chunks().last(), source.chunks().last());
4198        Ok(())
4199    }
4200
4201    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4202    #[dc(begin = 401, end = 402)]
4203    struct SourceBinaryRecord {
4204        #[dc(short = 403)]
4205        title: String,
4206        #[dc(short = 404, binary)]
4207        bytes: Vec<u8>,
4208    }
4209
4210    #[crate::ctb_test]
4211    fn test_source_inspection_binary_and_encapsulation_boundaries() -> Result<()>
4212    {
4213        let strict = DcProjectionPolicy::strict();
4214        let original = SourceBinaryRecord {
4215            title: "TEXT".to_owned(),
4216            bytes: vec![0, 255, 42, 0],
4217        };
4218        let updated = SourceBinaryRecord {
4219            title: "CODE".to_owned(),
4220            bytes: vec![43, 0, 0, 0],
4221        };
4222        let source = original.to_dc_mixed()?;
4223        let view = source.inspect::<SourceBinaryRecord>();
4224        let revised = view.replace_field("bytes", &updated)?;
4225        let decoded = revised.decode::<SourceBinaryRecord>(&strict)?;
4226        assert_eq!(decoded.title, original.title);
4227        assert_eq!(decoded.bytes, updated.bytes);
4228        let text = original.to_dc_string()?;
4229        assert_eq!(text.decode::<SourceBinaryRecord>(&strict)?, original);
4230        let revised_text = text
4231            .inspect::<SourceBinaryRecord>()
4232            .replace_field("bytes", &updated)?;
4233        assert_eq!(
4234            revised_text.decode::<SourceBinaryRecord>(&strict)?.bytes,
4235            updated.bytes
4236        );
4237        let field = view
4238            .fields()
4239            .iter()
4240            .find(|field| field.field() == "bytes")
4241            .context("Missing binary field")?;
4242        let prefix_end = field.range().start;
4243        assert_eq!(
4244            revised.as_bytes().get(..prefix_end),
4245            source.as_bytes().get(..prefix_end)
4246        );
4247        let mut encapsulated = DcMstring::new();
4248        encapsulated.push_binary(b"payload");
4249        encapsulated
4250            .replace_source_field(22..23, &source)
4251            .unwrap_err();
4252        Ok(())
4253    }
4254
4255    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4256    #[dc(begin = 401, end = 402)]
4257    struct SourceNestedRecord {
4258        #[dc(nested = 317)]
4259        inner: SampleFileRecord,
4260        #[dc(short = 333)]
4261        numbers: Vec<u64>,
4262    }
4263
4264    #[crate::ctb_test]
4265    fn test_source_inspection_nested_and_repeated() -> Result<()> {
4266        let strict = DcProjectionPolicy::strict();
4267        let original = SourceNestedRecord {
4268            inner: sample_source_record(42),
4269            numbers: vec![1, 2],
4270        };
4271        let updated = SourceNestedRecord {
4272            inner: sample_source_record(999),
4273            numbers: vec![3],
4274        };
4275        let source = original.to_dc_mixed()?;
4276        let view = source.inspect::<SourceNestedRecord>();
4277        assert!(
4278            view.fields()
4279                .iter()
4280                .any(|field| field.field() == "inode" && field.depth() == 2)
4281        );
4282        view.replace_field("inode", &updated).unwrap_err();
4283        view.replace_field("numbers", &updated).unwrap_err();
4284        let inode = view
4285            .fields()
4286            .iter()
4287            .find(|field| field.field() == "inode")
4288            .context("Missing nested inode")?;
4289        let revised = view.replace_annotation(inode, &updated.inner)?;
4290        assert_eq!(
4291            revised.decode::<SourceNestedRecord>(&strict)?.inner,
4292            updated.inner
4293        );
4294        view.replace_annotation(inode, &updated).unwrap_err();
4295        let other_view = source.inspect::<SourceNestedRecord>();
4296        other_view
4297            .replace_annotation(inode, &updated.inner)
4298            .unwrap_err();
4299        let number = view
4300            .fields()
4301            .iter()
4302            .find(|field| field.field() == "numbers")
4303            .context("Missing repeated field")?;
4304        let revised = view.replace_annotation(number, &updated)?;
4305        assert_eq!(
4306            revised.decode::<SourceNestedRecord>(&strict)?.numbers,
4307            vec![3, 2]
4308        );
4309        let revised = view.replace_field("inner", &updated)?;
4310        let decoded = revised.decode::<SourceNestedRecord>(&strict)?;
4311        assert_eq!(decoded.inner, updated.inner);
4312        assert_eq!(decoded.numbers, original.numbers);
4313        let mut duplicate = DcMstring::new();
4314        duplicate.push_char(DcChar::from_short(317));
4315        original.inner.encode_dc_field("inode", &mut duplicate)?;
4316        updated.inner.encode_dc_field("inode", &mut duplicate)?;
4317        duplicate
4318            .inspect::<SampleFileRecord>()
4319            .replace_field("inode", &updated.inner)
4320            .unwrap_err();
4321        Ok(())
4322    }
4323
4324    #[crate::ctb_test]
4325    fn test_source_navigator_positions() -> Result<()> {
4326        let strict = DcProjectionPolicy::strict();
4327        let mut source = DcMstring::new();
4328        source.push_str("\u{e9}");
4329        source.push_binary_with_sha256(b"payload").unwrap();
4330        source.push_str("end");
4331        let mut nav = crate::DcDocumentNavigator::from_mstr(&source);
4332        assert_eq!(
4333            nav.cursor(),
4334            u64::try_from(crate::DCMM_HEADER_LEN).unwrap()
4335        );
4336        let stub1 = nav.next_sibling_stub(&strict)?.unwrap();
4337        assert_eq!(stub1.head_dc, DcChar::from_char('\u{e9}'));
4338        let stub2 = nav.next_sibling_stub(&strict)?.unwrap();
4339        assert_eq!(stub2.head_dc, DC_START_ENCAPSULATION_BINARY);
4340        let stub3 = nav.next_sibling_stub(&strict)?.unwrap();
4341        assert_eq!(stub3.head_dc, DcChar::from_char('e'));
4342        Ok(())
4343    }
4344
4345    #[crate::ctb_test]
4346    fn test_source_keyed_record_edits() -> Result<()> {
4347        let strict = DcProjectionPolicy::strict();
4348        let original = SampleKeyedRecord {
4349            count: 42,
4350            label: Some("original".to_owned()),
4351        };
4352        let updated = SampleKeyedRecord {
4353            count: 999,
4354            label: None,
4355        };
4356        let source = original.to_dc_mixed()?;
4357        let view = source.inspect::<SampleKeyedRecord>();
4358        assert_eq!(view.fields().len(), 2);
4359        let revised = view.replace_field("label", &updated)?;
4360        assert_eq!(
4361            revised.decode::<SampleKeyedRecord>(&strict)?,
4362            SampleKeyedRecord {
4363                count: 42,
4364                label: None
4365            }
4366        );
4367        let text = original.to_dc_string()?;
4368        let revised = text
4369            .inspect::<SampleKeyedRecord>()
4370            .replace_field("count", &updated)?;
4371        assert_eq!(revised.decode::<SampleKeyedRecord>(&strict)?.count, 999);
4372        let mut incomplete = DcMstring::new();
4373        incomplete.push_char(DcChar::from_short(313));
4374        incomplete.push_char(DcChar::from_short(275));
4375        incomplete.push_char(DcChar::from_short(275));
4376        original.encode_dc_map_field(
4377            "count",
4378            &mut incomplete,
4379            crate::DcKvMapEncoding::Legacy,
4380        )?;
4381        incomplete.push_char(DcChar::from_short(312));
4382        "future".encode_dc_mixed(&mut incomplete)?;
4383        incomplete
4384            .push_binary_with_sha256(b"unknown value")
4385            .unwrap();
4386        let forgiving = DcProjectionPolicy::forgiving();
4387        let view =
4388            incomplete.inspect_with_policy::<SampleKeyedRecord>(&forgiving);
4389        assert!(view.diagnostic().is_some());
4390        let end = view.fields()[0].range().end;
4391        let revised = view.replace_field("count", &updated)?;
4392        let revised_end = revised
4393            .inspect_with_policy::<SampleKeyedRecord>(&forgiving)
4394            .fields()[0]
4395            .range()
4396            .end;
4397        assert_eq!(
4398            revised.as_bytes().get(revised_end..),
4399            incomplete.as_bytes().get(end..)
4400        );
4401        Ok(())
4402    }
4403
4404    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4405    #[dc(begin = 317, end = 318)]
4406    struct SampleFileRecord {
4407        #[dc(short = 327)]
4408        inode: u64,
4409        #[dc(short = 337)]
4410        path: std::path::PathBuf,
4411        #[dc(short = 369)]
4412        is_directory: bool,
4413        #[dc(short = 336)]
4414        optional_size: Option<u64>,
4415    }
4416
4417    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4418    enum SampleKind {
4419        #[dc(short = 358)]
4420        Regular,
4421        #[dc(short = 359)]
4422        Directory,
4423    }
4424
4425    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4426    #[dc(key_value)]
4427    struct SampleKeyedRecord {
4428        #[dc(key = "count")]
4429        count: u64,
4430        #[dc(key = "label")]
4431        label: Option<String>,
4432    }
4433
4434    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4435    #[dc(names, begin = 310, end = 311)]
4436    enum SampleNamedValue {
4437        #[dc(name = "unsigned")]
4438        Unsigned(u64),
4439        #[dc(name = "signed")]
4440        Signed(i64),
4441        #[dc(name = "bytes", binary)]
4442        Bytes(Vec<u8>),
4443        #[dc(name = "empty")]
4444        Empty,
4445    }
4446
4447    #[crate::ctb_test]
4448    fn test_named_key_value_syntax() -> Result<()> {
4449        let strict = DcProjectionPolicy::strict();
4450        let record = SampleKeyedRecord {
4451            count: u64::MAX,
4452            label: None,
4453        };
4454        assert_dc_roundtrip(&record)?;
4455        assert_dc_roundtrip(&SampleKeyedRecord {
4456            count: 0,
4457            label: Some("value".to_string()),
4458        })?;
4459        let mut encoded = DcMstring::new();
4460        record.encode_dc_mixed(&mut encoded)?;
4461        assert_eq!(encoded.decode::<SampleKeyedRecord>(&strict)?, record);
4462
4463        let map = BTreeMap::from([
4464            ("count".to_string(), SampleNamedValue::Unsigned(u64::MAX)),
4465            ("minimum".to_string(), SampleNamedValue::Signed(i64::MIN)),
4466            (
4467                "binary".to_string(),
4468                SampleNamedValue::Bytes(vec![0, 255, 128]),
4469            ),
4470            ("empty".to_string(), SampleNamedValue::Empty),
4471        ]);
4472        assert_dc_roundtrip(&map)?;
4473        assert_dc_roundtrip(&BTreeMap::<String, SampleNamedValue>::new())?;
4474        let mut encoded = DcMstring::new();
4475        SampleNamedValue::Unsigned(42).encode_dc_mixed(&mut encoded)?;
4476        assert_eq!(
4477            encoded.decode::<SampleNamedValue>(&strict)?,
4478            SampleNamedValue::Unsigned(42)
4479        );
4480        Ok(())
4481    }
4482
4483    #[crate::ctb_test]
4484    fn test_named_key_value_rejects_malformed() -> Result<()> {
4485        let strict = DcProjectionPolicy::strict();
4486        for encoding in [
4487            crate::DcKvMapEncoding::Legacy,
4488            crate::DcKvMapEncoding::Pairs,
4489        ] {
4490            for keys in [
4491                vec!["count"],
4492                vec!["count", "count"],
4493                vec!["unknown"],
4494                vec!["label", "count"],
4495            ] {
4496                let mut encoded = DcMstring::new();
4497                encoding.encode_header(&mut encoded);
4498                for (index, key) in keys.iter().enumerate() {
4499                    encoding.encode_entry_begin(&mut encoded, index == 0);
4500                    key.encode_dc_mixed(&mut encoded)?;
4501                    encoded.push_char(DcChar::from_short(312));
4502                    1u64.encode_dc_mixed(&mut encoded)?;
4503                    encoding.encode_entry_end(&mut encoded);
4504                }
4505                encoding.encode_end(&mut encoded);
4506                encoded.decode::<SampleKeyedRecord>(&strict).unwrap_err();
4507            }
4508            let mut duplicate = DcMstring::new();
4509            encoding.encode_header(&mut duplicate);
4510            for value in [1u64, 2] {
4511                encoding.encode_entry_begin(&mut duplicate, value == 1);
4512                "count".encode_dc_mixed(&mut duplicate)?;
4513                duplicate.push_char(DcChar::from_short(312));
4514                value.encode_dc_mixed(&mut duplicate)?;
4515                encoding.encode_entry_end(&mut duplicate);
4516            }
4517            encoding.encode_end(&mut duplicate);
4518            duplicate
4519                .decode::<BTreeMap<String, u64>>(&strict)
4520                .unwrap_err();
4521        }
4522        for separators in [false, true] {
4523            let mut encoded = DcMstring::new();
4524            encoded.push_char(DC_BEGIN_KV_MAP);
4525            encoded.push_char(DcChar::from_short(275));
4526            encoded.push_char(DcChar::from_short(275));
4527            "count".encode_dc_mixed(&mut encoded)?;
4528            if separators {
4529                encoded.push_char(DcChar::from_short(312));
4530            }
4531            1u64.encode_dc_mixed(&mut encoded)?;
4532            encoded
4533                .decode::<BTreeMap<String, u64>>(&strict)
4534                .unwrap_err();
4535        }
4536        let mut legacy = DcMstring::new();
4537        legacy.push_char(DC_BEGIN_KV_MAP);
4538        "count".encode_dc_mixed(&mut legacy)?;
4539        1u64.encode_dc_mixed(&mut legacy)?;
4540        legacy.push_char(DC_END_KV_MAP);
4541        legacy.decode::<SampleKeyedRecord>(&strict).unwrap_err();
4542        legacy.decode::<BTreeMap<String, u64>>(&strict).unwrap_err();
4543        Ok(())
4544    }
4545
4546    #[crate::ctb_test]
4547    fn test_named_key_value_legacy_reads_and_edits() -> Result<()> {
4548        let strict = DcProjectionPolicy::strict();
4549        let original = SampleKeyedRecord {
4550            count: 42,
4551            label: Some("old".to_owned()),
4552        };
4553        let updated = SampleKeyedRecord {
4554            count: 999,
4555            label: None,
4556        };
4557        let encoding = crate::DcKvMapEncoding::Legacy;
4558        let mut source = DcMstring::new();
4559        encoding.encode_header(&mut source);
4560        original.encode_dc_map_field("count", &mut source, encoding)?;
4561        source.push_char(DcChar::from_short(312));
4562        original.encode_dc_map_field("label", &mut source, encoding)?;
4563        encoding.encode_end(&mut source);
4564        assert_eq!(source.decode::<SampleKeyedRecord>(&strict)?, original);
4565        let view = source.inspect::<SampleKeyedRecord>();
4566        let range = view.fields()[0].range();
4567        let revised = view.replace_field("count", &updated)?;
4568        assert_eq!(revised.decode::<SampleKeyedRecord>(&strict)?.count, 999);
4569        let revised_range =
4570            revised.inspect::<SampleKeyedRecord>().fields()[0].range();
4571        assert_eq!(
4572            source.as_bytes().get(..range.start),
4573            revised.as_bytes().get(..revised_range.start)
4574        );
4575        assert_eq!(
4576            source.as_bytes().get(range.end..),
4577            revised.as_bytes().get(revised_range.end..)
4578        );
4579        let text = source.to_dc_string()?;
4580        let revised = text
4581            .inspect::<SampleKeyedRecord>()
4582            .replace_field("label", &updated)?;
4583        assert_eq!(revised.decode::<SampleKeyedRecord>(&strict)?.label, None);
4584
4585        for entries in [vec![], vec![("a", 1u64), ("b", 2)]] {
4586            let mut legacy = DcMstring::new();
4587            encoding.encode_header(&mut legacy);
4588            for (index, (key, value)) in entries.iter().enumerate() {
4589                encoding.encode_entry_begin(&mut legacy, index == 0);
4590                key.encode_dc_mixed(&mut legacy)?;
4591                legacy.push_char(DcChar::from_short(312));
4592                value.encode_dc_mixed(&mut legacy)?;
4593            }
4594            encoding.encode_end(&mut legacy);
4595            let decoded = legacy.decode::<BTreeMap<String, u64>>(&strict)?;
4596            assert_eq!(
4597                decoded,
4598                entries
4599                    .iter()
4600                    .map(|(key, value)| ((*key).to_owned(), *value))
4601                    .collect::<BTreeMap<_, _>>()
4602            );
4603            let canonical = decoded.to_dc_mixed()?;
4604            let mut nav = crate::DcDocumentNavigator::from_mstr(&canonical);
4605            assert_eq!(
4606                nav.next_sibling_stub(&strict)?.unwrap().head_dc,
4607                DC_BEGIN_KV_MAP
4608            );
4609            assert_dc_document_roundtrip(&decoded)?;
4610        }
4611        Ok(())
4612    }
4613
4614    #[crate::ctb_test]
4615    fn test_named_key_value_pair_boundaries() -> Result<()> {
4616        let strict = DcProjectionPolicy::strict();
4617        let nested = BTreeMap::from([("inner".to_owned(), 42u64)]);
4618        let outer = BTreeMap::from([("outer".to_owned(), nested)]);
4619        assert_dc_document_roundtrip(&outer)?;
4620        let source = outer.to_dc_mixed()?;
4621        crate::validate_dc_mixed_strict(&source)?;
4622        let original = SampleKeyedRecord {
4623            count: 42,
4624            label: None,
4625        };
4626        let source = original.to_dc_mixed()?;
4627        let view = source.inspect::<SampleKeyedRecord>();
4628        let range = view.fields()[0].range();
4629        let payload = source
4630            .as_bytes()
4631            .get(range)
4632            .context("Missing pair field range")?;
4633        let mut pair_bytes = DcMstring::new().into_bytes();
4634        pair_bytes.extend_from_slice(payload);
4635        let pair = DcMstring::from_bytes(pair_bytes)?;
4636        let mut nav = crate::DcDocumentNavigator::from_mstr(&pair);
4637        let mut arena = crate::DcSyntaxArena::new();
4638        let node_id = nav.parse_node_into_arena(&mut arena, &strict)?;
4639        let pair_node = arena.node(node_id).context("Missing node in arena")?;
4640        assert!(
4641            matches!(pair_node.kind, crate::DcSyntaxKind::Container { opener, .. } if opener.to_short_dc() == Some(514))
4642        );
4643        crate::validate_dc_mixed_strict(&pair)?;
4644
4645        for body in [
4646            vec![514, 517, 312, 518],
4647            vec![514, 517, 312, 518, 515, 312, 514, 517, 312, 518, 515],
4648            vec![517, 312, 518],
4649        ] {
4650            let mut invalid = DcMstring::new();
4651            crate::DcKvMapEncoding::Pairs.encode_header(&mut invalid);
4652            for dc in body {
4653                invalid.push_char(DcChar::from_short(dc));
4654            }
4655            crate::DcKvMapEncoding::Pairs.encode_end(&mut invalid);
4656            invalid.decode::<BTreeMap<bool, bool>>(&strict).unwrap_err();
4657            assert!(crate::validate_dc_mixed_strict(&invalid).is_err());
4658        }
4659        Ok(())
4660    }
4661
4662    #[crate::ctb_test]
4663    fn test_native_path_roundtrips() -> Result<()> {
4664        let strict = DcProjectionPolicy::strict();
4665        for path in ["", "/", "a//b/", "./../a", "a/b", "a/Unicode-\u{1f600}"] {
4666            assert_dc_roundtrip(&PathBuf::from(path))?;
4667        }
4668        #[cfg(unix)]
4669        {
4670            use std::os::unix::ffi::OsStrExt;
4671            for bytes in [b"a/\xff\x80".as_slice(), b"a\\b/\xfe".as_slice()] {
4672                let path = PathBuf::from(std::ffi::OsStr::from_bytes(bytes));
4673                let encoded = path.to_dc_mixed()?;
4674                let decoded = encoded.decode::<PathBuf>(&strict)?;
4675                assert_eq!(decoded.as_os_str().as_encoded_bytes(), bytes);
4676            }
4677        }
4678        #[cfg(windows)]
4679        {
4680            use std::os::windows::ffi::OsStringExt;
4681            let path = PathBuf::from(std::ffi::OsString::from_wide(&[
4682                0x61, 0x5c, 0xd800, 0x62, 0xdc00,
4683            ]));
4684            let encoded = path.to_dc_mixed()?;
4685            let decoded = encoded.decode::<PathBuf>(&strict)?;
4686            assert_eq!(
4687                decoded.as_os_str().as_encoded_bytes(),
4688                path.as_os_str().as_encoded_bytes()
4689            );
4690            for path in [
4691                r"\\?\C:\parent\name",
4692                r"\\?\UNC\server\share\name",
4693                r"C:\parent\name",
4694            ] {
4695                assert_dc_roundtrip(&PathBuf::from(path))?;
4696            }
4697        }
4698        let encoded = PathBuf::from("name").to_dc_mixed()?;
4699        let mut nav = crate::DcDocumentNavigator::from_mstr(&encoded);
4700        let mut arena = crate::DcSyntaxArena::new();
4701        let node_id = nav.parse_node_into_arena(&mut arena, &strict)?;
4702        let mut ctx = crate::DcProjectionContext::new(&arena, &strict);
4703        assert_eq!(
4704            PathBuf::decode_dc_node(&mut ctx, node_id)?,
4705            PathBuf::from("name")
4706        );
4707        Ok(())
4708    }
4709
4710    #[crate::ctb_test]
4711    fn test_conflicting_filename_representations_rejected() -> Result<()> {
4712        let strict = DcProjectionPolicy::strict();
4713        let mut encoded = DcMstring::new();
4714        encoded.push_char(DC_EQUIVALENT_REPRESENTATIONS);
4715        encoded.push_char(DC_BEGIN_LIST);
4716        encoded.push_char(DcChar::from_short(275));
4717        "text".encode_dc_mixed(&mut encoded)?;
4718        encoded.push_char(DC_LIST_ELEMENT_SEPARATOR);
4719        encoded.push_binary_with_sha256(b"different").unwrap();
4720        encoded.push_char(DC_END_LIST);
4721        let mut nav = crate::DcDocumentNavigator::from_mstr(&encoded);
4722        let mut arena = crate::DcSyntaxArena::new();
4723        let node_id = nav.parse_node_into_arena(&mut arena, &strict)?;
4724        let mut ctx = crate::DcProjectionContext::new(&arena, &strict);
4725        decode_filename_bytes(&mut ctx, node_id).unwrap_err();
4726        Ok(())
4727    }
4728
4729    #[crate::ctb_test]
4730    fn test_primitive_roundtrips() -> Result<()> {
4731        assert_dc_roundtrip(&"Hello, world!".to_string())?;
4732        assert_dc_roundtrip(&42u64)?;
4733        assert_dc_roundtrip(&(-123456i64))?;
4734        assert_dc_roundtrip(&true)?;
4735        assert_dc_roundtrip(&false)?;
4736        assert_dc_roundtrip(&Some(999u32))?;
4737        assert_dc_roundtrip(&Option::<u32>::None)?;
4738        assert_dc_roundtrip(&vec![1u8, 2, 3, 4, 5])?;
4739        assert_dc_roundtrip(&BinaryPayload::new(vec![0xDE, 0xAD, 0xBE, 0xEF]))?;
4740        assert_dc_roundtrip(&Box::new(12345u32))?;
4741        assert_dc_roundtrip(&Arc::new("shared_string".to_string()))?;
4742        assert_dc_roundtrip(&PathBuf::from("foo/bar/baz.txt"))?;
4743        assert_dc_roundtrip(&[7u8; 32])?;
4744        let now = SystemTime::UNIX_EPOCH
4745            .checked_add(std::time::Duration::new(1_700_000_000, 500_000))
4746            .unwrap();
4747        assert_dc_roundtrip(&now)?;
4748        Ok(())
4749    }
4750
4751    #[crate::ctb_test]
4752    fn test_derive_struct_roundtrip() -> Result<()> {
4753        let record = SampleFileRecord {
4754            inode: 1234567,
4755            path: "docs/readme.txt".into(),
4756            is_directory: false,
4757            optional_size: Some(1024),
4758        };
4759        assert_dc_roundtrip(&record)?;
4760
4761        let empty_size_record = SampleFileRecord {
4762            inode: 7654321,
4763            path: "empty_dir".into(),
4764            is_directory: true,
4765            optional_size: None,
4766        };
4767        assert_dc_roundtrip(&empty_size_record)?;
4768        Ok(())
4769    }
4770
4771    #[crate::ctb_test]
4772    fn test_tagged_optional_field_markers() -> Result<()> {
4773        let strict = DcProjectionPolicy::strict();
4774        for optional_size in [None, Some(1024)] {
4775            let mut record = sample_source_record(42);
4776            record.optional_size = optional_size;
4777            let mut expected = DcMstring::new();
4778            expected.push_char(DcChar::from_short(336));
4779            optional_size.encode_dc_mixed(&mut expected)?;
4780
4781            let mut field = DcMstring::new();
4782            record.encode_dc_field("optional_size", &mut field)?;
4783            assert_eq!(field, expected);
4784            assert_dc_roundtrip(&record)?;
4785
4786            let source = sample_source_record(42).to_dc_mixed()?;
4787            let revised = source
4788                .inspect::<SampleFileRecord>()
4789                .replace_field("optional_size", &record)?;
4790            assert_eq!(revised.decode::<SampleFileRecord>(&strict)?, record);
4791        }
4792
4793        #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4794        #[dc(begin = 317, end = 318)]
4795        struct NestedOptionalRecord {
4796            #[dc(short = 336)]
4797            value: Option<Option<u64>>,
4798        }
4799
4800        for value in [None, Some(None), Some(Some(42))] {
4801            let record = NestedOptionalRecord { value };
4802            let mut expected = DcMstring::new();
4803            expected.push_char(DcChar::from_short(317));
4804            expected.push_char(DcChar::from_short(336));
4805            value.encode_dc_mixed(&mut expected)?;
4806            expected.push_char(DcChar::from_short(318));
4807            assert_eq!(record.to_dc_mixed()?, expected);
4808            assert_eq!(
4809                expected.decode::<NestedOptionalRecord>(&strict)?,
4810                record
4811            );
4812        }
4813        Ok(())
4814    }
4815
4816    #[crate::ctb_test]
4817    fn test_derive_enum_roundtrip() -> Result<()> {
4818        assert_dc_roundtrip(&SampleKind::Regular)?;
4819        assert_dc_roundtrip(&SampleKind::Directory)?;
4820        Ok(())
4821    }
4822
4823    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4824    #[dc(begin = 401, end = 402)]
4825    struct SampleShorthandStruct {
4826        #[dc(336)]
4827        short_num: u32,
4828        #[dc(f315)]
4829        format_str: String,
4830        #[dc(u01a3)]
4831        unicode_val: i32,
4832        #[dc(l1000)]
4833        long_val: u64,
4834        #[dc(348)]
4835        nested_vals: Option<Vec<String>>,
4836    }
4837
4838    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
4839    #[dc(begin = 317, end = 318)]
4840    enum SampleShorthandEnum {
4841        #[dc(f315)]
4842        AppleSingle,
4843        #[dc(f316)]
4844        AppleDouble,
4845        #[dc(405)]
4846        FinderLabel(u8),
4847    }
4848
4849    #[crate::ctb_test]
4850    fn test_shorthand_syntax_roundtrip() -> Result<()> {
4851        let sample = SampleShorthandStruct {
4852            short_num: 42,
4853            format_str: "format_f315".to_string(),
4854            unicode_val: -99,
4855            long_val: 123456789,
4856            nested_vals: Some(vec!["alpha".to_string(), "beta".to_string()]),
4857        };
4858        assert_dc_roundtrip(&sample)?;
4859
4860        assert_dc_roundtrip(&SampleShorthandEnum::AppleSingle)?;
4861        assert_dc_roundtrip(&SampleShorthandEnum::AppleDouble)?;
4862        assert_dc_roundtrip(&SampleShorthandEnum::FinderLabel(7))?;
4863        Ok(())
4864    }
4865
4866    #[crate::ctb_test]
4867    fn test_ip_addr_roundtrip() -> Result<()> {
4868        let strict = DcProjectionPolicy::strict();
4869        let v4: std::net::Ipv4Addr = "192.168.1.1".parse().unwrap();
4870        assert_dc_roundtrip(&v4)?;
4871
4872        let v6: std::net::Ipv6Addr = "2001:db8::ff00:42:8329".parse().unwrap();
4873        assert_dc_roundtrip(&v6)?;
4874
4875        let ip_v4: std::net::IpAddr = std::net::IpAddr::V4(v4);
4876        assert_dc_roundtrip(&ip_v4)?;
4877
4878        let ip_v6: std::net::IpAddr = std::net::IpAddr::V6(v6);
4879        assert_dc_roundtrip(&ip_v6)?;
4880
4881        // Ensure IPv4 and IPv6 representations cannot be confused or cross-decoded:
4882        let mut v4_mst = DcMstring::new();
4883        v4.encode_dc_mixed(&mut v4_mst)?;
4884        v4_mst.decode::<std::net::Ipv6Addr>(&strict).unwrap_err();
4885
4886        let mut v6_mst = DcMstring::new();
4887        v6.encode_dc_mixed(&mut v6_mst)?;
4888        v6_mst.decode::<std::net::Ipv4Addr>(&strict).unwrap_err();
4889
4890        let decoded_v4_ip = v4_mst.decode::<std::net::IpAddr>(&strict)?;
4891        assert_eq!(decoded_v4_ip, ip_v4);
4892
4893        let decoded_v6_ip = v6_mst.decode::<std::net::IpAddr>(&strict)?;
4894        assert_eq!(decoded_v6_ip, ip_v6);
4895        Ok(())
4896    }
4897
4898    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, DcMixed)]
4899    #[dc(begin = 388, end = 389, flags)]
4900    struct SampleFlags {
4901        #[dc(499)]
4902        flag_a: bool,
4903        #[dc(500)]
4904        flag_b: bool,
4905        #[dc(501)]
4906        flag_c: bool,
4907    }
4908
4909    impl SampleFlags {
4910        fn to_u8(&self) -> u8 {
4911            let mut v = 0u8;
4912            if self.flag_a {
4913                v |= 1;
4914            }
4915            if self.flag_b {
4916                v |= 2;
4917            }
4918            if self.flag_c {
4919                v |= 4;
4920            }
4921            v
4922        }
4923        fn from_u8(v: u8) -> Self {
4924            Self {
4925                flag_a: (v & 1) != 0,
4926                flag_b: (v & 2) != 0,
4927                flag_c: (v & 4) != 0,
4928            }
4929        }
4930    }
4931
4932    impl DcMixedNumber for SampleFlags {
4933        fn encode_dc_number(
4934            &self,
4935            mst: &mut crate::DcWriter<'_>,
4936        ) -> Result<()> {
4937            self.to_u8().encode_dc_mixed_to(mst)
4938        }
4939        fn decode_dc_number(
4940            ctx: &mut DcProjectionContext<'_, '_>,
4941            node_id: NodeId,
4942        ) -> Result<Self> {
4943            let v = u8::decode_dc_node(ctx, node_id)?;
4944            Ok(Self::from_u8(v))
4945        }
4946    }
4947
4948    #[crate::ctb_test]
4949    fn test_flag_lists_strict_roundtrip() -> Result<()> {
4950        for mask in 0..=7 {
4951            let flags = SampleFlags::from_u8(mask);
4952            assert_dc_document_roundtrip(&flags)?;
4953            let expected = if mask == 0 {
4954                vec![388, 389]
4955            } else {
4956                let mut exp = vec![388, 310, 275];
4957                for (enabled, tag) in [
4958                    (flags.flag_a, 499),
4959                    (flags.flag_b, 500),
4960                    (flags.flag_c, 501),
4961                ] {
4962                    if enabled {
4963                        if exp.len() > 3 {
4964                            exp.push(312);
4965                        }
4966                        exp.push(tag);
4967                    }
4968                }
4969                exp.extend([311, 389]);
4970                exp
4971            };
4972            let expected = expected
4973                .into_iter()
4974                .map(|id| DcChar::from_short(id).to_u128())
4975                .collect::<Vec<_>>();
4976            ensure!(flags.to_dc_mixed()?.to_dc_tokens()? == expected);
4977        }
4978        Ok(())
4979    }
4980
4981    #[crate::ctb_test]
4982    fn test_flag_lists_reject_malformed_framing() -> Result<()> {
4983        let strict = DcProjectionPolicy::strict();
4984        for tokens in [
4985            vec![388, 499, 389],
4986            vec![388, 499, 500, 389],
4987            vec![388, 310, 499, 311, 389],
4988            vec![388, 310, 275, 499, 500, 311, 389],
4989            vec![388, 310, 275, 499, 312, 311, 389],
4990            vec![388, 310, 275, 403, 311, 389],
4991            vec![388, 310, 275, 499, 389],
4992            vec![388, 310, 275, 499, 311],
4993            vec![388, 310, 275, 499],
4994        ] {
4995            let mut mst = DcMstring::new();
4996            for token in tokens {
4997                mst.push_char(DcChar::from_short(token));
4998            }
4999            ensure!(mst.decode::<SampleFlags>(&strict).is_err());
5000        }
5001
5002        // Verify empty flag list representations decode to default in strict mode
5003        for empty_tokens in [vec![388, 389], vec![388, 310, 275, 311, 389]] {
5004            let mut mst = DcMstring::new();
5005            for token in empty_tokens {
5006                mst.push_char(DcChar::from_short(token));
5007            }
5008            let decoded: SampleFlags = mst.decode(&strict)?;
5009            ensure!(!decoded.flag_a && !decoded.flag_b && !decoded.flag_c);
5010        }
5011
5012        Ok(())
5013    }
5014
5015    #[derive(Debug, Clone, PartialEq, Eq, Default, DcMixed)]
5016    #[dc(begin = 401, end = 402)]
5017    struct SampleEquivalentParent {
5018        #[dc(406, equivalents = (388, number), default, omit_default)]
5019        flags: SampleFlags,
5020        #[dc(400, default, omit_default)]
5021        name: String,
5022    }
5023
5024    #[crate::ctb_test]
5025    fn test_equivalent_representations_roundtrip() -> Result<()> {
5026        let strict = DcProjectionPolicy::strict();
5027        let parent = SampleEquivalentParent {
5028            flags: SampleFlags {
5029                flag_a: true,
5030                flag_b: false,
5031                flag_c: true,
5032            },
5033            name: "test_eq".to_string(),
5034        };
5035        assert_dc_roundtrip(&parent)?;
5036        let tokens = parent.to_dc_mixed()?.to_dc_tokens()?;
5037        let prefix = [401, 406, 397, 310, 275, 388]
5038            .map(|id| DcChar::from_short(id).to_u128());
5039        ensure!(tokens.get(..prefix.len()) == Some(prefix.as_slice()));
5040
5041        // Also test decoding from semantic-only stream (no 397)
5042        let mut mst = DcMstring::new();
5043        mst.push_char(DcChar::from_short(401));
5044        mst.push_char(DcChar::from_short(406));
5045        mst.push_char(DcChar::from_short(388));
5046        mst.push_char(DC_BEGIN_LIST);
5047        mst.push_char(DcChar::from_short(275));
5048        mst.push_char(DcChar::from_short(499));
5049        mst.push_char(DC_END_LIST);
5050        mst.push_char(DcChar::from_short(389));
5051        mst.push_char(DcChar::from_short(402));
5052
5053        let decoded = mst.decode::<SampleEquivalentParent>(&strict)?;
5054        ensure!(decoded.flags.flag_a);
5055        ensure!(!decoded.flags.flag_b);
5056        ensure!(!decoded.flags.flag_c);
5057
5058        // Test simplified empty flags decoding: 406 388 389
5059        let mut mst_empty = DcMstring::new();
5060        mst_empty.push_char(DcChar::from_short(401));
5061        mst_empty.push_char(DcChar::from_short(406));
5062        mst_empty.push_char(DcChar::from_short(388));
5063        mst_empty.push_char(DcChar::from_short(389));
5064        mst_empty.push_char(DcChar::from_short(402));
5065
5066        let decoded_empty =
5067            mst_empty.decode::<SampleEquivalentParent>(&strict)?;
5068        ensure!(!decoded_empty.flags.flag_a);
5069        ensure!(!decoded_empty.flags.flag_b);
5070        ensure!(!decoded_empty.flags.flag_c);
5071
5072        Ok(())
5073    }
5074
5075    #[crate::ctb_test]
5076    fn test_array_list_serialization_roundtrip() -> Result<()> {
5077        let arr_32 = [42u8; 32];
5078        assert_dc_roundtrip(&arr_32)?;
5079
5080        let arr_4 = [100u32, 200, 300, 400];
5081        assert_dc_roundtrip(&arr_4)?;
5082
5083        // Verify that arr_32 serializes as numbers, not as binary encapsulation
5084        let mut mst = DcMstring::new();
5085        arr_32.encode_dc_mixed(&mut mst)?;
5086        ensure!(!mst.as_bytes().contains(&203));
5087        Ok(())
5088    }
5089
5090    #[derive(Debug, Clone, PartialEq, Eq, Default, DcMixed)]
5091    #[dc(begin = 317, end = 318)]
5092    struct SampleBinaryStruct {
5093        #[dc(392, binary)]
5094        digest: [u8; 32],
5095        #[dc(385, binary)]
5096        payload: Vec<u8>,
5097        #[dc(539, binary)]
5098        opt_digest: Option<[u8; 32]>,
5099        #[dc(338, binary)]
5100        wrapped: BinaryPayload,
5101    }
5102
5103    #[derive(Debug, PartialEq, Eq, DcMixed)]
5104    #[dc(begin = 401, end = 402)]
5105    struct SampleFormatFields {
5106        #[dc(496, representation = f228)]
5107        name: String,
5108        #[dc(510, representation = f524, default, omit_default)]
5109        bounds: Option<[i16; 4]>,
5110    }
5111
5112    #[crate::ctb_test]
5113    fn test_format_field_representation_boundaries() -> Result<()> {
5114        let strict = DcProjectionPolicy::strict();
5115        for bounds in [None, Some([-10, 20, 30, 40])] {
5116            let value = SampleFormatFields {
5117                name: "name".to_owned(),
5118                bounds,
5119            };
5120            crate::assert_dc_document_roundtrip(&value)?;
5121            let encoded = value.to_dc_mixed()?;
5122            let decoded = encoded.decode::<SampleFormatFields>(&strict)?;
5123            ensure!(decoded == value);
5124            if let Some(expected_bounds) = bounds {
5125                let mut arena = DcSyntaxArena::new();
5126                let root = DcDocumentNavigator::parse_arena(
5127                    encoded.as_bytes(),
5128                    &mut arena,
5129                    &strict,
5130                )?;
5131                let mut ctx = DcProjectionContext::new(&arena, &strict);
5132                let container =
5133                    arena.node(root).context("Root node missing")?;
5134                let mut found_bounds = false;
5135                if let DcSyntaxKind::Container { children, .. } =
5136                    &container.kind
5137                {
5138                    for &child_id in children {
5139                        let child_node = arena
5140                            .node(child_id)
5141                            .context("Child node missing")?;
5142                        if let DcSyntaxKind::Tagged { tag, args } =
5143                            &child_node.kind
5144                        {
5145                            if ctx.canonical_token(*tag)
5146                                == ctx.canonical_token(DcChar::from_short(510))
5147                            {
5148                                if let Some(&arg_id) = args.first() {
5149                                    let dec_bounds = decode_format_representation::<[i16; 4]>(
5150                                        &mut ctx,
5151                                        arg_id,
5152                                        DcChar::from_u128(FormatId::QuickDrawRect.dc_id()
5153                                            .context("Missing rectangle format identifier")?),
5154                                    )?;
5155                                    ensure!(dec_bounds == expected_bounds);
5156                                    found_bounds = true;
5157                                }
5158                            }
5159                        }
5160                    }
5161                }
5162                ensure!(found_bounds);
5163            }
5164        }
5165        let format = DcChar::from_u128(
5166            FormatId::FileName
5167                .dc_id()
5168                .context("Missing filename format identifier")?,
5169        );
5170        for closing in [None, Some(DC_END_LIST)] {
5171            let mut malformed = DcMstring::new();
5172            malformed.push_char(DC_BEGIN_FORMAT_REPRESENTATION);
5173            malformed.push_char(format);
5174            "name".encode_dc_mixed(&mut malformed)?;
5175            if let Some(closing) = closing {
5176                malformed.push_char(closing);
5177            }
5178            let mut arena = DcSyntaxArena::new();
5179            let parsed = DcDocumentNavigator::parse_arena(
5180                malformed.as_bytes(),
5181                &mut arena,
5182                &strict,
5183            );
5184            let result = parsed.and_then(|root_id| {
5185                let mut ctx = DcProjectionContext::new(&arena, &strict);
5186                decode_format_representation::<String>(
5187                    &mut ctx, root_id, format,
5188                )
5189            });
5190            ensure!(result.is_err(), "Malformed format boundary was accepted");
5191        }
5192        Ok(())
5193    }
5194
5195    #[derive(Debug, PartialEq, Eq, DcMixed)]
5196    #[dc(begin = 401, end = 402)]
5197    struct SampleFinderCodes {
5198        #[dc(403, binary)]
5199        file_type: Vec<u8>,
5200        #[dc(404, binary)]
5201        creator: Vec<u8>,
5202    }
5203
5204    #[crate::ctb_test]
5205    fn test_finder_binary_codes_require_four_payload_bytes() -> Result<()> {
5206        for length in [0, 3, 4, 5, 8] {
5207            let codes = SampleFinderCodes {
5208                file_type: vec![0xff; length],
5209                creator: vec![0; length],
5210            };
5211            let validation = crate::assert_dc_document_roundtrip(&codes);
5212            ensure!(
5213                validation.is_ok() == (length == 4),
5214                "Unexpected Finder code validation for byte length {length}: {validation:?}"
5215            );
5216        }
5217        Ok(())
5218    }
5219
5220    #[crate::ctb_test]
5221    fn test_binary_annotated_struct_roundtrip() -> Result<()> {
5222        let s = SampleBinaryStruct {
5223            digest: [7u8; 32],
5224            payload: vec![1, 2, 3, 4, 5],
5225            opt_digest: Some([9u8; 32]),
5226            wrapped: BinaryPayload::new(vec![0xAA, 0xBB]),
5227        };
5228        assert_dc_roundtrip(&s)?;
5229
5230        let s_none = SampleBinaryStruct {
5231            digest: [0u8; 32],
5232            payload: Vec::new(),
5233            opt_digest: None,
5234            wrapped: BinaryPayload::default(),
5235        };
5236        assert_dc_roundtrip(&s_none)?;
5237        Ok(())
5238    }
5239
5240    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
5241    #[dc(begin = 317, end = 318)]
5242    enum SampleBinaryEnum {
5243        #[dc(412, binary)]
5244        Hash([u8; 32]),
5245        #[dc(413, binary)]
5246        Blob(Vec<u8>),
5247    }
5248
5249    #[crate::ctb_test]
5250    fn test_binary_annotated_enum_roundtrip() -> Result<()> {
5251        let e1 = SampleBinaryEnum::Hash([0x55; 32]);
5252        assert_dc_roundtrip(&e1)?;
5253
5254        let e2 = SampleBinaryEnum::Blob(vec![10, 20, 30]);
5255        assert_dc_roundtrip(&e2)?;
5256        Ok(())
5257    }
5258
5259    #[crate::ctb_test]
5260    fn test_binary_fields_do_not_require_a_typed_decoder() -> Result<()> {
5261        let strict = DcProjectionPolicy::strict();
5262        #[derive(Debug, PartialEq)]
5263        struct RawBytes(Vec<u8>);
5264
5265        impl crate::DcForgivingDefault for RawBytes {
5266            fn dc_forgiving_default() -> Self {
5267                Self(Vec::new())
5268            }
5269        }
5270
5271        impl AsRef<[u8]> for RawBytes {
5272            fn as_ref(&self) -> &[u8] {
5273                &self.0
5274            }
5275        }
5276
5277        impl TryFrom<&[u8]> for RawBytes {
5278            type Error = anyhow::Error;
5279
5280            fn try_from(bytes: &[u8]) -> Result<Self> {
5281                Ok(Self(bytes.to_vec()))
5282            }
5283        }
5284
5285        #[derive(Debug, PartialEq, DcMixed)]
5286        #[dc(begin = 317, end = 318)]
5287        struct BinaryFields {
5288            #[dc(385, binary)]
5289            payload: RawBytes,
5290            #[dc(539, binary)]
5291            flags: Option<RawBytes>,
5292        }
5293
5294        let value = BinaryFields {
5295            payload: RawBytes(vec![0, 128, 255]),
5296            flags: Some(RawBytes(u64::MAX.to_le_bytes().to_vec())),
5297        };
5298        assert_dc_roundtrip(&value)?;
5299
5300        let mut invalid_list = DcMstring::new();
5301        invalid_list.push_char(DcChar::from_short(317));
5302        invalid_list.push_char(DcChar::from_short(385));
5303        value.payload.0.encode_dc_mixed(&mut invalid_list)?;
5304        invalid_list.push_char(DcChar::from_short(318));
5305        ensure!(
5306            invalid_list.decode::<BinaryFields>(&strict).is_err(),
5307            "Byte lists must not be accepted for binary fields under strict policy"
5308        );
5309        Ok(())
5310    }
5311
5312    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
5313    #[dc(begin = 317, end = 318)]
5314    struct SampleRepeatedVecStruct {
5315        #[dc(346)]
5316        ips: Vec<std::net::IpAddr>,
5317        #[dc(519)]
5318        offsets: Vec<i64>,
5319    }
5320
5321    #[crate::ctb_test]
5322    fn test_repeated_tagged_vec_roundtrip() -> Result<()> {
5323        let v4: std::net::Ipv4Addr = "192.168.1.1".parse()?;
5324        let v6: std::net::Ipv6Addr = "fe80::1".parse()?;
5325        let s = SampleRepeatedVecStruct {
5326            ips: vec![std::net::IpAddr::V4(v4), std::net::IpAddr::V6(v6)],
5327            offsets: vec![-100, 200],
5328        };
5329        assert_dc_roundtrip(&s)?;
5330
5331        let empty = SampleRepeatedVecStruct {
5332            ips: Vec::new(),
5333            offsets: Vec::new(),
5334        };
5335        ensure!(empty.to_dc_mixed()?.decode::<SampleRepeatedVecStruct>(&DcProjectionPolicy::strict()).is_err());
5336        Ok(())
5337    }
5338
5339    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
5340    #[dc(begin = 317, end = 318)]
5341    struct SampleFlattenedFormatsStruct {
5342        #[dc(342)]
5343        name: String,
5344        #[dc(flatten)]
5345        formats: Vec<ctb_formats_utilities::FormatId>,
5346    }
5347
5348    #[crate::ctb_test]
5349    fn test_flattened_formats_roundtrip() -> Result<()> {
5350        let s = SampleFlattenedFormatsStruct {
5351            name: "test_env".to_string(),
5352            formats: vec![
5353                ctb_formats_utilities::FormatId::PwaMobile,
5354                ctb_formats_utilities::FormatId::Linux,
5355                ctb_formats_utilities::FormatId::GnuLinux,
5356            ],
5357        };
5358        assert_dc_roundtrip(&s)?;
5359
5360        let empty = SampleFlattenedFormatsStruct {
5361            name: "empty_formats".to_string(),
5362            formats: Vec::new(),
5363        };
5364        assert_dc_roundtrip(&empty)?;
5365        Ok(())
5366    }
5367
5368    #[crate::ctb_test]
5369    fn test_malachite_natural_and_integer_dc_roundtrip() -> Result<()> {
5370        use malachite::{Integer, Natural};
5371
5372        let small_nat = Natural::from(42_u64);
5373        assert_dc_roundtrip(&small_nat)?;
5374
5375        let u64_max_nat = Natural::from(u64::MAX);
5376        assert_dc_roundtrip(&u64_max_nat)?;
5377
5378        let u128_nat = Natural::from(u128::MAX);
5379        assert_dc_roundtrip(&u128_nat)?;
5380
5381        let large_nat = Natural::from(u128::MAX) * Natural::from(u128::MAX);
5382        assert_dc_roundtrip(&large_nat)?;
5383
5384        let pos_int = Integer::from(123_456_789_i64);
5385        assert_dc_roundtrip(&pos_int)?;
5386
5387        let neg_int = Integer::from(-987_654_321_i64);
5388        assert_dc_roundtrip(&neg_int)?;
5389
5390        let large_neg_int = -Integer::from(u128::MAX);
5391        assert_dc_roundtrip(&large_neg_int)?;
5392
5393        Ok(())
5394    }
5395
5396    #[derive(Debug, Clone, PartialEq, Eq, DcMixed)]
5397    #[dc(begin = 317, end = 318)]
5398    struct ChecksumRecord {
5399        #[dc(short = 368, checksum)]
5400        sha256: [u8; 32],
5401    }
5402
5403    #[crate::ctb_test]
5404    fn test_checksum_field_and_payload_roundtrip() -> Result<()> {
5405        let strict = DcProjectionPolicy::strict();
5406        let digest = [7u8; 32];
5407        let record = ChecksumRecord { sha256: digest };
5408        let mst = record.to_dc_mixed()?;
5409        let decoded_mst = mst.decode::<ChecksumRecord>(&strict)?;
5410        assert_eq!(decoded_mst, record);
5411
5412        let dc_str = record.to_dc_string()?;
5413        let decoded_str = dc_str.decode::<ChecksumRecord>(&strict)?;
5414        assert_eq!(decoded_str, record);
5415
5416        // Test push_checksum and arena node inspection directly
5417        let mut manual_mst = DcMstring::new();
5418        manual_mst
5419            .push_checksum(ctb_utilities::format_id::DC_SHA256, &digest)?;
5420        let mut arena = DcSyntaxArena::new();
5421        let root = DcDocumentNavigator::parse_arena(
5422            manual_mst.as_bytes(),
5423            &mut arena,
5424            &strict,
5425        )?;
5426        let node = arena.node(root).context("Root node missing")?;
5427        match &node.kind {
5428            DcSyntaxKind::Binary {
5429                checksum_format,
5430                payload,
5431                ..
5432            } => {
5433                assert_eq!(
5434                    *checksum_format,
5435                    Some(ctb_utilities::format_id::DC_SHA256)
5436                );
5437                assert_eq!(payload.materialize_bytes()?.as_ref(), &digest);
5438            }
5439            other => bail!("Expected Binary checksum node, got {other:?}"),
5440        }
5441
5442        Ok(())
5443    }
5444
5445    #[crate::ctb_test]
5446    fn test_pathbuf_syntax_validation() -> Result<()> {
5447        let p = std::path::PathBuf::from("/tmp/src");
5448        let mut mst = DcMstring::new();
5449        p.encode_dc_mixed(&mut mst)?;
5450        crate::validate_dc_mixed_strict(&mst)?;
5451        Ok(())
5452    }
5453
5454    #[crate::ctb_test]
5455    fn test_vec_dc_mixed_roundtrip_with_separator() -> Result<()> {
5456        let strict = DcProjectionPolicy::strict();
5457        let items = vec![10u32, 20u32, 30u32];
5458        let mut mst = DcMstring::new();
5459        items.encode_dc_mixed(&mut mst)?;
5460
5461        // Verify tokens: DC_BEGIN_LIST, 275, 10, DC_LIST_ELEMENT_SEPARATOR, 20, DC_LIST_ELEMENT_SEPARATOR, 30, DC_END_LIST
5462        crate::validate_dc_mixed_strict(&mst)?;
5463
5464        let decoded = mst.decode::<Vec<u32>>(&strict)?;
5465        assert_eq!(decoded, items);
5466        Ok(())
5467    }
5468
5469    #[crate::ctb_test]
5470    fn test_vec_optional_length_header() -> Result<()> {
5471        let strict = DcProjectionPolicy::strict();
5472        let forgiving = DcProjectionPolicy::forgiving();
5473        let mut mst = DcMstring::new();
5474        mst.push_char(DC_BEGIN_LIST);
5475        2usize.encode_dc_mixed(&mut mst)?;
5476        mst.push_char(DcChar::from_short(275));
5477        10u32.encode_dc_mixed(&mut mst)?;
5478        mst.push_char(DC_LIST_ELEMENT_SEPARATOR);
5479        20u32.encode_dc_mixed(&mut mst)?;
5480        mst.push_char(DC_END_LIST);
5481
5482        assert_eq!(mst.decode::<Vec<u32>>(&strict)?, vec![10, 20]);
5483
5484        // Mismatched length header errors in strict mode, succeeds in forgiving mode
5485        let mut mismatch = DcMstring::new();
5486        mismatch.push_char(DC_BEGIN_LIST);
5487        5usize.encode_dc_mixed(&mut mismatch)?;
5488        mismatch.push_char(DcChar::from_short(275));
5489        10u32.encode_dc_mixed(&mut mismatch)?;
5490        mismatch.push_char(DC_END_LIST);
5491        mismatch.decode::<Vec<u32>>(&strict).unwrap_err();
5492        assert_eq!(mismatch.decode::<Vec<u32>>(&forgiving)?, vec![10]);
5493        Ok(())
5494    }
5495
5496    #[crate::ctb_test]
5497    fn test_literal_string_escape_255_roundtrip() -> Result<()> {
5498        let strict = DcProjectionPolicy::strict();
5499        let mut mst = DcMstring::new();
5500        mst.push_char(DcChar::from_short(260));
5501        mst.push_char(DcChar::from_short(262));
5502        mst.push_char(DcChar::from_short(264));
5503        mst.push_char(DcChar::from_short(263));
5504        mst.push_char(DcChar::from_char('A'));
5505        mst.push_char(DcChar::from_short(255));
5506        mst.push_char(DcChar::from_char('B'));
5507        mst.push_char(DcChar::from_short(261));
5508        assert_eq!(mst.decode::<String>(&strict)?, "AB");
5509        Ok(())
5510    }
5511
5512    #[crate::ctb_test]
5513    fn test_forgiving_struct_projection_policy() -> Result<()> {
5514        let strict = DcProjectionPolicy::strict();
5515        let forgiving = DcProjectionPolicy::forgiving();
5516
5517        // 1. Unknown field tag (Dc 600 + binary payload) inside SampleFileRecord
5518        let mut with_unknown = DcMstring::new();
5519        let original = sample_source_record(42);
5520        with_unknown.push_char(DcChar::from_short(317));
5521        original.encode_dc_field("inode", &mut with_unknown)?;
5522        with_unknown.push_char(DcChar::from_short(600));
5523        with_unknown.push_binary_with_sha256(b"future field")?;
5524        original.encode_dc_field("path", &mut with_unknown)?;
5525        original.encode_dc_field("is_directory", &mut with_unknown)?;
5526        original.encode_dc_field("optional_size", &mut with_unknown)?;
5527        with_unknown.push_char(DcChar::from_short(318));
5528
5529        with_unknown
5530            .decode::<SampleFileRecord>(&strict)
5531            .unwrap_err();
5532        assert_eq!(
5533            with_unknown.decode::<SampleFileRecord>(&forgiving)?,
5534            original
5535        );
5536
5537        // 2. Malformed field value for `inode` (string instead of number) + missing `is_directory`
5538        let mut malformed = DcMstring::new();
5539        malformed.push_char(DcChar::from_short(317));
5540        malformed.push_char(DcChar::from_short(327));
5541        "not_a_number".encode_dc_mixed(&mut malformed)?;
5542        original.encode_dc_field("path", &mut malformed)?;
5543        malformed.push_char(DcChar::from_short(318));
5544
5545        malformed.decode::<SampleFileRecord>(&strict).unwrap_err();
5546        let recovered = malformed.decode::<SampleFileRecord>(&forgiving)?;
5547        assert_eq!(recovered.inode, 0);
5548        assert_eq!(recovered.path, std::path::Path::new("path"));
5549        assert!(!recovered.is_directory);
5550        assert_eq!(recovered.optional_size, None);
5551        Ok(())
5552    }
5553
5554    #[crate::ctb_test]
5555    fn test_seekable_file_large_binary_payload_decode() -> Result<()> {
5556        use std::io::Write as _;
5557        let strict = DcProjectionPolicy::strict();
5558        let large_bytes: Vec<u8> = (0..(crate::INLINE_BINARY_THRESHOLD + 1024))
5559            .map(|i| u8::try_from(i % 251).unwrap())
5560            .collect();
5561        let original = (
5562            "streamed_large_blob".to_owned(),
5563            BinaryPayload::new(large_bytes),
5564        );
5565        let mst = original.to_dc_mixed()?;
5566        let mut file = tempfile::tempfile()?;
5567        file.write_all(mst.as_bytes())?;
5568        let mut nav = DcDocumentNavigator::from_dcmm_file(file, 0)?;
5569        let mut arena = DcSyntaxArena::new();
5570        let stub = nav
5571            .next_sibling_stub(&strict)?
5572            .context("Expected root frame stub")?;
5573        let decoded: (String, BinaryPayload) =
5574            nav.decode_frame_with_arena(&stub, &mut arena, None, &strict)?;
5575        assert_eq!(decoded, original);
5576        Ok(())
5577    }
5578
5579    #[crate::ctb_test]
5580    fn test_pre_1970_system_time_roundtrip() -> Result<()> {
5581        let strict = DcProjectionPolicy::strict();
5582        let pre_epoch = std::time::UNIX_EPOCH
5583            .checked_sub(Duration::from_secs(86_400))
5584            .context("Failed to construct pre-1970 SystemTime")?;
5585        assert_dc_roundtrip(&pre_epoch)?;
5586        assert_dc_document_roundtrip(&pre_epoch)?;
5587
5588        // Also test pre-1970 with sub-second nanoseconds
5589        let pre_epoch_nanos = std::time::UNIX_EPOCH
5590            .checked_sub(Duration::new(86_400, 123_456_789))
5591            .context("Failed to construct pre-1970 SystemTime with nanos")?;
5592        assert_dc_roundtrip(&pre_epoch_nanos)?;
5593
5594        // Also test SecondsSinceEpoch (f486) with negative seconds
5595        let mut mst = DcMstring::new();
5596        mst.push_char(DC_BEGIN_TIME_MOMENT);
5597        mst.push_char(format_dc_char(FormatId::SecondsSinceEpoch)?);
5598        (-86_400_i64).encode_dc_mixed(&mut mst)?;
5599        mst.push_char(DC_END_TIME_MOMENT);
5600        assert_eq!(mst.decode::<SystemTime>(&strict)?, pre_epoch);
5601        Ok(())
5602    }
5603
5604    #[crate::ctb_test]
5605    fn test_tuple_and_vec_transparent_and_format_unwrapping() -> Result<()> {
5606        let strict = DcProjectionPolicy::strict();
5607        let pair = (-12_i16, 42_i16);
5608        assert_dc_roundtrip(&pair)?;
5609        assert_dc_document_roundtrip(&pair)?;
5610
5611        // Wrap pair in DC_EQUIVALENT_REPRESENTATIONS (397) and DC_BEGIN_FORMAT_REPRESENTATION (511)
5612        let fmt = format_dc_char(FormatId::QuickDrawPoint)?;
5613        let mut wrapped_pair = DcMstring::new();
5614        wrapped_pair.push_char(DC_EQUIVALENT_REPRESENTATIONS);
5615        wrapped_pair.push_char(DC_BEGIN_LIST);
5616        wrapped_pair.push_char(DC_TYPE_ANY);
5617        encode_format_representation(
5618            &[-12_i16, 42_i16],
5619            fmt,
5620            &mut wrapped_pair,
5621            &SharedValueContext::default(),
5622        )?;
5623        wrapped_pair.push_char(DC_END_LIST);
5624        assert_eq!(wrapped_pair.decode::<(i16, i16)>(&strict)?, pair);
5625
5626        // Wrap a typed list in equivalent and optional representations.
5627        let list = vec![10_i16, 20];
5628        let mut wrapped_vec = DcMstring::new();
5629        wrapped_vec.push_char(DC_EQUIVALENT_REPRESENTATIONS);
5630        wrapped_vec.push_char(DC_BEGIN_LIST);
5631        wrapped_vec.push_char(DC_TYPE_ANY);
5632        wrapped_vec.push_char(DC_OPTIONAL_PRESENT);
5633        list.encode_dc_mixed(&mut wrapped_vec)?;
5634        wrapped_vec.push_char(DC_END_LIST);
5635        assert_eq!(wrapped_vec.decode::<Vec<i16>>(&strict)?, list);
5636        Ok(())
5637    }
5638
5639    #[crate::ctb_test]
5640    fn test_deeply_nested_containers_respect_max_depth() -> Result<()> {
5641        let depth = 12usize;
5642        let mut nested = DcMstring::new();
5643        for _ in 0..depth {
5644            nested.push_char(DC_BEGIN_LIST);
5645            nested.push_char(DC_TYPE_ANY);
5646        }
5647        42u32.encode_dc_mixed(&mut nested)?;
5648        for _ in 0..depth {
5649            nested.push_char(DC_END_LIST);
5650        }
5651
5652        let strict_low = DcProjectionPolicy::strict()
5653            .with_max_depth(4, crate::DiagnosticAction::Error);
5654        let forgiving_low = DcProjectionPolicy::forgiving()
5655            .with_max_depth(4, crate::DiagnosticAction::Warn);
5656
5657        let mut arena_strict = DcSyntaxArena::new();
5658        assert!(
5659            DcDocumentNavigator::parse_document_arena(
5660                nested.as_bytes(),
5661                &mut arena_strict,
5662                &strict_low,
5663            )
5664            .is_err(),
5665            "Strict policy should reject nesting deeper than max_depth"
5666        );
5667
5668        let mut arena_forgiving = DcSyntaxArena::new();
5669        DcDocumentNavigator::parse_document_arena(
5670            nested.as_bytes(),
5671            &mut arena_forgiving,
5672            &forgiving_low,
5673        )?;
5674        assert!(
5675            !arena_forgiving.diagnostics().is_empty(),
5676            "Forgiving policy should record a diagnostic when max_depth is exceeded"
5677        );
5678        Ok(())
5679    }
5680
5681    #[derive(Debug, Clone, PartialEq, Eq, crate::DcMixed)]
5682    enum SampleExtent {
5683        #[dc(374)]
5684        Data {
5685            #[dc(376)]
5686            offset: u64,
5687            #[dc(377)]
5688            length: u64,
5689        },
5690        #[dc(375)]
5691        Hole {
5692            #[dc(376)]
5693            offset: u64,
5694            #[dc(377)]
5695            length: u64,
5696        },
5697    }
5698
5699    #[derive(Debug, Clone, PartialEq, Eq, crate::DcMixed)]
5700    #[dc(begin = 317, end = 318)]
5701    struct SampleExtentAndTimeRecord {
5702        #[dc(329)]
5703        modified_time: Option<SystemTime>,
5704        #[dc(begin = 372, end = 373)]
5705        extents: Vec<SampleExtent>,
5706        #[dc(348)]
5707        nested: Option<Vec<Option<BTreeMap<String, Option<u64>>>>>,
5708    }
5709
5710    #[crate::ctb_test]
5711    fn test_generic_equivalent_and_partially_equivalent_representations()
5712    -> Result<()> {
5713        let strict = DcProjectionPolicy::strict();
5714
5715        // 1. SystemTime and Duration in 397/538 prefer nanosecond resolution when coarse seconds is listed first
5716        let target_time = std::time::UNIX_EPOCH
5717            .checked_add(Duration::new(1_700_000_000, 987_654_321))
5718            .context("Failed to construct target_time")?;
5719        let mut time_eq = DcMstring::new();
5720        time_eq.push_char(DC_PARTIALLY_EQUIVALENT_REPRESENTATIONS);
5721        time_eq.push_char(DC_BEGIN_LIST);
5722        time_eq.push_char(DC_TYPE_ANY);
5723        time_eq.push_char(DC_BEGIN_TIME_MOMENT);
5724        time_eq.push_char(format_dc_char(FormatId::SecondsSinceEpoch)?);
5725        1_700_000_000_i64.encode_dc_mixed(&mut time_eq)?;
5726        time_eq.push_char(DC_END_TIME_MOMENT);
5727        time_eq.push_char(DC_LIST_ELEMENT_SEPARATOR);
5728        target_time.encode_dc_mixed(&mut time_eq)?;
5729        time_eq.push_char(DC_END_LIST);
5730        assert_eq!(time_eq.decode::<SystemTime>(&strict)?, target_time);
5731
5732        let target_dur = Duration::new(42, 123_456_789);
5733        let mut dur_eq = DcMstring::new();
5734        dur_eq.push_char(DC_PARTIALLY_EQUIVALENT_REPRESENTATIONS);
5735        dur_eq.push_char(DC_BEGIN_LIST);
5736        dur_eq.push_char(DC_TYPE_ANY);
5737        dur_eq.push_char(DC_BEGIN_DATE_MAGNITUDE);
5738        dur_eq.push_char(format_dc_char(FormatId::Second)?);
5739        42_u64.encode_dc_mixed(&mut dur_eq)?;
5740        dur_eq.push_char(DC_END_DATE_MAGNITUDE);
5741        dur_eq.push_char(DC_LIST_ELEMENT_SEPARATOR);
5742        target_dur.encode_dc_mixed(&mut dur_eq)?;
5743        dur_eq.push_char(DC_END_LIST);
5744        assert_eq!(dur_eq.decode::<Duration>(&strict)?, target_dur);
5745
5746        // 2. Bounded Vec<SampleExtent> and enum struct-variant fields wrapped in 397/538
5747        let expected_extents = vec![
5748            SampleExtent::Data {
5749                offset: 0,
5750                length: 4096,
5751            },
5752            SampleExtent::Hole {
5753                offset: 4096,
5754                length: 8192,
5755            },
5756        ];
5757        let mut expected_map = BTreeMap::new();
5758        expected_map.insert("alpha".to_owned(), Some(77_u64));
5759        let expected_nested = Some(vec![Some(expected_map.clone()), None]);
5760
5761        let mut rec_doc = DcMstring::new();
5762        rec_doc.push_char(DcChar::from_short(317));
5763        // modified_time wrapped in 397 (with an untagged label candidate first) and 561 (coarse seconds first, nanosecond second)
5764        rec_doc.push_char(DC_EQUIVALENT_REPRESENTATIONS);
5765        rec_doc.push_char(DC_BEGIN_LIST);
5766        rec_doc.push_char(DC_TYPE_ANY);
5767        "Modified: yesterday".encode_dc_mixed(&mut rec_doc)?;
5768        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5769        rec_doc.push_char(DcChar::from_short(329));
5770        rec_doc.push_char(DC_OPTIONAL_PRESENT);
5771        rec_doc.push_char(DC_PARTIALLY_EQUIVALENT_REPRESENTATIONS);
5772        rec_doc.push_char(DC_BEGIN_LIST);
5773        rec_doc.push_char(DC_TYPE_ANY);
5774        rec_doc.push_char(DC_BEGIN_TIME_MOMENT);
5775        rec_doc.push_char(format_dc_char(FormatId::SecondsSinceEpoch)?);
5776        1_700_000_000_i64.encode_dc_mixed(&mut rec_doc)?;
5777        rec_doc.push_char(DC_END_TIME_MOMENT);
5778        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5779        target_time.encode_dc_mixed(&mut rec_doc)?;
5780        rec_doc.push_char(DC_END_LIST);
5781        rec_doc.push_char(DC_END_LIST);
5782
5783        // extents (372..373) where first extent is wrapped in 397 with a non-extent candidate first,
5784        // and second extent has its variant fields wrapped in 397/561
5785        rec_doc.push_char(DcChar::from_short(372));
5786        rec_doc.push_char(DC_EQUIVALENT_REPRESENTATIONS);
5787        rec_doc.push_char(DC_BEGIN_LIST);
5788        rec_doc.push_char(DC_TYPE_ANY);
5789        "extent_0_label".encode_dc_mixed(&mut rec_doc)?;
5790        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5791        expected_extents[0].encode_dc_mixed(&mut rec_doc)?;
5792        rec_doc.push_char(DC_END_LIST);
5793
5794        rec_doc.push_char(DcChar::from_short(375));
5795        rec_doc.push_char(DcChar::from_short(376));
5796        rec_doc.push_char(DC_EQUIVALENT_REPRESENTATIONS);
5797        rec_doc.push_char(DC_BEGIN_LIST);
5798        rec_doc.push_char(DC_TYPE_ANY);
5799        "offset 4096".encode_dc_mixed(&mut rec_doc)?;
5800        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5801        4096_u64.encode_dc_mixed(&mut rec_doc)?;
5802        rec_doc.push_char(DC_END_LIST);
5803        rec_doc.push_char(DcChar::from_short(377));
5804        rec_doc.push_char(DC_PARTIALLY_EQUIVALENT_REPRESENTATIONS);
5805        rec_doc.push_char(DC_BEGIN_LIST);
5806        rec_doc.push_char(DC_TYPE_ANY);
5807        "8192 bytes".encode_dc_mixed(&mut rec_doc)?;
5808        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5809        8192_u64.encode_dc_mixed(&mut rec_doc)?;
5810        rec_doc.push_char(DC_END_LIST);
5811        rec_doc.push_char(DcChar::from_short(373));
5812
5813        // nested Option<Vec<Option<BTreeMap<String, Option<u64>>>>> with 397/561 at multiple levels
5814        rec_doc.push_char(DcChar::from_short(348));
5815        rec_doc.push_char(DC_EQUIVALENT_REPRESENTATIONS);
5816        rec_doc.push_char(DC_BEGIN_LIST);
5817        rec_doc.push_char(DC_TYPE_ANY);
5818        "summary_fallback".encode_dc_mixed(&mut rec_doc)?;
5819        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5820        rec_doc.push_char(DC_OPTIONAL_PRESENT);
5821        rec_doc.push_char(DC_PARTIALLY_EQUIVALENT_REPRESENTATIONS);
5822        rec_doc.push_char(DC_BEGIN_LIST);
5823        rec_doc.push_char(DC_TYPE_ANY);
5824        999_u64.encode_dc_mixed(&mut rec_doc)?;
5825        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5826        rec_doc.push_char(DC_BEGIN_LIST);
5827        rec_doc.push_char(DC_TYPE_ANY);
5828        rec_doc.push_char(DC_EQUIVALENT_REPRESENTATIONS);
5829        rec_doc.push_char(DC_BEGIN_LIST);
5830        rec_doc.push_char(DC_TYPE_ANY);
5831        "not_an_option".encode_dc_mixed(&mut rec_doc)?;
5832        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5833        rec_doc.push_char(DC_OPTIONAL_PRESENT);
5834        rec_doc.push_char(DC_EQUIVALENT_REPRESENTATIONS);
5835        rec_doc.push_char(DC_BEGIN_LIST);
5836        rec_doc.push_char(DC_TYPE_ANY);
5837        "not_a_map".encode_dc_mixed(&mut rec_doc)?;
5838        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5839        expected_map.encode_dc_mixed(&mut rec_doc)?;
5840        rec_doc.push_char(DC_END_LIST);
5841        rec_doc.push_char(DC_END_LIST);
5842        rec_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5843        rec_doc.push_char(DC_OPTIONAL_ABSENT);
5844        rec_doc.push_char(DC_END_LIST);
5845        rec_doc.push_char(DC_END_LIST);
5846        rec_doc.push_char(DC_END_LIST);
5847        rec_doc.push_char(DcChar::from_short(318));
5848
5849        let decoded = rec_doc.decode::<SampleExtentAndTimeRecord>(&strict)?;
5850        assert_eq!(
5851            decoded,
5852            SampleExtentAndTimeRecord {
5853                modified_time: Some(target_time),
5854                extents: expected_extents,
5855                nested: expected_nested,
5856            }
5857        );
5858        Ok(())
5859    }
5860
5861    #[crate::ctb_test]
5862    fn test_n_ary_tuple_strict_roundtrips_and_pair_compat() -> Result<()> {
5863        use super::{
5864            DC_BEGIN_KV_PAIR, DC_BEGIN_TUPLE, DC_BEGIN_TYPE_DEF, DC_END_KV_PAIR,
5865            DC_END_TUPLE, DC_END_TYPE_DEF, DC_LIST_ELEMENT_SEPARATOR,
5866            DC_TYPE_ANY, DcMixedEncode, assert_dc_document_roundtrip,
5867        };
5868        use crate::DcMstring;
5869
5870        assert_dc_document_roundtrip(&())?;
5871        assert_dc_document_roundtrip(&(42_u32,))?;
5872        assert_dc_document_roundtrip(&("alpha".to_owned(), -7_i64, true))?;
5873        assert_dc_document_roundtrip(&(
5874            1_u8,
5875            (20_u16, "nested".to_owned(), false),
5876            vec![3_u64, 4_u64],
5877            (),
5878        ))?;
5879
5880        // 2-tuples continue encoding via `Dc 514`..`Dc 515`, while decoding also accepts `Dc 2215`..`Dc 2216`.
5881        let mut pair_mstr = DcMstring::new();
5882        (10_u32, "ten".to_owned()).encode_dc_mixed(&mut pair_mstr)?;
5883        let pair_dc = pair_mstr.to_dc_string()?;
5884        assert_eq!(pair_dc.chars().next(), Some(DC_BEGIN_KV_PAIR));
5885        assert_eq!(pair_dc.chars().last(), Some(DC_END_KV_PAIR));
5886        assert_dc_document_roundtrip(&(10_u32, "ten".to_owned()))?;
5887
5888        let mut tuple2_doc = DcMstring::new();
5889        tuple2_doc.push_char(DC_BEGIN_TUPLE);
5890        2_u64.encode_dc_mixed(&mut tuple2_doc)?;
5891        for _ in 0..2 {
5892            tuple2_doc.push_char(DC_BEGIN_TYPE_DEF);
5893            tuple2_doc.push_char(DC_TYPE_ANY);
5894            tuple2_doc.push_char(DC_END_TYPE_DEF);
5895        }
5896        99_u32.encode_dc_mixed(&mut tuple2_doc)?;
5897        tuple2_doc.push_char(DC_LIST_ELEMENT_SEPARATOR);
5898        "ninety-nine".encode_dc_mixed(&mut tuple2_doc)?;
5899        tuple2_doc.push_char(DC_END_TUPLE);
5900        crate::validate_dc_mixed_strict(&tuple2_doc)?;
5901        let strict = crate::DcProjectionPolicy::strict();
5902        let decoded_pair = tuple2_doc.decode::<(u32, String)>(&strict)?;
5903        assert_eq!(decoded_pair, (99_u32, "ninety-nine".to_owned()));
5904        Ok(())
5905    }
5906}