1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::any::Any;
30use std::collections::BTreeMap;
31use std::sync::Arc;
32
33pub use serde_json;
34
35use crate::{
36 DcChar, DcMixedDecode, DcMixedEncode, DcMstring, DcProjectionContext,
37 NodeId,
38};
39use ctb_formats_dcdata::dc::{
40 DC_ASSIGN, DC_BEGIN_IDENTIFIER, DC_END_IDENTIFIER,
41 DC_ENTER_IDENTIFIER_SCOPE, DC_ESCAPE, DC_EXIT_IDENTIFIER_SCOPE,
42 DC_REFERENCE_BOUND_VALUE,
43};
44
45#[derive(Clone, Default)]
47pub struct SharedValueContext {
48 bindings: BTreeMap<DcMstring, Arc<dyn Any + Send + Sync>>,
49 scopes: Vec<BTreeMap<DcMstring, Arc<dyn Any + Send + Sync>>>,
50}
51
52impl std::fmt::Debug for SharedValueContext {
53 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 formatter
55 .debug_list()
56 .entries(
57 self.scopes
58 .iter()
59 .rev()
60 .chain(std::iter::once(&self.bindings))
61 .flat_map(BTreeMap::keys),
62 )
63 .finish()
64 }
65}
66
67impl SharedValueContext {
68 #[must_use]
70 pub fn contains(&self, name: impl Into<DcMstring>) -> bool {
71 let name = name.into();
72 self.lookup(&name).is_some()
73 }
74
75 fn lookup(
76 &self,
77 name: &crate::DcMstr,
78 ) -> Option<&Arc<dyn Any + Send + Sync>> {
79 self.scopes
80 .iter()
81 .rev()
82 .chain(std::iter::once(&self.bindings))
83 .find_map(|scope| scope.get(name))
84 }
85
86 pub fn enter_scope(&mut self) {
88 self.scopes.push(BTreeMap::new());
89 }
90
91 pub fn exit_scope(&mut self) -> Result<()> {
93 self.scopes.pop().context("No reference scope to exit")?;
94 Ok(())
95 }
96
97 pub fn insert<T: Any + Send + Sync>(
99 &mut self,
100 name: impl Into<DcMstring>,
101 value: Arc<T>,
102 ) -> Result<()> {
103 let name = name.into();
104 ensure!(!name.is_empty(), "Shared binding names must not be empty");
105 let scope = if let Some(scope) = self.scopes.last() {
106 scope
107 } else {
108 &self.bindings
109 };
110 ensure!(
111 !scope.contains_key(&name),
112 "Duplicate shared binding {name:?}"
113 );
114 if self.lookup(&name).is_some() {
115 warn_fmt!(
116 "Reference declaration {name:?} shadows an enclosing declaration"
117 );
118 }
119 let scope = if let Some(scope) = self.scopes.last_mut() {
120 scope
121 } else {
122 &mut self.bindings
123 };
124 scope.insert(name, Arc::new(value));
125 Ok(())
126 }
127
128 pub fn binding_for<T: Any + Send + Sync + PartialEq>(
130 &self,
131 value: &Arc<T>,
132 ) -> Option<&crate::DcMstr> {
133 self.scopes
134 .iter()
135 .rev()
136 .chain(std::iter::once(&self.bindings))
137 .flat_map(BTreeMap::iter)
138 .find_map(|(name, binding)| {
139 if !self
140 .lookup(name)
141 .is_some_and(|visible| Arc::ptr_eq(visible, binding))
142 {
143 return None;
144 }
145 let stored = binding.downcast_ref::<Arc<T>>()?;
146 if Arc::ptr_eq(stored, value) || stored == value {
147 Some(name.as_mstr())
148 } else {
149 None
150 }
151 })
152 }
153
154 pub fn resolve<T: Any + Send + Sync>(
156 &self,
157 name: impl Into<DcMstring>,
158 ) -> Result<Arc<T>> {
159 let name = name.into();
160 let binding = self
161 .lookup(&name)
162 .with_context(|| format!("Unresolved shared binding {name:?}"))?;
163 let value = binding.downcast_ref::<Arc<T>>().with_context(|| {
164 format!("Wrong type for shared binding {name:?}")
165 })?;
166 Ok(Arc::clone(value))
167 }
168}
169
170pub fn encode_scope_begin(mst: &mut DcMstring, scope: &mut SharedValueContext) {
172 mst.push_char(DC_ENTER_IDENTIFIER_SCOPE);
173 scope.enter_scope();
174}
175
176pub fn encode_scope_end(
178 mst: &mut DcMstring,
179 scope: &mut SharedValueContext,
180) -> Result<()> {
181 scope.exit_scope()?;
182 mst.push_char(DC_EXIT_IDENTIFIER_SCOPE);
183 Ok(())
184}
185
186pub fn encode_declaration<T>(
188 mst: &mut DcMstring,
189 scope: &mut SharedValueContext,
190 name: &str,
191 value: Arc<T>,
192) -> Result<()>
193where
194 T: Any + Send + Sync + DcMixedEncode,
195{
196 encode_identifier(mst, name)?;
197 mst.push_char(DC_ASSIGN);
198 value.encode_dc_mixed_with_context(mst, scope)?;
199 scope.insert(name, value)
200}
201
202pub trait SharedJson: Sized {
204 fn encode_json_with_context(
205 &self,
206 context: &SharedValueContext,
207 ) -> Result<serde_json::Value>;
208 fn decode_json_with_context(
209 value: serde_json::Value,
210 context: &SharedValueContext,
211 ) -> Result<Self>;
212}
213
214pub fn shared_to_json<T>(
216 value: &Arc<T>,
217 context: &SharedValueContext,
218) -> Result<serde_json::Value>
219where
220 T: Any + Send + Sync + PartialEq + serde::Serialize,
221{
222 let (key, payload) = if let Some(name) = context.binding_for(value) {
223 ("$dc_shared", serde_json::Value::String(name.to_string()))
224 } else {
225 ("$dc_inline", serde_json::to_value(value)?)
226 };
227 Ok(serde_json::Value::Object(serde_json::Map::from_iter([(
228 key.to_owned(),
229 payload,
230 )])))
231}
232
233pub fn shared_from_json<T>(
235 value: serde_json::Value,
236 context: &SharedValueContext,
237) -> Result<Arc<T>>
238where
239 T: Any + Send + Sync + serde::de::DeserializeOwned,
240{
241 let serde_json::Value::Object(mut envelope) = value else {
242 bail!("Expected shared-value envelope");
243 };
244 ensure!(envelope.len() == 1, "Invalid shared-value envelope");
245 if let Some(value) = envelope.remove("$dc_shared") {
246 let name = value.as_str().context("Shared binding must be a string")?;
247 context.resolve(name)
248 } else if let Some(value) = envelope.remove("$dc_inline") {
249 Ok(Arc::new(serde_json::from_value(value)?))
250 } else {
251 bail!("Unknown shared-value envelope");
252 }
253}
254
255pub fn encode_identifier(mst: &mut DcMstring, name: &str) -> Result<()> {
257 encode_identifier_to(&mut mst.writer(), name)
258}
259
260pub fn encode_identifier_to(
261 mst: &mut crate::DcWriter<'_>,
262 name: &str,
263) -> Result<()> {
264 ensure!(!name.is_empty(), "Identifiers must not be empty");
265 mst.push_char(DC_BEGIN_IDENTIFIER)?;
266 for character in name.chars() {
267 let character = DcChar::from_char(character);
268 if character == DC_ESCAPE || character == DC_END_IDENTIFIER {
269 mst.push_char(DC_ESCAPE)?;
270 }
271 mst.push_char(character)?;
272 }
273 mst.push_char(DC_END_IDENTIFIER)?;
274 Ok(())
275}
276
277pub fn encode_dc_identifier(
279 mst: &mut DcMstring,
280 name: &crate::DcMstr,
281) -> Result<()> {
282 encode_dc_identifier_to(&mut mst.writer(), name)
283}
284
285pub fn encode_dc_identifier_to(
286 mst: &mut crate::DcWriter<'_>,
287 name: &crate::DcMstr,
288) -> Result<()> {
289 use ctb_formats_dcdata::DcCharExt;
290 for chunk in name.chunks() {
291 if !matches!(chunk, crate::DcMixed::Text(_)) {
292 bail!(
293 "Cannot encode DcMstr containing raw binary chunks as an identifier"
294 );
295 }
296 }
297 let dc_str = name.to_dc_string()?;
298 ensure!(!dc_str.is_empty(), "Identifiers must not be empty");
299 let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
300 mst.push_char(DC_BEGIN_IDENTIFIER)?;
301 for (idx, character) in dc_str.chars().enumerate() {
302 if character.fills_role(ctb_formats_dcdata::syntax::DcRole::Escape)
303 || character
304 .fills_role(ctb_formats_dcdata::syntax::DcRole::EndIdentifier)
305 || (idx == 0
306 && crate::navigator::is_identifier_leading_type_starter(
307 character,
308 resolver.as_ref(),
309 ))
310 {
311 mst.push_char(DC_ESCAPE)?;
312 }
313 mst.push_char(character)?;
314 }
315 mst.push_char(DC_END_IDENTIFIER)?;
316 Ok(())
317}
318
319pub fn decode_dc_identifier(
321 ctx: &mut DcProjectionContext<'_, '_>,
322 node_id: NodeId,
323) -> Result<DcMstring> {
324 if let Some(name) =
325 ctx.arena.decode_identifier_with_resolver(node_id, ctx.resolver())
326 {
327 ensure!(!name.is_empty(), "Identifiers must not be empty");
328 Ok(name)
329 } else {
330 let node = ctx.node(node_id)?;
331 bail!(
332 "Expected Identifier node (Dc 270 .. 271), found {:?}",
333 node.kind
334 )
335 }
336}
337
338pub fn decode_identifier(
340 ctx: &mut DcProjectionContext<'_, '_>,
341 node_id: NodeId,
342) -> Result<DcMstring> {
343 decode_dc_identifier(ctx, node_id)
344}
345
346pub fn encode_shared_reference(
348 mst: &mut DcMstring,
349 field: &str,
350 binding: impl Into<DcMstring>,
351) -> Result<()> {
352 encode_shared_reference_to(&mut mst.writer(), field, binding)
353}
354
355pub fn encode_shared_reference_to(
356 mst: &mut crate::DcWriter<'_>,
357 field: &str,
358 binding: impl Into<DcMstring>,
359) -> Result<()> {
360 let binding = binding.into();
361 encode_identifier_to(mst, field)?;
362 mst.push_char(DC_ASSIGN)?;
363 mst.push_char(DC_REFERENCE_BOUND_VALUE)?;
364 encode_dc_identifier_to(mst, binding.as_mstr())
365}
366
367pub fn decode_shared_reference(
369 ctx: &mut DcProjectionContext<'_, '_>,
370 node_id: NodeId,
371) -> Result<(DcMstring, DcMstring)> {
372 if let Some((ident, value)) =
373 ctx.arena.decode_assignment_with_resolver(node_id, ctx.resolver())
374 {
375 let val_node = ctx.node(value)?;
376 match &val_node.kind {
377 crate::navigator::DcSyntaxKind::Tagged { tag, args }
378 if ctx.token_fills_role(
379 *tag,
380 ctb_formats_dcdata::syntax::DcRole::ReferenceBoundValue,
381 ) =>
382 {
383 let target_id = args
384 .first()
385 .copied()
386 .context("Missing reference target identifier")?;
387 let target_name = decode_dc_identifier(ctx, target_id)?;
388 Ok((ident, target_name))
389 }
390 other => bail!(
391 "Expected reference tag Dc 540 in assignment, found {other:?}"
392 ),
393 }
394 } else {
395 let node = ctx.node(node_id)?;
396 bail!("Expected Assignment node, found {:?}", node.kind)
397 }
398}
399
400#[cfg(test)]
401#[allow(
402 clippy::panic,
403 clippy::expect_used,
404 clippy::unwrap_used,
405 clippy::unwrap_in_result,
406 clippy::panic_in_result_fn,
407 clippy::indexing_slicing,
408 clippy::arithmetic_side_effects,
409 reason = "Standard repository test boilerplate"
410)]
411mod tests {
412 use super::*;
413
414 #[derive(
415 Debug,
416 PartialEq,
417 Eq,
418 serde::Serialize,
419 serde::Deserialize,
420 crate::DcMixed,
421 )]
422 #[dc(key_value)]
423 struct Definition {
424 #[dc(key = "value")]
425 value: u64,
426 }
427
428 #[derive(
429 Debug,
430 PartialEq,
431 Eq,
432 serde::Serialize,
433 serde::Deserialize,
434 crate::DcMixed,
435 )]
436 #[dc(begin = 401, end = 402)]
437 struct SharedRecord {
438 #[dc(nested = 559, shared = "definition")]
439 definition: Option<Arc<Definition>>,
440 }
441
442 #[derive(Debug, PartialEq, Eq, crate::DcMixed)]
443 #[dc(key_value)]
444 struct NestedRecord {
445 #[dc(key = "record")]
446 record: Box<SharedRecord>,
447 }
448
449 #[crate::ctb_test]
450 fn test_shared_attribute_roundtrip() -> Result<()> {
451 let strict = crate::DcProjectionPolicy::strict();
452 let definition = Arc::new(Definition { value: 42 });
453 let record = SharedRecord {
454 definition: Some(Arc::clone(&definition)),
455 };
456 crate::assert_dc_roundtrip(&record)?;
457 let mut context = SharedValueContext::default();
458 context.insert("source", Arc::clone(&definition))?;
459 let mut encoded = DcMstring::new();
460 record.encode_dc_mixed_with_context(&mut encoded, &context)?;
461 let decoded =
462 encoded.decode_with_context::<SharedRecord>(&context, &strict)?;
463 assert!(
464 decoded
465 .definition
466 .as_ref()
467 .is_some_and(|value| Arc::ptr_eq(value, &definition))
468 );
469 encoded.decode::<SharedRecord>(&strict).unwrap_err();
470 let json = record.encode_json_with_context(&context)?;
471 let decoded =
472 SharedRecord::decode_json_with_context(json.clone(), &context)?;
473 assert!(
474 decoded
475 .definition
476 .as_ref()
477 .is_some_and(|value| Arc::ptr_eq(value, &definition))
478 );
479 SharedRecord::decode_json_with_context(
480 json,
481 &SharedValueContext::default(),
482 )
483 .unwrap_err();
484 let empty = SharedRecord { definition: None };
485 assert_eq!(
486 SharedRecord::decode_json_with_context(
487 empty.encode_json_with_context(&context)?,
488 &context
489 )?,
490 empty
491 );
492 let distinct = SharedRecord {
493 definition: Some(Arc::new(Definition { value: 43 })),
494 };
495 let mut inline = DcMstring::new();
496 distinct.encode_dc_mixed_with_context(&mut inline, &context)?;
497 assert_eq!(inline.decode::<SharedRecord>(&strict)?, distinct);
498 let nested = NestedRecord {
499 record: Box::new(record),
500 };
501 let mut encoded = DcMstring::new();
502 nested.encode_dc_mixed_with_context(&mut encoded, &context)?;
503 let decoded =
504 encoded.decode_with_context::<NestedRecord>(&context, &strict)?;
505 assert!(
506 decoded
507 .record
508 .definition
509 .as_ref()
510 .is_some_and(|value| Arc::ptr_eq(value, &definition))
511 );
512 let array = [nested.record];
513 let mut encoded = DcMstring::new();
514 array.encode_dc_mixed_with_context(&mut encoded, &context)?;
515 let decoded = encoded
516 .decode_with_context::<[Box<SharedRecord>; 1]>(&context, &strict)?;
517 assert!(
518 decoded
519 .first()
520 .and_then(|record| record.definition.as_ref())
521 .is_some_and(|value| Arc::ptr_eq(value, &definition))
522 );
523 let mut duplicate = DcMstring::new();
524 duplicate.push_char(DcChar::from_short(401));
525 encode_shared_reference(&mut duplicate, "definition", "source")?;
526 encode_shared_reference(&mut duplicate, "definition", "source")?;
527 duplicate.push_char(DcChar::from_short(402));
528 duplicate
529 .decode_with_context::<SharedRecord>(&context, &strict)
530 .unwrap_err();
531 let mut unknown = DcMstring::new();
532 unknown.push_char(DcChar::from_short(401));
533 encode_shared_reference(&mut unknown, "unknown", "source")?;
534 unknown.push_char(DcChar::from_short(402));
535 unknown
536 .decode_with_context::<SharedRecord>(&context, &strict)
537 .unwrap_err();
538 Ok(())
539 }
540
541 #[crate::ctb_test]
542 fn test_source_shared_reference_edits() -> Result<()> {
543 let strict = crate::DcProjectionPolicy::strict();
544 let definition = Arc::new(Definition { value: 42 });
545 let record = SharedRecord {
546 definition: Some(Arc::clone(&definition)),
547 };
548 let updated = SharedRecord {
549 definition: Some(Arc::new(Definition { value: 999 })),
550 };
551 let mut context = SharedValueContext::default();
552 context.insert("source", Arc::clone(&definition))?;
553 let mut source = DcMstring::new();
554 record.encode_dc_mixed_with_context(&mut source, &context)?;
555 assert!(source.inspect::<SharedRecord>().diagnostic().is_some());
556 let view = source.inspect_with_context::<SharedRecord>(&context);
557 assert!(view.diagnostic().is_none());
558 assert_eq!(view.fields().len(), 1);
559 let revised = view.replace_field("definition", &updated)?;
560 assert_eq!(revised.decode::<SharedRecord>(&strict)?, updated);
561 let text = source.to_dc_string()?;
562 assert_eq!(
563 text.decode_with_context::<SharedRecord>(&context, &strict)?,
564 record
565 );
566 let revised = text
567 .inspect_with_context::<SharedRecord>(&context)
568 .replace_field("definition", &updated)?;
569 assert_eq!(revised.decode::<SharedRecord>(&strict)?, updated);
570 assert!(Arc::ptr_eq(
571 &context.resolve::<Definition>("source")?,
572 &definition
573 ));
574 Ok(())
575 }
576
577 #[crate::ctb_test]
578 fn test_lexical_reference_scopes() -> Result<()> {
579 let strict = crate::DcProjectionPolicy::strict();
580 let outer = Arc::new(Definition { value: 42 });
581 let inner = Arc::new(Definition { value: 43 });
582 let mut scope = SharedValueContext::default();
583 let mut document = DcMstring::new();
584 encode_scope_begin(&mut document, &mut scope);
585 encode_declaration(
586 &mut document,
587 &mut scope,
588 "source",
589 Arc::clone(&outer),
590 )?;
591 let outer_record = SharedRecord {
592 definition: Some(Arc::clone(&outer)),
593 };
594 outer_record.encode_dc_mixed_with_context(&mut document, &scope)?;
595 encode_scope_begin(&mut document, &mut scope);
596 encode_declaration(
597 &mut document,
598 &mut scope,
599 "source",
600 Arc::clone(&inner),
601 )?;
602 assert!(scope.binding_for(&outer).is_none());
603 SharedRecord {
604 definition: Some(Arc::clone(&inner)),
605 }
606 .encode_dc_mixed_with_context(&mut document, &scope)?;
607 encode_scope_end(&mut document, &mut scope)?;
608 assert!(Arc::ptr_eq(&scope.resolve::<Definition>("source")?, &outer));
609 outer_record.encode_dc_mixed_with_context(&mut document, &scope)?;
610 encode_scope_end(&mut document, &mut scope)?;
611 scope.resolve::<Definition>("source").unwrap_err();
612 assert!(scope.exit_scope().is_err());
613
614 let mut arena = crate::DcSyntaxArena::new();
615 crate::DcDocumentNavigator::parse_document_arena(
616 document.as_bytes(),
617 &mut arena,
618 &strict,
619 )?;
620 let mut ctx = crate::DcProjectionContext::new(&arena, &strict);
621 let roots = arena.roots();
622 ensure!(roots.len() == 1, "Expected single root scope");
623 let outer_scope_id = roots[0];
624 let outer_scope_node = arena
625 .node(outer_scope_id)
626 .context("Outer scope node missing")?;
627 let children = match &outer_scope_node.kind {
628 crate::navigator::DcSyntaxKind::Container { children, .. } => {
629 children.clone()
630 }
631 other => {
632 bail!("Expected container for outer scope, found {other:?}")
633 }
634 };
635
636 ctx.enter_reference_scope();
637 let outer_decl = ctx.decode_declaration::<Definition>(children[0])?;
638 assert_eq!(*outer_decl, *outer);
639
640 let decoded1 = SharedRecord::decode_dc_node(&mut ctx, children[1])?;
641 assert!(
642 decoded1
643 .definition
644 .as_ref()
645 .is_some_and(|value| Arc::ptr_eq(value, &outer_decl))
646 );
647
648 let inner_scope_node = arena
649 .node(children[2])
650 .context("Inner scope node missing")?;
651 let inner_children = match &inner_scope_node.kind {
652 crate::navigator::DcSyntaxKind::Container { children, .. } => {
653 children.clone()
654 }
655 other => {
656 bail!("Expected container for inner scope, found {other:?}")
657 }
658 };
659 ctx.enter_reference_scope();
660 let inner_decl =
661 ctx.decode_declaration::<Definition>(inner_children[0])?;
662 assert_eq!(*inner_decl, *inner);
663 let decoded2 =
664 SharedRecord::decode_dc_node(&mut ctx, inner_children[1])?;
665 assert!(
666 decoded2
667 .definition
668 .as_ref()
669 .is_some_and(|value| Arc::ptr_eq(value, &inner_decl))
670 );
671 ctx.exit_reference_scope()?;
672
673 let decoded3 = SharedRecord::decode_dc_node(&mut ctx, children[3])?;
674 assert!(
675 decoded3
676 .definition
677 .as_ref()
678 .is_some_and(|value| Arc::ptr_eq(value, &outer_decl))
679 );
680 ctx.exit_reference_scope()?;
681 ctx.resolve_shared::<Definition>("source").unwrap_err();
682
683 let mut next_document = DcMstring::new();
684 next_document.push_char(DcChar::from_short(401));
685 encode_shared_reference(&mut next_document, "definition", "source")?;
686 next_document.push_char(DcChar::from_short(402));
687 next_document.decode::<SharedRecord>(&strict).unwrap_err();
688
689 let mut identifier = DcMstring::new();
690 encode_identifier(&mut identifier, "source.environment")?;
691 let mut id_arena = crate::DcSyntaxArena::new();
692 let id_root = crate::DcDocumentNavigator::parse_arena(
693 identifier.as_bytes(),
694 &mut id_arena,
695 &strict,
696 )?;
697 let mut id_ctx = crate::DcProjectionContext::new(&id_arena, &strict);
698 assert_eq!(
699 decode_identifier(&mut id_ctx, id_root)?,
700 "source.environment"
701 );
702 assert!(encode_identifier(&mut DcMstring::new(), "").is_err());
703 Ok(())
704 }
705
706 #[crate::ctb_test]
707 fn test_shared_context_and_json() -> Result<()> {
708 let original = Arc::new(42u64);
709 let mut context = SharedValueContext::default();
710 context.insert("source", Arc::clone(&original))?;
711 let encoded = shared_to_json(&original, &context)?;
712 assert_eq!(
713 encoded
714 .get("$dc_shared")
715 .and_then(serde_json::Value::as_str),
716 Some("source")
717 );
718 let decoded = shared_from_json::<u64>(encoded.clone(), &context)?;
719 assert!(Arc::ptr_eq(&original, &decoded));
720 shared_from_json::<u64>(encoded, &SharedValueContext::default())
721 .unwrap_err();
722 context.resolve::<String>("source").unwrap_err();
723 assert!(context.insert("source", Arc::new(9u64)).is_err());
724 let distinct = Arc::new(43u64);
725 let encoded = shared_to_json(&distinct, &context)?;
726 assert_eq!(*shared_from_json::<u64>(encoded, &context)?, 43);
727 assert_eq!(
728 context.binding_for(&Arc::new(42u64)),
729 Some(DcMstring::from("source").as_mstr())
730 );
731 Ok(())
732 }
733}