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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::collections::HashMap;
use std::error::Error;
use std::fmt::Display;
use std::str::FromStr;
use std::ops::{Index, IndexMut};

use crate::lexer::Lexer;
use crate::parser::Parser;

#[derive(Debug)]
pub enum JSONError {
    SyntaxError(String),
    LexerError(String),
    ParseError(String),
    ValueError(String),
    KeyError(String),
    IndexError(String),
}

impl Error for JSONError {}

impl Display for JSONError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SyntaxError(what) => write!(f, "JSON Syntax Error: {}", what),
            Self::LexerError(what) => write!(f, "JSON Lexer Error: {}", what),
            Self::ParseError(what) => write!(f, "JSON Parse Error: {}", what),
            Self::ValueError(what) => write!(f, "JSON Value Error: {}", what),
            Self::KeyError(what) => write!(f, "JSON Key Error: {}", what),
            Self::IndexError(what) => write!(f, "JSON Index Error: {}", what),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum JSONValue {
    Bool(bool),
    Number(f64),
    String(String),
    Array(Vec<JSONValue>),
    Object(HashMap<String, JSONValue>),
    Null,
}

pub type Result<T> = std::result::Result<T, JSONError>;

impl JSONValue {
    ///////////////////////////////////////////////
    // Functions that assume `self` is an Object //
    ///////////////////////////////////////////////

