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