Skip to main content

cargo/context/
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`]: crate::context::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#[derive(Debug, PartialEq, Clone)]
53pub struct Value<T> {
54    /// The inner value that was deserialized.
55    pub val: T,
56    /// The location where `val` was defined in configuration (e.g. file it was
57    /// defined in, env var etc).
58    pub definition: Definition,
59}
60
61pub type OptValue<T> = Option<Value<T>>;
62
63// The names below are intended to be invalid Rust identifiers
64// to avoid conflicts with other valid structures.
65pub(crate) const VALUE_FIELD: &str = "$__cargo_private_value";
66pub(crate) const DEFINITION_FIELD: &str = "$__cargo_private_definition";
67pub(crate) const NAME: &str = "$__cargo_private_Value";
68pub(crate) static FIELDS: [&str; 2] = [VALUE_FIELD, DEFINITION_FIELD];
69
70impl<T> From<T> for Value<T> {
71    fn from(val: T) -> Self {
72        Self {
73            val,
74            definition: Definition::BuiltIn,
75        }
76    }
77}
78
79impl<'de, T> de::Deserialize<'de> for Value<T>
80where
81    T: de::Deserialize<'de>,
82{
83    fn deserialize<D>(deserializer: D) -> Result<Value<T>, D::Error>
84    where
85        D: de::Deserializer<'de>,
86    {
87        struct ValueVisitor<T> {
88            _marker: marker::PhantomData<T>,
89        }
90
91        impl<'de, T> de::Visitor<'de> for ValueVisitor<T>
92        where
93            T: de::Deserialize<'de>,
94        {
95            type Value = Value<T>;
96
97            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98                formatter.write_str("a value")
99            }
100
101            fn visit_map<V>(self, mut visitor: V) -> Result<Value<T>, V::Error>
102            where
103                V: de::MapAccess<'de>,
104            {
105                let value = visitor.next_key::<ValueKey>()?;
106                if value.is_none() {
107                    return Err(de::Error::custom("value not found"));
108                }
109                let val: T = visitor.next_value()?;
110
111                let definition = visitor.next_key::<DefinitionKey>()?;
112                if definition.is_none() {
113                    return Err(de::Error::custom("definition not found"));
114                }
115                let definition: Definition = visitor.next_value()?;
116                Ok(Value { val, definition })
117            }
118        }
119
120        deserializer.deserialize_struct(
121            NAME,
122            &FIELDS,
123            ValueVisitor {
124                _marker: marker::PhantomData,
125            },
126        )
127    }
128}
129
130struct FieldVisitor {
131    expected: &'static str,
132}
133
134impl<'de> de::Visitor<'de> for FieldVisitor {
135    type Value = ();
136
137    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
138        formatter.write_str("a valid value field")
139    }
140
141    fn visit_str<E>(self, s: &str) -> Result<(), E>
142    where
143        E: de::Error,
144    {
145        if s == self.expected {
146            Ok(())
147        } else {
148            Err(de::Error::custom("expected field with custom name"))
149        }
150    }
151}
152
153struct ValueKey;
154
155impl<'de> de::Deserialize<'de> for ValueKey {
156    fn deserialize<D>(deserializer: D) -> Result<ValueKey, D::Error>
157    where
158        D: de::Deserializer<'de>,
159    {
160        deserializer.deserialize_identifier(FieldVisitor {
161            expected: VALUE_FIELD,
162        })?;
163        Ok(ValueKey)
164    }
165}
166
167struct DefinitionKey;
168
169impl<'de> de::Deserialize<'de> for DefinitionKey {
170    fn deserialize<D>(deserializer: D) -> Result<DefinitionKey, D::Error>
171    where
172        D: de::Deserializer<'de>,
173    {
174        deserializer.deserialize_identifier(FieldVisitor {
175            expected: DEFINITION_FIELD,
176        })?;
177        Ok(DefinitionKey)
178    }
179}
180
181impl<'de> de::Deserialize<'de> for Definition {
182    fn deserialize<D>(deserializer: D) -> Result<Definition, D::Error>
183    where
184        D: de::Deserializer<'de>,
185    {
186        let (discr, value) = <(u32, String)>::deserialize(deserializer)?;
187        match discr {
188            0 => Ok(Definition::BuiltIn),
189            1 => Ok(Definition::Path(value.into())),
190            2 => Ok(Definition::Environment(value)),
191            3 => {
192                let path = (value.len() > 0).then_some(value.into());
193                Ok(Definition::Cli(path))
194            }
195            _ => panic!("unexpected discriminant {discr} value {value}"),
196        }
197    }
198}