    pub fn get(&self, key: &str) -> Result<&JSONValue> {
        match self {
            Self::Object(vals) => {
                if let Some(val) = vals.get(key) {
                    Ok(val)
                } else {
                    Err(JSONError::KeyError(format!("key {} not found", key)))
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected object, found {:?}", other.name())))
            }
        }
    }
    pub fn get_mut(&mut self, key: &str) -> Result<&mut JSONValue> {
        match self {
            Self::Object(vals) => {
                if let Some(val) = vals.get_mut(key) {
                    Ok(val)
                } else {
                    Err(JSONError::KeyError(format!("key {} not found", key)))
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected object, found {:?}", other.name())))
            }
        }
    }
    pub fn obj_insert(&mut self, key: &str, value: JSONValue) -> Result<()> {
        match self {
            Self::Object(map) => {
                if let Some(_) = map.get_mut(key) {
                    Err(JSONError::KeyError(format!("key {} already in object", key)))
                } else {
                    map.insert(key.to_string(), value);
                    Ok(())
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected object, found {:?}", other.name())))
            }
        }
    }
    pub fn obj_remove(&mut self, key: &str) -> Result<(String, JSONValue)> {
        match self {
            Self::Object(map) => {
                if let Some(v) = map.remove(key) {
                    Ok((key.to_string(), v))
                } else {
                    Err(JSONError::KeyError(format!("key {} not found", key)))
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected object, found {:?}", other.name())))
            }
        }
    }


    //////////////////////////////////////////////
    // Functions that assume `self` is an Array //
    //////////////////////////////////////////////

    pub fn try_index(&self, index: usize) -> Result<&JSONValue> {
        match self {
            Self::Array(arr) => {
                if let Some(val) = arr.get(index) {
                    Ok(val)
                } else {
                    Err(JSONError::ValueError(format!("index {} out of bounds for length {}", index, arr.len())))
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected array, found {}", other.name())))
            }
        }
    }
    pub fn try_index_mut(&mut self, index: usize) -> Result<&mut JSONValue> {
        match self {
            Self::Array(arr) => {
                let len = arr.len().clone();

                if let Some(val) = arr.get_mut(index) {
                    Ok(val)
                } else {
                    Err(JSONError::ValueError(format!("index {} out of bounds for length {}", index, len)))
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected array, found {}", other.name())))
            }
        }
    }
    pub fn arr_push(&mut self, val: JSONValue) -> Result<()> {
        match self {
            Self::Array(arr) => {
                arr.push(val);
                Ok(())
            }
            other => {
                Err(JSONError::ValueError(format!("expected array, found {}", other.name())))
            }
        }
    }
    pub fn arr_pop(&mut self) -> Result<JSONValue> {
        match self {
            Self::Array(arr) => {
                if let Some(v) = arr.pop() {
                    Ok(v)
                } else {
                    Err(JSONError::ValueError("cannot pop an array of zero length".to_string()))
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected array, found {}", other.name())))
            }
        }
    }
    pub fn arr_insert(&mut self, pos: usize, val: JSONValue) -> Result<()> {
        match self {
            Self::Array(arr) => {
                let len = arr.len().clone();

                if pos > len {
                    Err(JSONError::IndexError(format!("index {} out of bounds for length {}", pos, len)))
                } else {
                    arr.insert(pos, val);

                    Ok(())
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected array, found {}", other.name())))
            }
        }
    }
    pub fn arr_remove(&mut self, pos: usize) -> Result<JSONValue> {
        match self {
            Self::Array(arr) => {
                let len = arr.len().clone();

                if pos > len {
                    Err(JSONError::IndexError(format!("index {} out of bounds for length {}", pos, len)))
                } else {
                    Ok(arr.remove(pos))
                }
            }
            other => {
                Err(JSONError::ValueError(format!("expected array, found {}", other.name())))
            }
        }
    }

    /// Constructs a JSON null value.
    #[inline]
    pub const fn null() -> Self {
        Self::Null
    }

    // helper function to assist with <JSONValue as Display>::fmt(). Allows printed
    // JSON text to auto-format spacing. 
    fn fmt_recursive(&self, f: &mut std::fmt::Formatter<'_>, level: usize) -> std::fmt::Result {
        match self {
            Self::Bool(b) => { write!(f, "{}", b)?; }
            Self::Number(n) => { write!(f, "{}", n)?; }
            Self::String(s) => { write!(f, "\"{}\"", s)?; }
            Self::Array(arr) => {
                let tab_width = level * 4;
                write!(f, "[\n")?;
                for i in 0..arr.len() {
                    write!(f, "    {: <1$}", "", tab_width)?;
                    arr[i].fmt_recursive(f, level + 1)?;
                    if i != arr.len() - 1 {
                        write!(f, ",")?;
                    }
                    write!(f, "\n")?;
                }
                write!(f, "{: <1$}]", "", tab_width)?;
            }
            Self::Object(obj) => {
                let tab_width = level * 4;
                write!(f, "{{\n")?;
                let mut i = 0;
                for key in obj.keys() {
                    write!(f, "    {: <1$}", "", tab_width)?;
                    write!(f, "\"{}\": ", key)?;
                    obj[key].fmt_recursive(f, level + 1)?;
                    if i != obj.len() - 1 {
                        write!(f, ",")?;
                        i += 1;
                    }
                    write!(f, "\n")?;
                }
                write!(f, "{: <1$}}}", "", tab_width)?;
            }
            Self::Null => { write!(f, "null")?; }
        }


        Ok(())
    }

    // used for debug messages
    fn name(&self) -> &'static str {
        match self {
            Self::Bool(_) => "boolean",
            Self::Number(_) => "number",
            Self::String(_) => "string",
            Self::Array(_) => "array",
            Self::Object(_) => "object",
            Self::Null => "null",
        }
    }
}

///////////////////////////////////
// JSON-to-Rust Type Conversions //
///////////////////////////////////

/// A helper trait that performs non-consuming type conversions from
/// JSONValues to Rust primitive types.
pub trait Cast<T> {
    fn cast(&self) -> Result<T>;
}

impl Cast<bool> for JSONValue {
    fn cast(&self) -> Result<bool> {
        match self {
            Self::Bool(b) => Ok(*b),
            other => Err(JSONError::ValueError(format!("expected boolean, found {:?}", other.name())))
        }
    }
}

impl Cast<f64> for JSONValue {
    fn cast(&self) -> Result<f64> {
        match self {
            Self::Number(v) => Ok(*v),
            other => Err(JSONError::ValueError(format!("expected number, found {:?}", other.name())))
        }
    }
}

impl Cast<String> for JSONValue {
    fn cast(&self) -> Result<String> {
        match self {
            Self::String(s) => Ok(s.clone()),
            other => Err(JSONError::ValueError(format!("expected string, found {:?}", other.name())))
        }
    }
}

macro_rules! impl_cast_int {
    {$($type_name:ty) +} => {
        $(impl Cast<$type_name> for JSONValue {
            fn cast(&self) -> crate::json::Result<$type_name> {
                match self {
                    Self::Number(v) => Ok(v.clone() as $type_name),
                    other => Err(JSONError::ValueError(format!("expected number, found {:?}", other.name()))),
                }
            }
        })+
    }
}

impl_cast_int!(i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32);

///////////////////////////////////
// Rust-to-JSON Type Conversions //
///////////////////////////////////

// equivalent to <Self as FromStr>::from_str(self, &Vec<u8>::to_string())
impl TryFrom<Vec<u8>> for JSONValue {
    type Error = JSONError;

    fn try_from(value: Vec<u8>) -> std::result::Result<Self, Self::Error> {
        Parser::from(
            Lexer::new(value).tokenify()?
        ).parse()
    }
}

impl From<f64> for JSONValue {
    fn from(value: f64) -> Self {
        Self::Number(value)
    }
}

// macro for auto-implementing From<> traits for numeric types
macro_rules! impl_from_int {
    {$($type_name:ty) +} => {
        $(impl From<$type_name> for JSONValue {
            fn from(value: $type_name) -> Self {
                Self::Number(value as f64)
            }
        })+
    }
}



impl_from_int!(i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32);

// NOTE: this directly constructs a JSONValue::String, and does not perform any parsing
impl From<String> for JSONValue {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<bool> for JSONValue {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<Vec<JSONValue>> for JSONValue {
    fn from(value: Vec<JSONValue>) -> Self {
        Self::Array(value)
    }
}


/// Constructs a JSON null value. Equivalent to Self::null()
impl From<()> for JSONValue {
    fn from(_: ()) -> Self {
        Self::Null
    }
}

impl<T> From<Option<T>> for JSONValue where JSONValue: From<T> {
    fn from(value: Option<T>) -> Self {
        match value {
            Some(v) => <Self as From<T>>::from(v),
            None => Self::Null,
        }
    }
} 

///////////////////////////////
// JSON-Text I/O Conversions //
///////////////////////////////

// conversion from raw json text into a JSONValue
impl FromStr for JSONValue {
    type Err = JSONError;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Self::try_from(s.as_bytes().to_vec())
    }
}

impl Display for JSONValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_recursive(f, 0)
    }
}

//////////////////////////////////////////
// Indexing without Result<> protection //
//////////////////////////////////////////

impl Index<&str> for JSONValue {
    type Output = JSONValue;
    fn index(&self, index: &str) -> &Self::Output {
        self.get(index).unwrap()
    }
}

impl IndexMut<&str> for JSONValue {
    fn index_mut(&mut self, index: &str) -> &mut Self::Output {
        self.get_mut(index).unwrap()
    }
}

impl Index<String> for JSONValue {
    type Output = JSONValue;
    fn index(&self, index: String) -> &Self::Output {
        self.get(&index).unwrap()
    }
}

impl IndexMut<String> for JSONValue {
    fn index_mut(&mut self, index: String) -> &mut Self::Output {
        self.get_mut(&index).unwrap()
    }
}

impl Index<usize> for JSONValue {
    type Output = JSONValue;
    fn index(&self, index: usize) -> &Self::Output {
        match self {
            JSONValue::Array(arr) => &arr[index],
            other => panic!("expected array, found {:?}", other.name()),
        }
    }
}

impl IndexMut<usize> for JSONValue {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        match self {
            JSONValue::Array(arr) => &mut arr[index],
            other => panic!("expected array, found {:?}", other.name()),
        }
    }
}

impl<T> PartialEq<T> for JSONValue
    where JSONValue: Cast<T>,
    T: PartialEq<T>,
{
    fn eq(&self, other: &T) -> bool {
        let res: Result<T> = self.cast();
        match res {
            Ok(v) => &v == other,
            Err(_) => false,
        }
    }
}