Skip to main content

oak_json/language/
mod.rs

1#![doc = include_str!("readme.md")]
2#[cfg(feature = "serde")]
3mod de;
4#[cfg(feature = "serde")]
5mod ser;
6#[cfg(feature = "serde")]
7pub use self::{de::deserialize, de::from_str, ser::serialize, ser::to_string};
8use oak_core::{Language, LanguageCategory};
9
10/// The JSON language definition.
11#[derive(Debug, Clone, PartialEq, Eq, Hash)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13pub struct JsonLanguage {
14    /// Whether to allow trailing commas in objects and arrays
15    pub trailing_comma: bool,
16    /// Whether to allow bare keys (unquoted keys) in objects
17    pub bare_keys: bool,
18    /// Whether to allow single-quoted strings
19    pub single_quotes: bool,
20    /// Whether to allow comments (both line and block)
21    pub comments: bool,
22    /// Whether to allow hexadecimal numbers (e.g., 0xDEADBEEF)
23    pub hex_numbers: bool,
24    /// Whether to allow Infinity, -Infinity, and NaN
25    pub infinity_and_nan: bool,
26}
27
28impl Default for JsonLanguage {
29    fn default() -> Self {
30        Self::standard()
31    }
32}
33
34impl JsonLanguage {
35    /// Create a new instance of the JSON language with custom settings.
36    pub fn new(trailing_comma: bool, bare_keys: bool, single_quotes: bool, comments: bool, hex_numbers: bool, infinity_and_nan: bool) -> Self {
37        Self { trailing_comma, bare_keys, single_quotes, comments, hex_numbers, infinity_and_nan }
38    }
39
40    /// Create a JSON language instance with strict ANSI JSON settings.
41    pub fn standard() -> Self {
42        Self { trailing_comma: false, bare_keys: false, single_quotes: false, comments: false, hex_numbers: false, infinity_and_nan: false }
43    }
44
45    /// Create a JSON language instance with JSON5 settings.
46    pub fn json5() -> Self {
47        Self { trailing_comma: true, bare_keys: true, single_quotes: true, comments: true, hex_numbers: true, infinity_and_nan: true }
48    }
49
50    /// Create a JSON language instance with relaxed settings (alias for JSON5).
51    pub fn relaxed() -> Self {
52        Self::json5()
53    }
54}
55
56impl Language for JsonLanguage {
57    const NAME: &'static str = "json";
58    const CATEGORY: LanguageCategory = LanguageCategory::Config;
59
60    type TokenType = crate::lexer::token_type::JsonTokenType;
61    type ElementType = crate::parser::element_type::JsonElementType;
62    type TypedRoot = crate::ast::JsonRoot;
63}