Documentation
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*  Copyright (C) 2025 Saúl Valdelvira
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>. */

//! Json parser
//!
//! # Example
//! ```
//! use json::Json;
//!
//! let j = Json::deserialize(r#"{
//!     "array" : [ 1, 2, "3", null ],
//!     "true" : true,
//!     "nested" : {
//!         "inner" : []
//!     }
//! }"#).unwrap();
//!
//! let Json::Object(map) = j else { panic!() };
//! assert!(
//!     matches!(
//!         map.get("true"),
//!         Some(Json::True)));
//! ```

#![warn(clippy::pedantic)]
#![allow(clippy::missing_errors_doc, clippy::must_use_candidate)]
#![cfg_attr(not(feature = "std"), no_std)]

#[macro_use]
extern crate alloc;

mod prelude {
    pub use alloc::borrow::Cow;
    pub use alloc::boxed::Box;
    pub use alloc::string::{String, ToString};
    pub use alloc::vec::Vec;
    pub use core::fmt;

    #[cfg(feature = "std")]
    pub type Map<K, V> = std::collections::HashMap<K, V>;

    #[cfg(not(feature = "std"))]
    pub type Map<K, V> = alloc::collections::BTreeMap<K, V>;
}

use core::ops::{Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Sub, SubAssign};

use prelude::*;

mod lexer;
mod parser;

#[cfg(feature = "bindings")]
pub mod export;

mod error;

type Result<T> = core::result::Result<T, error::Error>;

/// Represents a JSON object
#[derive(Debug, PartialEq)]
pub enum Json {
    Array(Box<[Json]>),
    Object(Map<Box<str>, Json>),
    String(Box<str>),
    Number(f64),
    True,
    False,
    Null,
}

/// Configures the JSON parser
#[repr(C)]
#[derive(Clone, Copy)]
pub struct JsonConfig {
    /// Max depth for nested objects
    pub max_depth: u32,

    /// Allow trailing commas on objects and arrays
    pub allow_trailing_commas: bool,

    /// Allow comments withing the Json
    pub allow_comments: bool,
}

/// Default config used by [`Json::deserialize`]
const DEFAULT_CONFIG: JsonConfig = JsonConfig {
    max_depth: u32::MAX,
    allow_trailing_commas: false,
    allow_comments: false,
};

impl Default for JsonConfig {
    fn default() -> Self {
        DEFAULT_CONFIG
    }
}

impl Json {
    /// Deserializes the given string into a [Json] object
    ///
    /// ## Configuration used
    /// [`max_depth`](JsonConfig::max_depth) = [`u32::MAX`]
    ///
    /// [`recover_from_errors`](JsonConfig::recover_from_errors) = false
    #[inline]
    pub fn deserialize(text: impl AsRef<str>) -> Result<Json> {
        Json::deserialize_with_config(text, DEFAULT_CONFIG)
    }
    /// Deserializes the given string into a [Json] object
    /// using the given [`JsonConfig`]
    pub fn deserialize_with_config(text: impl AsRef<str>, conf: JsonConfig) -> Result<Json> {
        let text = text.as_ref();
        let tokens = lexer::tokenize(text, conf)?;
        parser::parse(text, &tokens, conf)
    }
    /// Serializes the JSON object into a [`fmt::Write`]
    pub fn serialize(&self, out: &mut dyn fmt::Write) -> fmt::Result {
        match self {
            Json::Array(elements) => {
                out.write_char('[')?;
                for i in 0..elements.len() {
                    elements[i].serialize(out)?;
                    if i < elements.len() - 1 {
                        out.write_char(',')?;
                    }
                }
                out.write_char(']')?;
            }
            Json::Object(obj) => {
                out.write_char('{')?;
                let mut first = true;
                for (k, v) in obj {
                    if !first {
                        out.write_char(',')?;
                    }
                    first = false;
                    write!(out, "\"{k}\":")?;
                    v.serialize(out)?;
                }
                out.write_char('}')?;
            }
            Json::String(s) => {
                write!(out, "\"{s}\"")?;
            }
            Json::Number(n) => {
                write!(out, "{n}")?;
            }
            Json::True => out.write_str("true")?,
            Json::False => out.write_str("false")?,
            Json::Null => out.write_str("null")?,
        }
        Ok(())
    }
    /// Attempts to get a value of the given json object.
    /// If the json enum is not an Object variant, or if
    /// it doesn't contain the key, returns None
    #[inline]
    pub fn get(&self, key: impl AsRef<str>) -> Option<&Json> {
        self.object().and_then(|obj| obj.get(key.as_ref()))
    }
    /// Same as [get](Self::get), but with a mutable reference
    #[inline]
    pub fn get_mut(&mut self, key: impl AsRef<str>) -> Option<&mut Json> {
        self.object_mut().and_then(|obj| obj.get_mut(key.as_ref()))
    }
    /// Attempts to get a value of the given json array.
    /// If the json enum is not an Array variant, or if
    /// it doesn't contain the key, returns None
    #[inline]
    pub fn nth(&self, i: usize) -> Option<&Json> {
        self.array().and_then(|arr| arr.get(i))
    }
    /// Same as [nth](Self::nth), but with a mutable reference
    #[inline]
    pub fn nth_mut(&mut self, i: usize) -> Option<&mut Json> {
        self.array_mut().and_then(|arr| arr.get_mut(i))
    }

