c4/trace.rs
1//! Provenance: [`SourceRef`] labels and the [`TracedValue`] tree that
2//! `Loader::trace` returns. Serializes to `$id`-tagged JSON leaves — a
3//! debug/test aid, never config data.
4
5use std::collections::BTreeMap;
6use std::path::PathBuf;
7
8use crate::Value;
9
10/// Where a traced value came from.
11///
12/// Source labels exist for debugging and testing — they are not config
13/// data, and no config semantics should be built on top of them.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum SourceRef {
16 /// The file path as the loader saw it (source path joined with the
17 /// relative path inside a folder source).
18 File(PathBuf),
19 /// A [`Source::String`] entry, by its index in the sources list.
20 String(usize),
21 /// A [`Source::value`] entry, by its index in the sources list.
22 Value(usize),
23}
24
25/// The result of [`Loader::trace`]: the merged tree with per-leaf
26/// provenance. Objects recurse; every non-object value (including whole
27/// arrays) is a [`TracedValue::Leaf`].
28///
29/// Serializes to JSON as
30/// `{ "$id": "Leaf", "value": …, "source": …, "format": … }` leaves —
31/// the shape used by the CLI `--trace` output and the test fixtures'
32/// expect.json. `$id` tags the node kind (an object node is a plain
33/// map), `source` is the file path (`SourceRef::String(i)` prints as
34/// `"string:<i>"`), `format` is the value's [`Value::format_id`].
35#[derive(Debug, Clone, PartialEq)]
36pub enum TracedValue {
37 Leaf { value: Value, source: SourceRef },
38 Object(BTreeMap<String, TracedValue>),
39}
40
41impl SourceRef {
42 /// The label used in serialized traces: the file path, or
43 /// `string:<index>` for string sources.
44 fn label(&self) -> String {
45 match self {
46 SourceRef::File(path) => path.to_string_lossy().into_owned(),
47 SourceRef::String(index) => format!("string:{index}"),
48 SourceRef::Value(index) => format!("value:{index}"),
49 }
50 }
51}
52
53impl serde::Serialize for TracedValue {
54 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
55 where
56 S: serde::Serializer,
57 {
58 use serde::ser::SerializeMap;
59 match self {
60 TracedValue::Leaf { value, source } => {
61 // "$id" tags the node kind: a plain config object could
62 // itself have value/source/format keys, and the tag makes
63 // json trace output self-describing for debugging
64 let mut map = serializer.serialize_map(Some(4))?;
65 map.serialize_entry("$id", "Leaf")?;
66 map.serialize_entry("value", value)?;
67 map.serialize_entry("source", &source.label())?;
68 map.serialize_entry("format", &value.format_id())?;
69 map.end()
70 }
71 TracedValue::Object(entries) => serializer.collect_map(entries),
72 }
73 }
74}