1use serde_json::Value;
17
18use crate::source_map::DocPath;
19
20pub fn error_path(root: &Value, error: &serde_json::Error) -> DocPath {
23 let message = error.to_string();
24 find(root, &message).unwrap_or_default()
25}
26
27pub fn error_path_text(root: &Value, error: &serde_json::Error) -> String {
30 let path = error_path(root, error);
31 if path.is_root() { ".".to_owned() } else { path.to_string() }
32}
33
34fn quoted<'a>(message: &'a str, prefix: &str) -> Option<&'a str> {
36 let rest = message.strip_prefix(prefix)?.strip_prefix('`')?;
37 rest.split_once('`').map(|(name, _)| name)
38}
39
40fn find(root: &Value, message: &str) -> Option<DocPath> {
41 if let Some(field) = quoted(message, "unknown field ") {
42 return first(root, &mut |value, _| value.as_object().is_some_and(|object| object.contains_key(field)))
43 .map(|path| path.key(field));
44 }
45 if let Some(field) = quoted(message, "missing field ") {
46 return missing(root, field);
47 }
48 if let Some(variant) = quoted(message, "unknown variant ") {
49 return first(root, &mut |value, _| match value {
50 Value::String(text) => text == variant,
51 Value::Object(object) => object.len() == 1 && object.contains_key(variant),
52 _ => false,
53 });
54 }
55 if let Some(length) = message.strip_prefix("invalid length ").and_then(|rest| rest.split_once(',')) {
56 let length: usize = length.0.parse().ok()?;
57 return unique(root, &mut |value| value.as_array().is_some_and(|items| items.len() == length));
58 }
59 let unexpected = message
60 .strip_prefix("invalid type: ")
61 .or_else(|| message.strip_prefix("invalid value: "))
62 .and_then(|rest| rest.rsplit_once(", expected "))
63 .map(|(unexpected, _)| unexpected)?;
64 match unexpected {
65 "map" => unique(root, &mut Value::is_object),
66 "sequence" => unique(root, &mut Value::is_array),
67 "null" | "unit value" => first(root, &mut |value, _| value.is_null()),
68 _ => first(root, &mut |value, _| describes(unexpected, value)),
69 }
70}
71
72fn describes(unexpected: &str, value: &Value) -> bool {
74 match value {
75 Value::String(text) => unexpected.strip_prefix("string ").is_some_and(|quoted| quoted == format!("{text:?}")),
76 Value::Bool(flag) => unexpected == format!("boolean `{flag}`"),
77 Value::Number(number) => {
78 let shown = number.to_string();
79 [format!("integer `{shown}`"), format!("floating point `{shown}`")].iter().any(|text| text == unexpected)
80 || number.as_f64().is_some_and(|float| unexpected == format!("floating point `{float}`"))
81 }
82 _ => false,
83 }
84}
85
86fn walk(value: &Value, path: &DocPath, visit: &mut dyn FnMut(&Value, &DocPath) -> bool) -> bool {
88 if visit(value, path) {
89 return true;
90 }
91 match value {
92 Value::Object(object) => object.iter().any(|(key, child)| walk(child, &path.key(key), visit)),
93 Value::Array(items) => items.iter().enumerate().any(|(index, child)| walk(child, &path.index(index), visit)),
94 _ => false,
95 }
96}
97
98fn first(root: &Value, matches: &mut dyn FnMut(&Value, &DocPath) -> bool) -> Option<DocPath> {
99 let mut found = None;
100 walk(root, &DocPath::root(), &mut |value, path| {
101 let hit = matches(value, path);
102 if hit {
103 found = Some(path.clone());
104 }
105 hit
106 });
107 found
108}
109
110fn unique(root: &Value, matches: &mut dyn FnMut(&Value) -> bool) -> Option<DocPath> {
112 let mut found = Vec::new();
113 walk(root, &DocPath::root(), &mut |value, path| {
114 if !path.is_root() && matches(value) {
115 found.push(path.clone());
116 }
117 found.len() > 1
118 });
119 if found.len() == 1 { found.pop() } else { None }
120}
121
122fn missing(root: &Value, field: &str) -> Option<DocPath> {
126 let lacks = |value: &Value| value.as_object().is_some_and(|object| !object.contains_key(field));
127 let in_array = first(root, &mut |value, _| {
128 value.as_array().is_some_and(|items| {
129 items.iter().any(lacks) && items.iter().any(|item| item.as_object().is_some_and(|o| o.contains_key(field)))
130 })
131 });
132 if let Some(array) = in_array {
133 let items = lookup(root, &array)?.as_array()?;
134 let index = items.iter().position(lacks)?;
135 return Some(array.index(index));
136 }
137 if lacks(root) {
138 return None;
139 }
140 unique(root, &mut |value| lacks(value))
141}
142
143fn lookup<'a>(root: &'a Value, path: &DocPath) -> Option<&'a Value> {
144 use crate::source_map::PathSegment;
145 path.segments().iter().try_fold(root, |value, segment| match segment {
146 PathSegment::Key(key) => value.get(key),
147 PathSegment::Index(index) => value.get(index),
148 })
149}
150
151#[cfg(test)]
152mod tests {
153 use serde::Deserialize;
154 use serde_json::json;
155
156 use super::*;
157
158 #[derive(Debug, Deserialize)]
159 #[serde(deny_unknown_fields)]
160 #[allow(dead_code)]
161 struct Variable {
162 name: String,
163 #[serde(default)]
164 value_selector: Vec<String>,
165 #[serde(default)]
166 kind: Option<Kind>,
167 }
168
169 #[derive(Debug, Deserialize)]
170 #[serde(rename_all = "snake_case")]
171 enum Kind {
172 Text,
173 Number,
174 }
175
176 #[derive(Debug, Deserialize)]
177 #[serde(deny_unknown_fields)]
178 #[allow(dead_code)]
179 struct Config {
180 #[serde(default)]
181 variables: Vec<Variable>,
182 #[serde(default)]
183 timeout_secs: u64,
184 #[serde(default)]
185 pair: Option<(u32, u32)>,
186 }
187
188 fn path_of(value: Value) -> String {
189 let error = serde_json::from_value::<Config>(value.clone()).unwrap_err();
190 error_path_text(&value, &error)
191 }
192
193 #[test]
194 fn names_the_offending_path_like_a_tracking_deserializer() {
195 assert_eq!(path_of(json!({ "variables": [{ "name": "a" }, { "name": "b", "valu": 1 }] })), "variables[1].valu");
196 assert_eq!(path_of(json!({ "variables": [{ "name": "a" }, { "value_selector": [] }] })), "variables[1]");
197 assert_eq!(
198 path_of(json!({ "variables": [{ "name": "a", "value_selector": ["x", 5] }] })),
199 "variables[0].value_selector[1]"
200 );
201 assert_eq!(path_of(json!({ "variables": [{ "name": "a", "kind": "date" }] })), "variables[0].kind");
202 assert_eq!(path_of(json!({ "timeout_secs": "soon" })), "timeout_secs");
203 assert_eq!(path_of(json!({ "timeout_secs": -1 })), "timeout_secs");
204 assert_eq!(path_of(json!({ "timeout_secs": 1.5 })), "timeout_secs");
205 assert_eq!(path_of(json!({ "pair": [1, 2, 3] })), "pair");
206 assert_eq!(path_of(json!({ "variables": [{ "name": true }] })), "variables[0].name");
207 assert_eq!(path_of(json!({ "extra": 1 })), "extra");
208 }
209
210 #[test]
211 fn falls_back_to_the_root() {
212 assert_eq!(path_of(json!({ "variables": {} })), "variables");
213 let error = serde_json::Error::io(std::io::Error::other("custom"));
214 assert!(error_path(&json!({}), &error).is_root());
215 }
216}