    /// Attempts to get the inner [`Number`] of the json
    /// object, if it is a [`Number`] variant
    ///
    /// [`Number`]: Json::Number
    #[inline]
    pub const fn number(&self) -> Option<f64> {
        if let Json::Number(n) = self {
            Some(*n)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`Number`] variant
    ///
    /// # Panics
    /// If the json object is not a [`Number`] variant
    ///
    /// [`Number`]: Json::Number
    #[inline]
    pub const fn expect_number(&self) -> f64 {
        self.number().unwrap()
    }
    /// Attempts to get a mutable reference to the inner [`Number`]
    /// of the json object, if it is a [`Number`] variant
    ///
    /// [`Number`]: Json::Number
    #[inline]
    pub const fn number_mut(&mut self) -> Option<&mut f64> {
        if let Json::Number(n) = self {
            Some(n)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`Number`] variant
    /// and gets a mutable reference to the inner number.
    ///
    /// # Panics
    /// If the json object is not a [`Number`] variant
    ///
    /// [`Number`]: Json::Number
    #[inline]
    pub const fn expect_number_mut(&mut self) -> &mut f64 {
        self.number_mut().unwrap()
    }

    /// Attempts to get the inner [`String`] of the json
    /// object, if it is a [`String`] variant
    ///
    /// [`String`]: Json::String
    #[inline]
    pub const fn string(&self) -> Option<&str> {
        if let Json::String(s) = self {
            Some(s)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`String`] variant
    ///
    /// # Panics
    /// If the json object is not a [`String`] variant
    ///
    /// [`String`]: Json::String
    #[inline]
    pub const fn expect_string(&self) -> &str {
        self.string().unwrap()
    }
    /// Attempts to get a mutable reference to the inner
    /// [`String`] of the json object, if it is a [`String`] variant
    ///
    /// [`String`]: Json::String
    #[inline]
    pub const fn string_mut(&mut self) -> Option<&mut str> {
        if let Json::String(s) = self {
            Some(s)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`String`] variant
    /// and gets a reference to the inner string
    ///
    /// # Panics
    /// If the json object is not a [`String`] variant
    ///
    /// [`String`]: Json::String
    #[inline]
    pub const fn expect_string_mut(&mut self) -> &mut str {
        self.string_mut().unwrap()
    }

    /// Attempts to get the inner Object of the json object, if
    /// it is an Object variant
    #[inline]
    pub const fn object(&self) -> Option<&Map<Box<str>, Json>> {
        if let Json::Object(o) = self {
            Some(o)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`Object`] variant
    /// and gets a reference to the inner object
    ///
    /// # Panics
    /// If the json object is not a [`Object`] variant
    ///
    /// [`Object`]: Json::Object
    #[inline]
    pub const fn expect_object(&self) -> &Map<Box<str>, Json> {
        self.object().unwrap()
    }
    /// Attempts to get a mutable reference to the inner [`Object`] of
    /// the json element, if it is an [`Object`] variant
    ///
    /// [`Object`]: Json::Object
    #[inline]
    pub const fn object_mut(&mut self) -> Option<&mut Map<Box<str>, Json>> {
        if let Json::Object(o) = self {
            Some(o)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`Object`] variant
    /// and gets a mutable reference to the inner object
    ///
    /// # Panics
    /// If the json object is not a [`Object`] variant
    ///
    /// [`Object`]: Json::Object
    #[inline]
    pub const fn expect_object_mut(&mut self) -> &mut Map<Box<str>, Json> {
        self.object_mut().unwrap()
    }

    /// Attempts to get the inner Array of the json object, if
    /// it is an Array variant
    #[inline]
    pub const fn array(&self) -> Option<&[Json]> {
        if let Json::Array(o) = self {
            Some(o)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`Array`] variant
    ///
    /// # Panics
    /// If the json object is not a [`Array`] variant
    ///
    /// [`Array`]: Json::Array
    #[inline]
    pub const fn expect_array(&self) -> &[Json] {
        self.array().unwrap()
    }
    /// Attempts to get the inner Array of the json object, if
    /// it is an Array variant
    #[inline]
    pub const fn array_mut(&mut self) -> Option<&mut [Json]> {
        if let Json::Array(o) = self {
            Some(o)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`Array`] variant
    ///
    /// # Panics
    /// If the json object is not a [`Array`] variant
    ///
    /// [`Array`]: Json::Array
    #[inline]
    pub const fn expect_array_mut(&mut self) -> &mut [Json] {
        self.array_mut().unwrap()
    }

    /// Attempts to get the inner boolean value of the json object, if
    /// it is a True or False variant
    #[inline]
    pub const fn boolean(&self) -> Option<bool> {
        if let Json::True = self {
            Some(true)
        } else if let Json::False = self {
            Some(false)
        } else {
            None
        }
    }
    /// Expects the json object to be a [`True`] or [`False`] variant
    ///
    /// # Panics
    /// If the json object is not a [`True`] or [`False`] variant
    ///
    /// [`True`]: Json::True
    /// [`False`]: Json::False
    #[inline]
    pub const fn expect_boolean(&self) -> bool {
        self.boolean().unwrap()
    }

    /// Returns true if the json is a Nil variant
    #[inline]
    pub const fn is_null(&self) -> bool {
        matches!(self, Json::Null)
    }
}

impl fmt::Display for Json {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.serialize(f)
    }
}

macro_rules! from_num {
    ( $( $nty:ty ),* ) => {
        $(
            impl From<$nty> for Json {
                fn from(value: $nty) -> Self {
                    Self::Number(value.into())
                }
            }

            impl AddAssign<$nty> for Json {
                fn add_assign(&mut self, rhs: $nty) {
                    *self.expect_number_mut() += f64::from(rhs);
                }
            }

            impl Add<$nty> for Json {
                type Output = Json;

                fn add(self, rhs: $nty) -> Self::Output {
                    Json::Number(self.expect_number() + f64::from(rhs))
                }
            }

            impl SubAssign<$nty> for Json {
                fn sub_assign(&mut self, rhs: $nty) {
                    *self.expect_number_mut() -= f64::from(rhs);
                }
            }

            impl Sub<$nty> for Json {
                type Output = Json;

                fn sub(self, rhs: $nty) -> Self::Output {
                    Json::Number(self.expect_number() - f64::from(rhs))
                }
            }

            impl MulAssign<$nty> for Json {
                fn mul_assign(&mut self, rhs: $nty) {
                    *self.expect_number_mut() *= f64::from(rhs);
                }
            }

            impl Mul<$nty> for Json {
                type Output = Json;

                fn mul(self, rhs: $nty) -> Self::Output {
                    Json::Number(self.expect_number() * f64::from(rhs))
                }
            }

            impl DivAssign<$nty> for Json {
                fn div_assign(&mut self, rhs: $nty) {
                    *self.expect_number_mut() /= f64::from(rhs);
                }
            }

            impl Div<$nty> for Json {
                type Output = Json;

                fn div(self, rhs: $nty) -> Self::Output {
                    Json::Number(self.expect_number() / f64::from(rhs))
                }
            }
        )*
    };
}

from_num!(f64, f32, i32, i16, u16, u8);

impl From<String> for Json {
    fn from(value: String) -> Self {
        Self::String(value.into_boxed_str())
    }
}

impl From<Box<str>> for Json {
    fn from(value: Box<str>) -> Self {
        Self::String(value)
    }
}

impl<'a> From<&'a str> for Json {
    fn from(value: &'a str) -> Self {
        Self::String(value.into())
    }
}

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

impl From<Map<Box<str>, Json>> for Json {
    fn from(value: Map<Box<str>, Json>) -> Self {
        Self::Object(value)
    }
}

impl From<bool> for Json {
    fn from(value: bool) -> Self {
        if value { Json::True } else { Json::False }
    }
}

impl Index<&str> for Json {
    type Output = Json;

    fn index(&self, index: &str) -> &Self::Output {
        self.get(index).unwrap_or_else(|| {
            panic!("Attemp to index a json element that doesn't contain the given key: '{index}'")
        })
    }
}

impl IndexMut<&str> for Json {
    fn index_mut(&mut self, index: &str) -> &mut Self::Output {
        self.get_mut(index).unwrap_or_else(|| {
            panic!("Attemp to index a json element that doesn't contain the given key: '{index}'")
        })
    }
}

impl Index<usize> for Json {
    type Output = Json;

    fn index(&self, index: usize) -> &Self::Output {
        self.nth(index).unwrap_or_else(|| {
            panic!("Attemp to index a json element that can't be indexed by {index}")
        })
    }
}

impl IndexMut<usize> for Json {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.nth_mut(index).unwrap_or_else(|| {
            panic!("Attemp to index a json element that can't be indexed by {index}")
        })
    }
}

#[doc(hidden)]
pub use prelude::Map;

/// Builds a [Json] object
///
/// # Example
/// ```
/// use json::json;
///
/// let j = json!({
///     "hello" : ["w", 0, "r", "ld"],
///     "array" : [
///         { "key" : "val" },
///         12.21,
///         null,
///         true,
///         false
///     ]
/// });
/// ```
#[macro_export]
macro_rules! json {
    ( $lit:literal ) => {
        $crate::Json::from( $lit )
    };
    ( { $e:expr } ) => {
        $crate::Json::from( $e )
    };
    ( [ $( $e:tt ),* $(,)? ] ) => {
        $crate::Json::from(
            vec![
                $(
                    json!($e)
                ),*
            ]
        )
    };
    ( { $( $key:literal : $val:tt ),* $(,)? } ) => {
        {
            let mut map = $crate::Map::new();
            $( map.insert($key .into(), json!($val) );  )*
            $crate::Json::from ( map )
        }
    };
    ( null ) => {
        $crate::Json::Null
    }
}