1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::{
30 DcMixedDecode, DcMstr, DcMstring, DcProjectionContext, DcStr, DcString,
31 SyntaxRuleResolver,
32};
33use std::ops::Range;
34
35pub trait DcMixedFields: DcMixedDecode {
37 fn encode_dc_field(
38 &self,
39 field: &str,
40 target: &mut DcMstring,
41 ) -> Result<()> {
42 self.encode_dc_field_to(field, &mut target.writer())
43 }
44
45 fn encode_dc_map_field(
46 &self,
47 field: &str,
48 target: &mut DcMstring,
49 encoding: crate::DcKvMapEncoding,
50 ) -> Result<()> {
51 self.encode_dc_map_field_to(field, &mut target.writer(), encoding)
52 }
53
54 fn dc_field_owner() -> &'static str;
56
57 fn encode_dc_field_to(
62 &self,
63 field: &str,
64 target: &mut crate::DcWriter<'_>,
65 ) -> Result<()>;
66
67 fn encode_dc_map_field_to(
72 &self,
73 field: &str,
74 target: &mut crate::DcWriter<'_>,
75 encoding: crate::DcKvMapEncoding,
76 ) -> Result<()> {
77 let _ = (field, target, encoding);
78 bail!("Record does not support key-value field encoding")
79 }
80
81 #[must_use]
83 fn accepts_dc_tag(_tag: u128) -> bool {
84 false
85 }
86
87 fn encode_fields_with_context(
92 &self,
93 _mst: &mut crate::DcWriter<'_>,
94 _context: &crate::SharedValueContext,
95 ) -> Result<()> {
96 bail!("Record does not support flattened field encoding")
97 }
98
99 fn decode_field(
104 &mut self,
105 _tag: u128,
106 _ctx: &mut DcProjectionContext<'_, '_>,
107 _node_id: crate::NodeId,
108 ) -> Result<bool> {
109 Ok(false)
110 }
111}
112
113#[derive(Debug)]
115pub struct DcDiagnostic {
116 position: u64,
117 error: anyhow::Error,
118}
119
120impl DcDiagnostic {
121 #[must_use]
123 pub const fn position(&self) -> u64 {
124 self.position
125 }
126
127 #[must_use]
129 pub const fn error(&self) -> &anyhow::Error {
130 &self.error
131 }
132}
133
134pub trait DcSource {
136 type Owned;
138
139 fn source_bytes(&self) -> &[u8];
141
142 fn replace_typed_source_field(
147 &self,
148 range: Range<usize>,
149 fragment: &DcMstr,
150 ) -> Result<Self::Owned> {
151 self.replace_typed_source_field_with_resolver(
152 range,
153 fragment,
154 ctb_formats_dcdata::syntax::default_syntax_resolver().as_ref(),
155 )
156 }
157
158 fn replace_typed_source_field_with_resolver(
164 &self,
165 range: Range<usize>,
166 fragment: &DcMstr,
167 resolver: &dyn SyntaxRuleResolver,
168 ) -> Result<Self::Owned> {
169 self.replace_typed_source_field_with_policy_and_resolver(
170 range,
171 fragment,
172 &crate::DcProjectionPolicy::strict(),
173 resolver,
174 )
175 }
176
177 fn replace_typed_source_field_with_policy_and_resolver(
183 &self,
184 range: Range<usize>,
185 fragment: &DcMstr,
186 policy: &crate::DcProjectionPolicy,
187 resolver: &dyn SyntaxRuleResolver,
188 ) -> Result<Self::Owned>;
189
190 fn replace_source_field(
195 &self,
196 range: Range<usize>,
197 fragment: &DcMstr,
198 ) -> Result<Self::Owned>;
199}
200
201fn splice(
202 source: &[u8],
203 range: Range<usize>,
204 fragment: &[u8],
205) -> Result<Vec<u8>> {
206 ensure!(range.start <= range.end, "Reversed source range");
207 let prefix = source
208 .get(..range.start)
209 .context("Source range starts outside string")?;
210 let suffix = source
211 .get(range.end..)
212 .context("Source range ends outside string")?;
213 let mut bytes = Vec::new();
214 bytes.extend_from_slice(prefix);
215 bytes.extend_from_slice(fragment);
216 bytes.extend_from_slice(suffix);
217 Ok(bytes)
218}
219
220impl DcSource for DcMstr {
221 type Owned = DcMstring;
222
223 fn source_bytes(&self) -> &[u8] {
224 self.as_bytes()
225 }
226
227 fn replace_typed_source_field_with_policy_and_resolver(
228 &self,
229 range: Range<usize>,
230 fragment: &DcMstr,
231 policy: &crate::DcProjectionPolicy,
232 resolver: &dyn SyntaxRuleResolver,
233 ) -> Result<DcMstring> {
234 ensure!(
235 range.start >= crate::DCMM_HEADER_LEN,
236 "Cannot select string header"
237 );
238 let payload = self
239 .as_bytes()
240 .get(range.clone())
241 .context("Invalid source fragment range")?;
242 let mut bytes = DcMstring::new().into_bytes();
243 bytes.extend_from_slice(payload);
244 let original = DcMstring::from_bytes_with_policy(bytes, policy)?;
245 let replacement =
246 DcMstring::from_slice_with_policy(fragment.as_bytes(), policy)?;
247 let revised =
248 crate::source_edit::preserve_source_with_policy_and_resolver(
249 &original,
250 &replacement,
251 policy,
252 resolver,
253 )?;
254 self.replace_source_field(range, &revised)
255 }
256
257 fn replace_source_field(
258 &self,
259 range: Range<usize>,
260 fragment: &DcMstr,
261 ) -> Result<DcMstring> {
262 ensure!(
263 range.start >= crate::dc_mixed::DCMM_HEADER_LEN,
264 "Cannot replace string header"
265 );
266 ensure!(
267 range.start <= range.end && range.end <= self.len(),
268 "Invalid source range"
269 );
270 let mut chunks = self.chunks();
271 while !chunks.slice.is_empty() {
272 let start = self.len().saturating_sub(chunks.slice.len());
273 let chunk = chunks.next().context("Invalid mixed-mode chunk")?;
274 let end = self.len().saturating_sub(chunks.slice.len());
275 match chunk {
276 crate::DcMixedChunk::Text(text) => {
277 for boundary in [range.start, range.end] {
278 if start <= boundary && boundary <= end {
279 ensure!(
280 text.is_char_boundary(
281 boundary.saturating_sub(start)
282 ),
283 "Source range splits a Dc character"
284 );
285 }
286 }
287 }
288 _ => {
289 for boundary in [range.start, range.end] {
290 ensure!(
291 boundary <= start || boundary >= end,
292 "Source range splits an encapsulation"
293 );
294 }
295 }
296 }
297 }
298 DcMstring::from_bytes(splice(
299 self.as_bytes(),
300 range,
301 fragment.payload_bytes(),
302 )?)
303 .map_err(Into::into)
304 }
305}
306
307impl DcSource for DcStr {
308 type Owned = DcString;
309
310 fn source_bytes(&self) -> &[u8] {
311 self.as_bytes()
312 }
313
314 fn replace_typed_source_field_with_policy_and_resolver(
315 &self,
316 range: Range<usize>,
317 fragment: &DcMstr,
318 policy: &crate::DcProjectionPolicy,
319 resolver: &dyn SyntaxRuleResolver,
320 ) -> Result<DcString> {
321 ensure!(
322 self.is_char_boundary(range.start)
323 && self.is_char_boundary(range.end),
324 "Source range splits a Dc character"
325 );
326 let bytes = self
327 .as_bytes()
328 .get(range.clone())
329 .context("Invalid source fragment range")?;
330 let replacement =
331 fragment.to_dc_string_with_policy_and_resolver(policy, resolver)?;
332 let revised =
333 crate::source_edit::preserve_text_with_policy_and_resolver(
334 DcStr::from_bytes(bytes)?,
335 &replacement,
336 policy,
337 resolver,
338 )?;
339 Ok(DcString::from_dctf(splice(
340 self.as_bytes(),
341 range,
342 revised.as_bytes(),
343 )?)?)
344 }
345
346 fn replace_source_field(
347 &self,
348 range: Range<usize>,
349 fragment: &DcMstr,
350 ) -> Result<DcString> {
351 ensure!(
352 range.start <= range.end && range.end <= self.len(),
353 "Invalid source range"
354 );
355 ensure!(
356 self.is_char_boundary(range.start)
357 && self.is_char_boundary(range.end),
358 "Source range splits a Dc character"
359 );
360 let fragment = fragment.to_dc_string()?;
361 DcString::from_dctf(splice(
362 self.as_bytes(),
363 range,
364 fragment.as_bytes(),
365 )?)
366 .map_err(Into::into)
367 }
368}
369
370pub struct DcInspection<'a, T, S: DcSource + ?Sized = DcMstr> {
375 source: &'a S,
376 value: Option<T>,
377 fields: Vec<DcFieldAnnotation>,
378 diagnostics: Vec<DcDiagnostic>,
379 policy: crate::DcProjectionPolicy,
380 resolver: Option<&'a dyn SyntaxRuleResolver>,
381}
382
383impl<T: std::fmt::Debug, S: DcSource + std::fmt::Debug + ?Sized> std::fmt::Debug
384 for DcInspection<'_, T, S>
385{
386 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
387 f.debug_struct("DcInspection")
388 .field("source", &&self.source)
389 .field("value", &self.value)
390 .field("fields", &self.fields)
391 .field("diagnostics", &self.diagnostics)
392 .field("has_resolver", &self.resolver.is_some())
393 .finish()
394 }
395}
396
397impl<'a, T: DcMixedDecode, S: DcSource + ?Sized> DcInspection<'a, T, S> {
398 fn read(
399 source: &'a S,
400 context: Option<&crate::SharedValueContext>,
401 policy: &crate::DcProjectionPolicy,
402 ) -> Self {
403 Self::read_with_resolver(source, context, policy, None)
404 }
405
406 fn read_with_resolver(
407 source: &'a S,
408 context: Option<&crate::SharedValueContext>,
409 policy: &crate::DcProjectionPolicy,
410 resolver: Option<&'a dyn SyntaxRuleResolver>,
411 ) -> Self {
412 let bytes = source.source_bytes();
413 let mut arena = crate::DcSyntaxArena::new();
414 let mut nav = if bytes.starts_with(&crate::DCMM_MAGIC) {
415 match DcMstr::from_bytes_with_policy(bytes, policy) {
416 Ok(mstr) => crate::DcDocumentNavigator::from_mstr(mstr),
417 Err(err) => {
418 return Self {
419 source,
420 value: None,
421 fields: Vec::new(),
422 diagnostics: vec![DcDiagnostic {
423 position: 0,
424 error: err.into(),
425 }],
426 policy: policy.clone(),
427 resolver,
428 };
429 }
430 }
431 } else {
432 match DcStr::from_bytes(bytes) {
433 Ok(text) => crate::DcDocumentNavigator::from_dc_str(text),
434 Err(err) => {
435 return Self {
436 source,
437 value: None,
438 fields: Vec::new(),
439 diagnostics: vec![DcDiagnostic {
440 position: 0,
441 error: err.into(),
442 }],
443 policy: policy.clone(),
444 resolver,
445 };
446 }
447 }
448 };
449
450 let parsed = if let Some(r) = resolver {
451 nav.parse_document_into_arena_with_resolver(&mut arena, policy, r)
452 } else {
453 nav.parse_document_into_arena(&mut arena, policy)
454 };
455 let mut diagnostics: Vec<DcDiagnostic> = arena
456 .diagnostics()
457 .iter()
458 .map(|diagnostic| DcDiagnostic {
459 position: diagnostic.token_offset,
460 error: anyhow::anyhow!(diagnostic.message.clone()),
461 })
462 .collect();
463 if let Err(err) = parsed {
464 let err_msg = err.to_string();
465 if diagnostics
466 .last()
467 .is_none_or(|d| d.error.to_string() != err_msg)
468 {
469 diagnostics.push(DcDiagnostic {
470 position: nav.position(),
471 error: err,
472 });
473 }
474 return Self {
475 source,
476 value: None,
477 fields: Vec::new(),
478 diagnostics,
479 policy: policy.clone(),
480 resolver,
481 };
482 }
483
484 let effective_resolver = nav.effective_resolver();
485 let active_resolver: &dyn SyntaxRuleResolver =
487 resolver.unwrap_or(effective_resolver.as_ref());
488 let roots = arena.roots();
489 let (result, fields, ctx_pos, projection_diagnostics, trailing_error) = {
490 let mut ctx = DcProjectionContext::with_all_resolvers(
491 &arena,
492 policy,
493 context,
494 Some(&mut nav),
495 Some(active_resolver),
496 None,
497 );
498 ctx.annotating = true;
499 let roots = ctx.strip_leading_document_most_recent_root(roots);
500 let result = T::decode_dc_document(&mut ctx, roots);
501 let trailing_error = if let Ok((_, consumed)) = &result {
502 match roots.get(*consumed..) {
503 Some(remaining) => {
504 ctx.handle_remaining_nodes(remaining).err()
505 }
506 None => Some(anyhow::anyhow!(
507 "Invalid document root consumption"
508 )),
509 }
510 } else {
511 None
512 };
513 let fields = std::mem::take(&mut ctx.annotations);
514 let projection_diagnostics = ctx.diagnostics().to_vec();
515 (
516 result,
517 fields,
518 ctx.current_position,
519 projection_diagnostics,
520 trailing_error,
521 )
522 };
523
524 diagnostics.extend(projection_diagnostics.into_iter().map(
525 |diagnostic| DcDiagnostic {
526 position: diagnostic.token_offset,
527 error: anyhow::anyhow!(diagnostic.message),
528 },
529 ));
530 let value = match result {
531 Ok((value, _)) => Some(value),
532 Err(e) => {
533 let err_msg = e.to_string();
534 if diagnostics
535 .last()
536 .is_none_or(|d| d.error.to_string() != err_msg)
537 {
538 let pos = if ctx_pos != 0 {
539 ctx_pos
540 } else {
541 nav.position()
542 };
543 diagnostics.push(DcDiagnostic {
544 position: pos,
545 error: e,
546 });
547 }
548 None
549 }
550 };
551 if let Some(error) = trailing_error {
552 let err_msg = error.to_string();
553 if diagnostics
554 .last()
555 .is_none_or(|d| d.error.to_string() != err_msg)
556 {
557 diagnostics.push(DcDiagnostic {
558 position: ctx_pos,
559 error,
560 });
561 }
562 }
563
564 Self {
565 source,
566 value,
567 fields,
568 diagnostics,
569 policy: policy.clone(),
570 resolver,
571 }
572 }
573
574 #[must_use]
576 pub fn source_bytes(&self) -> &[u8] {
577 self.source.source_bytes()
578 }
579
580 #[must_use]
583 pub const fn value(&self) -> Option<&T> {
584 self.value.as_ref()
585 }
586
587 #[must_use]
589 pub fn fields(&self) -> &[DcFieldAnnotation] {
590 &self.fields
591 }
592
593 #[must_use]
595 pub fn diagnostic(&self) -> Option<&DcDiagnostic> {
596 self.diagnostics.first()
597 }
598
599 #[must_use]
601 pub fn diagnostics(&self) -> &[DcDiagnostic] {
602 &self.diagnostics
603 }
604
605 pub fn replace_annotation<C: DcMixedFields>(
620 &self,
621 annotation: &DcFieldAnnotation,
622 updated: &C,
623 ) -> Result<S::Owned> {
624 ensure!(
625 self.fields
626 .iter()
627 .any(|field| std::ptr::eq(field, annotation)),
628 "Annotation does not belong to this source inspection"
629 );
630 ensure!(
631 annotation.owner == C::dc_field_owner(),
632 "Updated record does not own this annotated field"
633 );
634 let mut fragment = DcMstring::new();
635 if let Some(encoding) = annotation.map_encoding {
636 updated.encode_dc_map_field(
637 annotation.field,
638 &mut fragment,
639 encoding,
640 )?;
641 } else {
642 updated.encode_dc_field(annotation.field, &mut fragment)?;
643 }
644 let strict_with_limits = crate::DcProjectionPolicy::strict()
645 .with_max_depth(
646 self.policy.max_depth,
647 crate::DiagnosticAction::Error,
648 )
649 .with_max_encapsulation_metadata_depth(
650 self.policy.max_encapsulation_metadata_depth,
651 )
652 .with_max_encapsulation_payload_bytes(
653 self.policy.max_encapsulation_payload_bytes,
654 );
655 if let Some(resolver) = self.resolver {
656 self.source
657 .replace_typed_source_field_with_policy_and_resolver(
658 annotation.range(),
659 &fragment,
660 &strict_with_limits,
661 resolver,
662 )
663 } else {
664 self.source
665 .replace_typed_source_field_with_policy_and_resolver(
666 annotation.range(),
667 &fragment,
668 &strict_with_limits,
669 ctb_formats_dcdata::syntax::default_syntax_resolver()
670 .as_ref(),
671 )
672 }
673 }
674}
675
676impl<T: DcMixedFields, S: DcSource + ?Sized> DcInspection<'_, T, S> {
677 pub fn replace_field(&self, field: &str, updated: &T) -> Result<S::Owned> {
688 let mut matching = self.fields.iter().filter(|annotation| {
689 annotation.depth == 1
690 && annotation.owner == T::dc_field_owner()
691 && annotation.field == field
692 });
693 let annotation = matching
694 .next()
695 .context("No fully decoded outer field with this name")?;
696 ensure!(
697 matching.next().is_none(),
698 "Repeated field is ambiguous; select a larger understood record instead"
699 );
700 self.replace_annotation(annotation, updated)
701 }
702}
703
704impl DcMstr {
705 #[must_use]
707 pub fn inspect<T: DcMixedDecode>(&self) -> DcInspection<'_, T> {
708 DcInspection::read(self, None, &crate::DcProjectionPolicy::strict())
709 }
710
711 #[must_use]
713 pub fn inspect_with_policy<'a, T: DcMixedDecode>(
714 &'a self,
715 policy: &crate::DcProjectionPolicy,
716 ) -> DcInspection<'a, T> {
717 DcInspection::read(self, None, policy)
718 }
719
720 #[must_use]
722 pub fn inspect_with_context<'a, T: DcMixedDecode>(
723 &'a self,
724 context: &'a crate::SharedValueContext,
725 ) -> DcInspection<'a, T> {
726 DcInspection::read(
727 self,
728 Some(context),
729 &crate::DcProjectionPolicy::strict(),
730 )
731 }
732
733 #[must_use]
735 pub fn inspect_with_resolver<'a, T: DcMixedDecode>(
736 &'a self,
737 resolver: &'a dyn SyntaxRuleResolver,
738 ) -> DcInspection<'a, T> {
739 DcInspection::read_with_resolver(
740 self,
741 None,
742 &crate::DcProjectionPolicy::strict(),
743 Some(resolver),
744 )
745 }
746
747 #[must_use]
749 pub fn inspect_with_policy_and_resolver<'a, T: DcMixedDecode>(
750 &'a self,
751 policy: &crate::DcProjectionPolicy,
752 resolver: &'a dyn SyntaxRuleResolver,
753 ) -> DcInspection<'a, T> {
754 DcInspection::read_with_resolver(self, None, policy, Some(resolver))
755 }
756}
757
758impl DcStr {
759 pub fn decode<T: DcMixedDecode>(
764 &self,
765 policy: &crate::DcProjectionPolicy,
766 ) -> Result<T> {
767 self.decode_with_resolver_and_context(
768 ctb_formats_dcdata::syntax::default_syntax_resolver().as_ref(),
769 None,
770 policy,
771 )
772 }
773
774 pub fn decode_with_context<T: DcMixedDecode>(
779 &self,
780 context: &crate::SharedValueContext,
781 policy: &crate::DcProjectionPolicy,
782 ) -> Result<T> {
783 self.decode_with_resolver_and_context(
784 ctb_formats_dcdata::syntax::default_syntax_resolver().as_ref(),
785 Some(context),
786 policy,
787 )
788 }
789
790 pub fn decode_with_resolver<T: DcMixedDecode>(
795 &self,
796 resolver: &dyn SyntaxRuleResolver,
797 policy: &crate::DcProjectionPolicy,
798 ) -> Result<T> {
799 self.decode_with_resolver_and_context(resolver, None, policy)
800 }
801
802 pub fn decode_with_resolver_and_context<T: DcMixedDecode>(
808 &self,
809 resolver: &dyn SyntaxRuleResolver,
810 context: Option<&crate::SharedValueContext>,
811 policy: &crate::DcProjectionPolicy,
812 ) -> Result<T> {
813 let mut nav = crate::DcDocumentNavigator::from_dc_str(self);
814 let mut arena = crate::DcSyntaxArena::new();
815 nav.parse_document_into_arena_with_resolver(
816 &mut arena, policy, resolver,
817 )?;
818 let roots = arena.roots();
819 let mut ctx = DcProjectionContext::with_all_resolvers(
820 &arena,
821 policy,
822 context,
823 Some(&mut nav),
824 Some(resolver),
825 None,
826 );
827 let (res, consumed) = T::decode_dc_document(&mut ctx, roots)?;
828 ctx.handle_remaining_nodes(
829 roots
830 .get(consumed..)
831 .context("Invalid document root consumption")?,
832 )?;
833 Ok(res)
834 }
835
836 #[must_use]
838 pub fn inspect<T: DcMixedDecode>(&self) -> DcInspection<'_, T, DcStr> {
839 DcInspection::read(self, None, &crate::DcProjectionPolicy::strict())
840 }
841
842 #[must_use]
844 pub fn inspect_with_policy<'a, T: DcMixedDecode>(
845 &'a self,
846 policy: &crate::DcProjectionPolicy,
847 ) -> DcInspection<'a, T, DcStr> {
848 DcInspection::read(self, None, policy)
849 }
850
851 #[must_use]
853 pub fn inspect_with_context<'a, T: DcMixedDecode>(
854 &'a self,
855 context: &'a crate::SharedValueContext,
856 ) -> DcInspection<'a, T, DcStr> {
857 DcInspection::read(
858 self,
859 Some(context),
860 &crate::DcProjectionPolicy::strict(),
861 )
862 }
863
864 #[must_use]
866 pub fn inspect_with_resolver<'a, T: DcMixedDecode>(
867 &'a self,
868 resolver: &'a dyn SyntaxRuleResolver,
869 ) -> DcInspection<'a, T, DcStr> {
870 DcInspection::read_with_resolver(
871 self,
872 None,
873 &crate::DcProjectionPolicy::strict(),
874 Some(resolver),
875 )
876 }
877
878 #[must_use]
880 pub fn inspect_with_policy_and_resolver<'a, T: DcMixedDecode>(
881 &'a self,
882 policy: &crate::DcProjectionPolicy,
883 resolver: &'a dyn SyntaxRuleResolver,
884 ) -> DcInspection<'a, T, DcStr> {
885 DcInspection::read_with_resolver(self, None, policy, Some(resolver))
886 }
887}
888
889#[derive(Clone, Debug, PartialEq, Eq)]
891pub struct DcFieldAnnotation {
892 owner: &'static str,
893 field: &'static str,
894 range: Range<usize>,
895 depth: usize,
896 map_encoding: Option<crate::DcKvMapEncoding>,
897}
898
899impl DcFieldAnnotation {
900 pub(crate) const fn new(
901 owner: &'static str,
902 field: &'static str,
903 range: Range<usize>,
904 depth: usize,
905 ) -> Self {
906 Self {
907 owner,
908 field,
909 range,
910 depth,
911 map_encoding: None,
912 }
913 }
914
915 pub(crate) fn with_map_encoding(
916 mut self,
917 encoding: crate::DcKvMapEncoding,
918 ) -> Self {
919 self.map_encoding = Some(encoding);
920 self
921 }
922
923 #[must_use]
925 pub const fn owner(&self) -> &'static str {
926 self.owner
927 }
928
929 #[must_use]
931 pub const fn field(&self) -> &'static str {
932 self.field
933 }
934
935 #[must_use]
937 pub fn range(&self) -> Range<usize> {
938 self.range.clone()
939 }
940
941 #[must_use]
943 pub const fn depth(&self) -> usize {
944 self.depth
945 }
946}