Skip to main content

cargo_util_config/
value.rs

1//! Deserialization of a [`Value<T>`] type which tracks where it was deserialized from.
2//!
3//! ## Rationale for `Value<T>`
4//!
5//! Often Cargo wants to report semantic error information or other sorts of
6//! error information about configuration keys but it also may wish to indicate
7//! as an error context where the key was defined as well (to help user
8//! debugging). The `Value<T>` type here can be used to deserialize a `T` value
9//! from configuration, but also record where it was deserialized from when it
10//! was read.
11//!
12//! Deserializing `Value<T>` is pretty special, and serde doesn't have built-in
13//! support for this operation. To implement this we extend serde's "data model"
14//! a bit. We configure deserialization of `Value<T>` to basically only work with
15//! our one deserializer using configuration.
16//!
17//! ## How `Value<T>` deserialization works
18//!
19//! `Value<T>` uses a custom protocol to inject source location information
20//! into serde's deserialization process:
21//!
22//! **Magic identifiers**: `Value<T>::deserialize` requests a struct with special
23//! [name](NAME) and [field names](FIELDS) that use invalid Rust syntax to avoid
24//! conflicts. This signals to Cargo's deserializer that location tracking is needed.
25//!
26//! **Custom deserializer response**: When Cargo's deserializer sees these magic
27//! identifiers, it switches to `ValueDeserializer` (from the [`de`] module)
28//! instead of normal struct deserialization.
29//!
30//! **Two-field protocol**: `ValueDeserializer` presents exactly two fields
31//! through map visiting:
32//! * The actual value (deserialized normally)
33//! * The definition context (encoded as a `(u32, String)` tuple acting as a
34//!   tagged union of [`Definition`] variants)
35//!
36//! This allows `Value<T>` to capture both the deserialized data and where it
37//! came from.
38//!
39//! **Note**: When modifying [`Definition`] variants, be sure to update both
40//! the `Definition::deserialize` implementation here and the
41//! `MapAccess::next_value_seed` implementation in `ValueDeserializer`.
42//!
43//! [`de`]: super::de
44
45use super::Definition;
46use serde::de;
47use std::fmt;
48use std::marker;
49
50/// A type which can be deserialized as a configuration value which records
51/// where it was deserialized from.
52#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
53#[derive(Debug, PartialEq, Clone, serde::Serialize)]
54#[serde(transparent)]
55pub struct Value<T> {
56    /// The inner value that was deserialized.
57    pub val: T,
58    /// The location where `val` was defined in configuration (e.g. file it was
59    /// defined in, env var etc).
60    #[serde(skip)]
61    pub definition: Definition,
62}
63
64pub type OptValue<T> = Option<Value<T>>;
65
66// The names below are intended to be invalid Rust identifiers
67// to avoid conflicts with other valid structures.
68pub(crate) const VALUE_FIELD: &str = "$__cargo_private_value";
69pub(crate) const DEFINITION_FIELD: &str = "$__cargo_private_definition";
70pub(crate) const NAME: &str = "$__cargo_private_Value";
71pub(crate) static FIELDS: [&str; 2] = [VALUE_FIELD, DEFINITION_FIELD];
72
73impl<T> From<T> for Value<T> {
74    fn from(val: T) -> Self {
75        Self {
76            val,
77            definition: Definition::builtin(),
78        }
79    }
80}
81
82impl<'de, T> de::Deserialize<'de> for Value<T>
83where
84    T: de::Deserialize<'de>,
85{
86    fn deserialize<D>(deserializer: D) -> Result<Value<T>, D::Error>
87    where
88        D: de::Deserializer<'de>,
89    {
90        struct ValueVisitor<T> {
91            _marker: marker::PhantomData<T>,
92        }
93
94        impl<'de, T> de::Visitor<'de> for ValueVisitor<T>
95        where
96            T: de::Deserialize<'de>,
97        {
98            type Value = Value<T>;
99
100            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
101                formatter.write_str("a value")
102            }
103
104            fn visit_map<V>(self, mut visitor: V) -> Result<Value<T>, V::Error>
105            where
106                V: de::MapAccess<'de>,
107            {
108                let value = visitor.next_key::<ValueKey>()?;
109                if value.is_none() {
110                    return Err(de::Error::custom("value not found"));
111                }
112                let val: T = visitor.next_value()?;
113
114                let definition = visitor.next_key::<DefinitionKey>()?;
115                if definition.is_none() {
116                    return Err(de::Error::custom("definition not found"));
117                }
118                let definition: Definition = visitor.next_value()?;
119                Ok(Value { val, definition })
120            }
121        }
122
123        deserializer.deserialize_struct(
124            NAME,
125            &FIELDS,
126            ValueVisitor {
127                _marker: marker::PhantomData,
128            },
129        )
130    }
131}
132
133struct FieldVisitor {
134    expected: &'static str,
135}
136
137impl<'de> de::Visitor<'de> for FieldVisitor {
138    type Value = ();
139
140    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
141        formatter.write_str("a valid value field")
142    }
143
144    fn visit_str<E>(self, s: &str) -> Result<(), E>
145    where
146        E: de::Error,
147    {
148        if s == self.expected {
149            Ok(())
150        } else {
151            Err(de::Error::custom("expected field with custom name"))
152        }
153    }
154}
155
156struct ValueKey;
157
158impl<'de> de::Deserialize<'de> for ValueKey {
159    fn deserialize<D>(deserializer: D) -> Result<ValueKey, D::Error>
160    where
161        D: de::Deserializer<'de>,
162    {
163        deserializer.deserialize_identifier(FieldVisitor {
164            expected: VALUE_FIELD,
165        })?;
166        Ok(ValueKey)
167    }
168}
169
170struct DefinitionKey;
171
172impl<'de> de::Deserialize<'de> for DefinitionKey {
173    fn deserialize<D>(deserializer: D) -> Result<DefinitionKey, D::Error>
174    where
175        D: de::Deserializer<'de>,
176    {
177        deserializer.deserialize_identifier(FieldVisitor {
178            expected: DEFINITION_FIELD,
179        })?;
180        Ok(DefinitionKey)
181    }
182}
183
184impl<'de> de::Deserialize<'de> for Definition {
185    fn deserialize<D>(deserializer: D) -> Result<Definition, D::Error>
186    where
187        D: de::Deserializer<'de>,
188    {
189        let (discr, value) = <(u32, String)>::deserialize(deserializer)?;
190        match discr {
191            0 => Ok(Definition::builtin()),
192            1 => Ok(Definition::path(value.into())),
193            2 => Ok(Definition::environment(value)),
194            3 => {
195                let path = (value.len() > 0).then_some(value.into());
196                Ok(Definition::cli(path))
197            }
198            _ => panic!("unexpected discriminant {discr} value {value}"),
199        }
200    }
201}