jsonc_parser/cst/
input.rs

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
#[derive(Debug, Clone)]
pub enum CstInputValue {
  Null,
  Bool(bool),
  Number(String),
  String(String),
  Array(Vec<CstInputValue>),
  Object(Vec<(String, CstInputValue)>),
}

impl CstInputValue {
  pub(crate) fn force_multiline(&self) -> bool {
    match self {
      CstInputValue::Null | CstInputValue::Bool(_) | CstInputValue::Number(_) | CstInputValue::String(_) => false,
      CstInputValue::Array(v) => v.iter().any(|v| v.is_object_or_array_with_elements()),
      CstInputValue::Object(v) => !v.is_empty(),
    }
  }

  fn is_object_or_array_with_elements(&self) -> bool {
    match self {
      CstInputValue::Null | CstInputValue::Bool(_) | CstInputValue::Number(_) | CstInputValue::String(_) => false,
      CstInputValue::Array(v) => !v.is_empty(),
      CstInputValue::Object(v) => !v.is_empty(),
    }
  }
}

#[macro_export]
macro_rules! json {
  (null) => {
    $crate::cst::CstInputValue::Null
  };

  (true) => {
    $crate::cst::CstInputValue::Bool(true)
  };

  (false) => {
    $crate::cst::CstInputValue::Bool(false)
  };

  ($num:literal) => {
    $crate::cst::CstInputValue::Number($num.to_string())
  };

  ($str:literal) => {
    $crate::cst::CstInputValue::String($str.to_string())
  };

  ([ $($elems:tt),* $(,)? ]) => {
    $crate::cst::CstInputValue::Array(vec![
      $(json!($elems)),*
    ])
  };

  ({ $($key:tt : $value:tt),* $(,)? }) => {
    $crate::cst::CstInputValue::Object(vec![
      $(($key.to_string(), json!($value))),*
    ])
  };
}