Skip to main content

c4/
trace.rs

1//! Provenance: [`SourceRef`] labels, the [`TracedValue`] tree and the
2//! [`Warning`]s that `Loader::trace` returns together as a [`Trace`].
3//! Serializes to `$id`-tagged JSON leaves — a debug/test aid, never
4//! config data.
5
6use std::collections::BTreeMap;
7use std::path::PathBuf;
8
9use crate::Value;
10
11/// Where a traced value came from.
12///
13/// Source labels exist for debugging and testing — they are not config
14/// data, and no config semantics should be built on top of them.
15///
16/// Non-exhaustive: new variants may come without a breaking release, so
17/// a `match` needs a `_` arm.
18#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum SourceRef {
21    /// The file path as the loader saw it (source path joined with the
22    /// relative path inside a folder source).
23    File(PathBuf),
24    /// A [`Source::String`](crate::Source::String) entry, by its index in
25    /// the sources list.
26    String(usize),
27    /// A [`Source::Value`](crate::Source::Value) entry (a 1-tuple
28    /// `(value,)` source), by its index in the sources list.
29    Value(usize),
30}
31
32/// The merged tree of a [`Trace`], with per-leaf provenance. Objects recurse; every non-object value (including whole
33/// arrays) is a [`TracedValue::Leaf`].
34///
35/// Serializes to JSON as
36/// `{ "$id": "Leaf", "value": …, "source": …, "format": … }` leaves —
37/// the shape used by the CLI `--trace` json output. `$id` tags the node kind (an object node is a plain
38/// map), `source` is the file path (`SourceRef::String(i)` prints as
39/// `"string:<i>"`), `format` is the value's [`Value::format_id`].
40#[derive(Debug, Clone, PartialEq)]
41pub enum TracedValue {
42    Leaf { value: Value, source: SourceRef },
43    Object(BTreeMap<String, TracedValue>),
44}
45
46/// The result of [`Loader::trace`](crate::Loader::trace): the merged
47/// tree plus the warnings collected while loading it.
48///
49/// Serializes to JSON as `{ "value": …, "warnings": […] }` — both keys
50/// always present.
51#[derive(Debug, Clone, PartialEq)]
52pub struct Trace {
53    pub value: TracedValue,
54    /// In load order. Empty unless some input was accepted but not acted
55    /// on — so far only skipped cnf directives (`!include`, `.include`, …).
56    pub warnings: Vec<Warning>,
57}
58
59/// Input c4 accepted but did not act on. Only a [`Trace`] carries
60/// warnings: the library never prints them, and `load()` drops them.
61///
62/// `Display` and the serialized `{ "source", "message" }` form use the
63/// same source label as the trace leaves.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct Warning {
66    pub source: SourceRef,
67    /// Starts with the line number where there is one: `line 4: …`.
68    pub message: String,
69}
70
71impl std::fmt::Display for Warning {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "{}: {}", self.source.label(), self.message)
74    }
75}
76
77impl serde::Serialize for Warning {
78    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
79    where
80        S: serde::Serializer,
81    {
82        use serde::ser::SerializeMap;
83        let mut map = serializer.serialize_map(Some(2))?;
84        map.serialize_entry("source", &self.source.label())?;
85        map.serialize_entry("message", &self.message)?;
86        map.end()
87    }
88}
89
90impl serde::Serialize for Trace {
91    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
92    where
93        S: serde::Serializer,
94    {
95        use serde::ser::SerializeMap;
96        let mut map = serializer.serialize_map(Some(2))?;
97        map.serialize_entry("value", &self.value)?;
98        map.serialize_entry("warnings", &self.warnings)?;
99        map.end()
100    }
101}
102
103/// Drop the provenance: the plain merged value, as `load()` returns it.
104impl From<TracedValue> for Value {
105    fn from(traced: TracedValue) -> Value {
106        match traced {
107            TracedValue::Leaf { value, .. } => value,
108            TracedValue::Object(entries) => {
109                Value::Object(entries.into_iter().map(|(k, v)| (k, v.into())).collect())
110            }
111        }
112    }
113}
114
115impl SourceRef {
116    /// The label used in serialized traces: the file path, or
117    /// `string:<index>` for string sources.
118    fn label(&self) -> String {
119        match self {
120            SourceRef::File(path) => path.to_string_lossy().into_owned(),
121            SourceRef::String(index) => format!("string:{index}"),
122            SourceRef::Value(index) => format!("value:{index}"),
123        }
124    }
125}
126
127impl serde::Serialize for TracedValue {
128    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
129    where
130        S: serde::Serializer,
131    {
132        use serde::ser::SerializeMap;
133        match self {
134            TracedValue::Leaf { value, source } => {
135                // "$id" tags the node kind: a plain config object could
136                // itself have value/source/format keys, and the tag makes
137                // json trace output self-describing for debugging
138                let mut map = serializer.serialize_map(Some(4))?;
139                map.serialize_entry("$id", "Leaf")?;
140                map.serialize_entry("value", value)?;
141                map.serialize_entry("source", &source.label())?;
142                map.serialize_entry("format", &value.format_id())?;
143                map.end()
144            }
145            TracedValue::Object(entries) => serializer.collect_map(entries),
146        }
147    }
148}