1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use crate::fromdynamic::{FromDynamicOptions, UnknownFieldAction};
use crate::object::Object;
use crate::value::Value;
use thiserror::Error;

#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
    #[error("`{}` is not a valid {} variant. {}", .variant_name, .type_name, Self::possible_matches(.variant_name, &.possible))]
    InvalidVariantForType {
        variant_name: String,
        type_name: &'static str,
        possible: &'static [&'static str],
    },
    #[error("`{}` is not a valid {} field. {}", .field_name, .type_name, Self::possible_matches(.field_name, &.possible))]
    UnknownFieldForStruct {
        field_name: String,
        type_name: &'static str,
        possible: &'static [&'static str],
    },
    #[error("{}", .0)]
    Message(String),
    #[error("Cannot coerce vec of size {} to array of size {}", .vec_size, .array_size)]
    ArraySizeMismatch { vec_size: usize, array_size: usize },
    #[error("Cannot convert `{}` to `{}`", .source_type, .dest_type)]
    NoConversion {
        source_type: String,
        dest_type: &'static str,
    },
    #[error("Expected char to be a string with a single character")]
    CharFromWrongSizedString,
    #[error("Expected a valid `{}` variant name as single key in object, but there are {} keys", .type_name, .num_keys)]
    IncorrectNumberOfEnumKeys {
        type_name: &'static str,
        num_keys: usize,
    },
    #[error("Error processing {}::{}: {:#}", .type_name, .field_name, .error)]
    ErrorInField {
        type_name: &'static str,
        field_name: &'static str,
        error: String,
    },
    #[error("Error processing {} (types: {}) {:#}", .field_name.join("."), .type_name.join(", "), .error)]
    ErrorInNestedField {
        type_name: Vec<&'static str>,
        field_name: Vec<&'static str>,
        error: String,
    },
    #[error("`{}` is not a valid type to use as a field name in `{}`", .key_type, .type_name)]
    InvalidFieldType {
        type_name: &'static str,
        key_type: String,
    },
    #[error("{}::{} is deprecated: {}", .type_name, .field_name, .reason)]
    DeprecatedField {
        type_name: &'static str,
        field_name: &'static str,
        reason: &'static str,
    },
}

