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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use core::fmt;
use std::{collections::BTreeMap, marker::PhantomData, str::FromStr};

use crate::{array::JsonArray, code_map::Mapped, CodeMap, Kind, KindSet, Object, Value};

/// Conversion from JSON syntax, with code mapping info.
///
/// This trait is very similar to [`TryFrom<Value>`] but also passes code
/// code mapping info to the conversion function.
pub trait TryFromJson: Sized {
	/// Error that may be returned by the conversion function.
	type Error;

	/// Tries to convert the given JSON value into `Self`, using the given
	/// `code_map`.
	///
	/// It is assumed that the offset of `value` in the code map is `0`, for
	/// instance if it is the output of a [`Parse`](crate::Parse) trait
	/// function.
	fn try_from_json(value: &Value, code_map: &CodeMap) -> Result<Self, Self::Error> {
		Self::try_from_json_at(value, code_map, 0)
	}

	/// Tries to convert the given JSON value into `Self`, using the given
	/// `code_map` and the offset of `value` in the code map.
	///
	/// Note to implementors: use the [`JsonArray::iter_mapped`] and
	/// [`Object::iter_mapped`] methods to visit arrays and objects while
	/// keeping track of the code map offset of each visited item.
	fn try_from_json_at(
		value: &Value,
		code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error>;
}

impl<T: TryFromJson> TryFromJson for Box<T> {
	type Error = T::Error;

	fn try_from_json_at(
		json: &Value,
		code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error> {
		T::try_from_json_at(json, code_map, offset).map(Box::new)
	}
}

impl<T: TryFromJson> TryFromJson for Option<T> {
	type Error = T::Error;

	fn try_from_json_at(
		json: &Value,
		code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error> {
		match json {
			Value::Null => Ok(None),
			other => T::try_from_json_at(other, code_map, offset).map(Some),
		}
	}
}

/// Conversion from JSON syntax object, with code mapping info.
///
/// This trait is very similar to [`TryFrom<Object>`] but also passes code
/// code mapping info to the conversion function.
pub trait TryFromJsonObject: Sized {
	type Error;

	/// Tries to convert the given JSON object into `Self`, using the given
	/// `code_map`.
	///
	/// It is assumed that the offset of `object` in the code map is `0`, for
	/// instance if it is the output of a [`Parse`](crate::Parse) trait
	/// function.
	fn try_from_json_object(object: &Object, code_map: &CodeMap) -> Result<Self, Self::Error> {
		Self::try_from_json_object_at(object, code_map, 0)
	}

	/// Tries to convert the given JSON object into `Self`, using the given
	/// `code_map` and the offset of `object` in the code map.
	///
	/// Note to implementors: use the [`JsonArray::iter_mapped`] and
	/// [`Object::iter_mapped`] methods to visit arrays and objects while
	/// keeping track of the code map offset of each visited item.
	fn try_from_json_object_at(
		object: &Object,
		code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error>;
}

impl<T: TryFromJsonObject> TryFromJsonObject for Box<T> {
	type Error = T::Error;

	fn try_from_json_object_at(
		object: &Object,
		code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error> {
		T::try_from_json_object_at(object, code_map, offset).map(Box::new)
	}
}

/// Unexpected JSON value kind error.
///
/// This error may be returned by [`TryFromJson`] and [`TryFromJsonObject`]
/// when trying to convert a value of the wrong [`Kind`].
#[derive(Debug)]
pub struct Unexpected {
	/// Expected kind(s).
	pub expected: KindSet,

	/// Found kind.
	pub found: Kind,
}

impl fmt::Display for Unexpected {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(
			f,
			"expected {}, found {}",
			self.expected.as_disjunction(),
			self.found
		)
	}
}

impl TryFromJson for () {
	type Error = Mapped<Unexpected>;

	fn try_from_json_at(
		json: &Value,
		_code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error> {
		match json {
			Value::Null => Ok(()),
			other => Err(Mapped::new(
				offset,
				Unexpected {
					expected: KindSet::NULL,
					found: other.kind(),
				},
			)),
		}
	}
}

impl TryFromJson for bool {
	type Error = Mapped<Unexpected>;

