|
| 1 | +//! Deserialization of a `Value<T>` type which tracks where it was deserialized |
| 2 | +//! from. |
| 3 | +//! |
| 4 | +//! Often Cargo wants to report semantic error information or other sorts of |
| 5 | +//! error information about configuration keys but it also may wish to indicate |
| 6 | +//! as an error context where the key was defined as well (to help user |
| 7 | +//! debugging). The `Value<T>` type here can be used to deserialize a `T` value |
| 8 | +//! from configuration, but also record where it was deserialized from when it |
| 9 | +//! was read. |
| 10 | +
|
| 11 | +use crate::util::config::Config; |
| 12 | +use serde::de; |
| 13 | +use std::fmt; |
| 14 | +use std::marker; |
| 15 | +use std::mem; |
| 16 | +use std::path::{Path, PathBuf}; |
| 17 | + |
| 18 | +/// A type which can be deserialized as a configuration value which records |
| 19 | +/// where it was deserialized from. |
| 20 | +#[derive(Debug, PartialEq, Clone)] |
| 21 | +pub struct Value<T> { |
| 22 | + /// The inner value that was deserialized. |
| 23 | + pub val: T, |
| 24 | + /// The location where `val` was defined in configuration (e.g. file it was |
| 25 | + /// defined in, env var etc). |
| 26 | + pub definition: Definition, |
| 27 | +} |
| 28 | + |
| 29 | +pub type OptValue<T> = Option<Value<T>>; |
| 30 | + |
| 31 | +// Deserializing `Value<T>` is pretty special, and serde doesn't have built-in |
| 32 | +// support for this operation. To implement this we extend serde's "data model" |
| 33 | +// a bit. We configure deserialization of `Value<T>` to basically only work with |
| 34 | +// our one deserializer using configuration. |
| 35 | +// |
| 36 | +// We define that `Value<T>` deserialization asks the deserializer for a very |
| 37 | +// special struct name and struct field names. In doing so the deserializer will |
| 38 | +// recognize this and synthesize a magical value for the `definition` field when |
| 39 | +// we deserialize it. This protocol is how we're able to have a channel of |
| 40 | +// information flowing from the configuration deserializer into the |
| 41 | +// deserialization implementation here. |
| 42 | +// |
| 43 | +// You'll want to also check out the implementation of `ValueDeserializer` in |
| 44 | +// `de.rs`. Also note that the names below are intended to be invalid Rust |
| 45 | +// identifiers to avoid how they might conflict with other valid structures. |
| 46 | +// Finally the `definition` field is transmitted as a tuple of i32/string, which |
| 47 | +// is effectively a tagged union of `Definition` itself. |
| 48 | + |
| 49 | +pub(crate) const VALUE_FIELD: &str = "$__cargo_private_value"; |
| 50 | +pub(crate) const DEFINITION_FIELD: &str = "$__cargo_private_definition"; |
| 51 | +pub(crate) const NAME: &str = "$__cargo_private_Value"; |
| 52 | +pub(crate) static FIELDS: [&str; 2] = [VALUE_FIELD, DEFINITION_FIELD]; |
| 53 | + |
| 54 | +#[derive(Clone, Debug)] |
| 55 | +pub enum Definition { |
| 56 | + Path(PathBuf), |
| 57 | + Environment(String), |
| 58 | +} |
| 59 | + |
| 60 | +impl Definition { |
| 61 | + pub fn root<'a>(&'a self, config: &'a Config) -> &'a Path { |
| 62 | + match self { |
| 63 | + Definition::Path(p) => p.parent().unwrap().parent().unwrap(), |
| 64 | + Definition::Environment(_) => config.cwd(), |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +impl PartialEq for Definition { |
| 70 | + fn eq(&self, other: &Definition) -> bool { |
| 71 | + // configuration values are equivalent no matter where they're defined, |
| 72 | + // but they need to be defined in the same location. For example if |
| 73 | + // they're defined in the environment that's different than being |
| 74 | + // defined in a file due to path interepretations. |
| 75 | + mem::discriminant(self) == mem::discriminant(other) |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +impl fmt::Display for Definition { |
| 80 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 81 | + match self { |
| 82 | + Definition::Path(p) => p.display().fmt(f), |
| 83 | + Definition::Environment(key) => write!(f, "environment variable `{}`", key), |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +impl<'de, T> de::Deserialize<'de> for Value<T> |
| 89 | +where |
| 90 | + T: de::Deserialize<'de>, |
| 91 | +{ |
| 92 | + fn deserialize<D>(deserializer: D) -> Result<Value<T>, D::Error> |
| 93 | + where |
| 94 | + D: de::Deserializer<'de>, |
| 95 | + { |
| 96 | + struct ValueVisitor<T> { |
| 97 | + _marker: marker::PhantomData<T>, |
| 98 | + } |
| 99 | + |
| 100 | + impl<'de, T> de::Visitor<'de> for ValueVisitor<T> |
| 101 | + where |
| 102 | + T: de::Deserialize<'de>, |
| 103 | + { |
| 104 | + type Value = Value<T>; |
| 105 | + |
| 106 | + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 107 | + formatter.write_str("a value") |
| 108 | + } |
| 109 | + |
| 110 | + fn visit_map<V>(self, mut visitor: V) -> Result<Value<T>, V::Error> |
| 111 | + where |
| 112 | + V: de::MapAccess<'de>, |
| 113 | + { |
| 114 | + let value = visitor.next_key::<ValueKey>()?; |
| 115 | + if value.is_none() { |
| 116 | + return Err(de::Error::custom("value not found")); |
| 117 | + } |
| 118 | + let val: T = visitor.next_value()?; |
| 119 | + |
| 120 | + let definition = visitor.next_key::<DefinitionKey>()?; |
| 121 | + if definition.is_none() { |
| 122 | + return Err(de::Error::custom("definition not found")); |
| 123 | + } |
| 124 | + let definition: Definition = visitor.next_value()?; |
| 125 | + Ok(Value { val, definition }) |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + deserializer.deserialize_struct( |
| 130 | + NAME, |
| 131 | + &FIELDS, |
| 132 | + ValueVisitor { |
| 133 | + _marker: marker::PhantomData, |
| 134 | + }, |
| 135 | + ) |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +struct FieldVisitor { |
| 140 | + expected: &'static str, |
| 141 | +} |
| 142 | + |
| 143 | +impl<'de> de::Visitor<'de> for FieldVisitor { |
| 144 | + type Value = (); |
| 145 | + |
| 146 | + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 147 | + formatter.write_str("a valid value field") |
| 148 | + } |
| 149 | + |
| 150 | + fn visit_str<E>(self, s: &str) -> Result<(), E> |
| 151 | + where |
| 152 | + E: de::Error, |
| 153 | + { |
| 154 | + if s == self.expected { |
| 155 | + Ok(()) |
| 156 | + } else { |
| 157 | + Err(de::Error::custom("expected field with custom name")) |
| 158 | + } |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +struct ValueKey; |
| 163 | + |
| 164 | +impl<'de> de::Deserialize<'de> for ValueKey { |
| 165 | + fn deserialize<D>(deserializer: D) -> Result<ValueKey, D::Error> |
| 166 | + where |
| 167 | + D: de::Deserializer<'de>, |
| 168 | + { |
| 169 | + deserializer.deserialize_identifier(FieldVisitor { |
| 170 | + expected: VALUE_FIELD, |
| 171 | + })?; |
| 172 | + Ok(ValueKey) |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +struct DefinitionKey; |
| 177 | + |
| 178 | +impl<'de> de::Deserialize<'de> for DefinitionKey { |
| 179 | + fn deserialize<D>(deserializer: D) -> Result<DefinitionKey, D::Error> |
| 180 | + where |
| 181 | + D: de::Deserializer<'de>, |
| 182 | + { |
| 183 | + deserializer.deserialize_identifier(FieldVisitor { |
| 184 | + expected: DEFINITION_FIELD, |
| 185 | + })?; |
| 186 | + Ok(DefinitionKey) |
| 187 | + } |
| 188 | +} |
| 189 | + |
| 190 | +impl<'de> de::Deserialize<'de> for Definition { |
| 191 | + fn deserialize<D>(deserializer: D) -> Result<Definition, D::Error> |
| 192 | + where |
| 193 | + D: de::Deserializer<'de>, |
| 194 | + { |
| 195 | + let (discr, value) = <(u32, String)>::deserialize(deserializer)?; |
| 196 | + if discr == 0 { |
| 197 | + Ok(Definition::Path(value.into())) |
| 198 | + } else { |
| 199 | + Ok(Definition::Environment(value)) |
| 200 | + } |
| 201 | + } |
| 202 | +} |
0 commit comments