impl Error {
    fn compute_unknown_fields(
        type_name: &'static str,
        object: &crate::Object,
        possible: &'static [&'static str],
    ) -> Vec<Self> {
        let mut errors = vec![];

        for key in object.keys() {
            match key {
                Value::String(s) => {
                    if !possible.contains(&s.as_str()) {
                        errors.push(Self::UnknownFieldForStruct {
                            field_name: s.to_string(),
                            type_name,
                            possible: possible.clone(),
                        });
                    }
                }
                other => {
                    errors.push(Self::InvalidFieldType {
                        type_name,
                        key_type: other.variant_name().to_string(),
                    });
                }
            }
        }

        errors
    }

    pub fn raise_deprecated_fields(
        options: FromDynamicOptions,
        type_name: &'static str,
        field_name: &'static str,
        reason: &'static str,
    ) -> Result<(), Self> {
        if options.deprecated_fields == UnknownFieldAction::Ignore {
            return Ok(());
        }
        let err = Self::DeprecatedField {
            type_name,
            field_name,
            reason,
        };

        match options.deprecated_fields {
            UnknownFieldAction::Deny => Err(err),
            UnknownFieldAction::Warn => {
                log::warn!("{:#}", err);
                Ok(())
            }
            UnknownFieldAction::Ignore => unreachable!(),
        }
    }

    pub fn raise_unknown_fields(
        options: FromDynamicOptions,
        type_name: &'static str,
        object: &crate::Object,
        possible: &'static [&'static str],
    ) -> Result<(), Self> {
        if options.unknown_fields == UnknownFieldAction::Ignore {
            return Ok(());
        }

        let errors = Self::compute_unknown_fields(type_name, object, possible);
        if errors.is_empty() {
            return Ok(());
        }

        let show_warning = options.unknown_fields == UnknownFieldAction::Warn || errors.len() > 1;

        if show_warning {
            for err in &errors {
                log::warn!("{:#}", err);
            }
        }

        if options.unknown_fields == UnknownFieldAction::Deny {
            for err in errors {
                return Err(err);
            }
        }

        Ok(())
    }

    fn possible_matches(used: &str, possible: &'static [&'static str]) -> String {
        // Produce similar field name list
        let mut candidates: Vec<(f64, &str)> = possible
            .iter()
            .map(|&name| (strsim::jaro_winkler(used, name), name))
            .filter(|(confidence, _)| *confidence > 0.8)
            .collect();
        candidates.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
        let suggestions: Vec<&str> = candidates.into_iter().map(|(_, name)| name).collect();

        // Filter the suggestions out of the allowed field names
        // and sort what remains.
        let mut fields: Vec<&str> = possible
            .iter()
            .filter(|&name| !suggestions.iter().any(|candidate| candidate == name))
            .copied()
            .collect();
        fields.sort_unstable();

        let mut message = String::new();

        match suggestions.len() {
            0 => {}
            1 => message.push_str(&format!("Did you mean `{}`?", suggestions[0])),
            _ => {
                message.push_str("Did you mean one of ");
                for (idx, candidate) in suggestions.iter().enumerate() {
                    if idx > 0 {
                        message.push_str(", ");
                    }
                    message.push('`');
                    message.push_str(candidate);
                    message.push('`');
                }
                message.push('?');
            }
        }
        if !fields.is_empty() {
            let limit = 5;
            if fields.len() > limit {
                message.push_str(
                    " There are too many alternatives to list here; consult the documentation!",
                );
            } else {
                if suggestions.is_empty() {
                    message.push_str("Possible alternatives are ");
                } else if suggestions.len() == 1 {
                    message.push_str(" The other option is ");
                } else {
                    message.push_str(" Other alternatives are ");
                }
                for (idx, candidate) in fields.iter().enumerate() {
                    if idx > 0 {
                        message.push_str(", ");
                    }
                    message.push('`');
                    message.push_str(candidate);
                    message.push('`');
                }
            }
        }

        message
    }

    pub fn field_context(
        self,
        type_name: &'static str,
        field_name: &'static str,
        obj: &Object,
    ) -> Self {
        let is_leaf = !matches!(self, Self::ErrorInField { .. });
        fn add_obj_context(is_leaf: bool, obj: &Object, message: String) -> String {
            if is_leaf {
                // Show the object as context.
                // However, some objects, like the main config, are very large and
                // it isn't helpful to show that, so only include it when the context
                // is more reasonable.
                let obj_str = format!("{:#?}", obj);
                if obj_str.len() > 128 || obj_str.lines().count() > 10 {
                    message
                } else {
                    format!("{}.\n{}", message, obj_str)
                }
            } else {
                message
            }
        }

        match self {
            Self::NoConversion { source_type, .. } if source_type == "Null" => Self::ErrorInField {
                type_name,
                field_name,
                error: add_obj_context(is_leaf, obj, format!("missing field `{}`", field_name)),
            },
            Self::ErrorInField {
                type_name: child_type,
                field_name: child_field,
                error,
            } => Self::ErrorInNestedField {
                type_name: vec![type_name, child_type],
                field_name: vec![field_name, child_field],
                error,
            },
            Self::ErrorInNestedField {
                type_name: mut child_type,
                field_name: mut child_field,
                error,
            } => Self::ErrorInNestedField {
                type_name: {
                    child_type.insert(0, type_name);
                    child_type
                },
                field_name: {
                    child_field.insert(0, field_name);
                    child_field
                },
                error,
            },
            _ => Self::ErrorInField {
                type_name,
                field_name,
                error: add_obj_context(is_leaf, obj, format!("{:#}", self)),
            },
        }
    }
}

impl From<String> for Error {
    fn from(s: String) -> Error {
        Error::Message(s)
    }
}