	fn try_from_json_at(
		json: &Value,
		_code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error> {
		match json {
			Value::Boolean(value) => Ok(*value),
			other => Err(Mapped::new(
				offset,
				Unexpected {
					expected: KindSet::BOOLEAN,
					found: other.kind(),
				},
			)),
		}
	}
}

pub struct NumberType<T>(PhantomData<T>);

impl<T> Clone for NumberType<T> {
	fn clone(&self) -> Self {
		*self
	}
}

impl<T> Copy for NumberType<T> {}

impl<T> Default for NumberType<T> {
	fn default() -> Self {
		Self(PhantomData)
	}
}

impl<T> fmt::Debug for NumberType<T> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "NumberType")
	}
}

impl<T> fmt::Display for NumberType<T> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "NumberType")
	}
}

pub enum TryIntoNumberError<T> {
	Unexpected(Unexpected),
	OutOfBounds(T),
}

impl<T> TryIntoNumberError<T> {
	pub fn map<U>(self, f: impl FnOnce(T) -> U) -> TryIntoNumberError<U> {
		match self {
			Self::Unexpected(e) => TryIntoNumberError::Unexpected(e),
			Self::OutOfBounds(t) => TryIntoNumberError::OutOfBounds(f(t)),
		}
	}
}

impl std::error::Error for Unexpected {}

macro_rules! number_from_json {
	($($ty:ident),*) => {
		$(
			impl TryFromJson for $ty {
				type Error = Mapped<TryIntoNumberError<NumberType<$ty>>>;

				fn try_from_json_at(json: &Value, _code_map: &CodeMap, offset: usize) -> Result<Self, Self::Error> {
					match json {
						Value::Number(value) => value.parse().map_err(|_| Mapped::new(offset, TryIntoNumberError::OutOfBounds(NumberType::default()))),
						other => Err(Mapped::new(offset, TryIntoNumberError::Unexpected(Unexpected {
							expected: KindSet::NUMBER,
							found: other.kind()
						})))
					}
				}
			}
		)*
	};
}

number_from_json!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);

impl TryFromJson for String {
	type Error = Mapped<Unexpected>;

	fn try_from_json_at(
		json: &Value,
		_code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error> {
		match json {
			Value::String(value) => Ok(value.to_string()),
			other => Err(Mapped::new(
				offset,
				Unexpected {
					expected: KindSet::STRING,
					found: other.kind(),
				},
			)),
		}
	}
}

impl<T: TryFromJson> TryFromJson for Vec<T>
where
	T::Error: From<Mapped<Unexpected>>,
{
	type Error = T::Error;

	fn try_from_json_at(
		json: &Value,
		code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error> {
		match json {
			Value::Array(value) => value
				.iter_mapped(code_map, offset)
				.map(|item| T::try_from_json_at(item.value, code_map, item.offset))
				.collect::<Result<Vec<_>, _>>(),
			other => Err(Mapped::new(
				offset,
				Unexpected {
					expected: KindSet::ARRAY,
					found: other.kind(),
				},
			)
			.into()),
		}
	}
}

impl<K: FromStr + Ord, V: TryFromJson> TryFromJson for BTreeMap<K, V>
where
	V::Error: From<Mapped<Unexpected>> + From<Mapped<K::Err>>,
{
	type Error = V::Error;

	fn try_from_json_at(
		json: &Value,
		code_map: &CodeMap,
		offset: usize,
	) -> Result<Self, Self::Error> {
		match json {
			Value::Object(object) => {
				let mut result = BTreeMap::new();

				for entry in object.iter_mapped(code_map, offset) {
					result.insert(
						entry
							.value
							.key
							.value
							.parse()
							.map_err(|e| Mapped::new(entry.value.key.offset, e))?,
						V::try_from_json_at(
							entry.value.value.value,
							code_map,
							entry.value.value.offset,
						)?,
					);
				}

				Ok(result)
			}
			other => Err(Mapped::new(
				offset,
				Unexpected {
					expected: KindSet::OBJECT,
					found: other.kind(),
				},
			)
			.into()),
		}
	}
}