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
//! An EDN reader/presenter in Rust.
//!
//! ## Implementations
//! -  [`core::fmt::Display`] will output valid EDN for any Edn object
//!
//! ## Differences from Clojure
//! -  Escape characters are not escaped.
//! -  Tags are current unimplemented.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use core::fmt;

#[cfg(feature = "floats")]
use ordered_float::OrderedFloat;

use crate::{error, parse};

#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Edn<'e> {
  Vector(Vec<Edn<'e>>),
  Set(BTreeSet<Edn<'e>>),
  Map(BTreeMap<Edn<'e>, Edn<'e>>),
  List(Vec<Edn<'e>>),
  Key(&'e str),
  Symbol(&'e str),
  Str(&'e str),
  Int(i64),
  #[cfg(feature = "floats")]
  Double(OrderedFloat<f64>),
  Rational((i64, i64)),
  Char(char),
  Bool(bool),
  Nil,
}

/// Reads one object from the &str.
///
/// # Errors
///
/// See [`crate::error::Error`].
pub fn read_string(edn: &str) -> Result<Edn<'_>, error::Error> {
  Ok(parse::parse(edn)?.0)
}

/// Reads the first object from the &str and the remaining unread &str.
///
/// # Errors
///
/// See [`crate::error::Error`].
pub fn read(edn: &str) -> Result<(Edn<'_>, &str), error::Error> {
  let r = parse::parse(edn)?;
  // Default behavior of Clojure's `read` is to throw an error on EOF, unlike `read_string`
  // https://clojure.github.io/tools.reader/#clojure.tools.reader.edn/read
  if r.0 == Edn::Nil && r.1.is_empty() {
    return Err(error::Error {
      code: error::Code::UnexpectedEOF,
      line: None,
      column: None,
      ptr: None,
    });
  }
  Ok((r.0, r.1))
}

impl<'e> Edn<'e> {
  pub fn get(&self, e: &Self) -> Option<&Self> {
    if let Edn::Map(m) = self {
      let lol = m.get(e);
      if let Some(l) = lol {
        return Some(l);
      };
    }
    None
  }
  pub fn nth(&self, i: usize) -> Option<&Self> {
    let vec = match self {
      Edn::Vector(v) => v,
      Edn::List(l) => l,
      _ => return None,
    };

    vec.get(i)
  }
}

const fn char_to_edn(c: char) -> Option<&'static str> {
  match c {
    '\n' => Some("newline"),
    '\r' => Some("return"),
    ' ' => Some("space"),
    '\t' => Some("tab"),
    _ => None,
  }
}

impl<'e> fmt::Display for Edn<'e> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Vector(v) => {
        write!(f, "[")?;
        let mut it = v.iter().peekable();
        while let Some(i) = it.next() {
          if it.peek().is_some() {
            write!(f, "{i} ")?;
          } else {
            write!(f, "{i}")?;
          }
        }
        write!(f, "]")
      }
      Self::Set(s) => {
        write!(f, "#{{")?;
        let mut it = s.iter().peekable();
        while let Some(i) = it.next() {
          if it.peek().is_some() {
            write!(f, "{i} ")?;
          } else {
            write!(f, "{i}")?;
          }
        }
        write!(f, "}}")
      }
      Self::Map(m) => {
        write!(f, "{{")?;
        let mut it = m.iter().peekable();
        while let Some(kv) = it.next() {
          if it.peek().is_some() {
            write!(f, "{} {}, ", kv.0, kv.1)?;
          } else {
            write!(f, "{} {}", kv.0, kv.1)?;
          }
        }
        write!(f, "}}")
      }
      Self::List(l) => {
        write!(f, "(")?;
        let mut it = l.iter().peekable();
        while let Some(i) = it.next() {
          if it.peek().is_some() {
            write!(f, "{i} ")?;
          } else {
            write!(f, "{i}")?;
          }
        }
        write!(f, ")")
      }
      Self::Symbol(sy) => write!(f, "{sy}"),
      Self::Key(k) => write!(f, "{k}"),
      Self::Str(s) => write!(f, "\"{s}\""),
      Self::Int(i) => write!(f, "{i}"),
      #[cfg(feature = "floats")]
      Self::Double(d) => write!(f, "{d}"),
      Self::Rational((n, d)) => write!(f, "{n}/{d}"),
      Self::Bool(b) => write!(f, "{b}"),
      Self::Char(c) => {
        write!(f, "\\")?;
        if let Some(c) = char_to_edn(*c) {
          return write!(f, "{c}");
        }
        write!(f, "{c}")
      }
      Self::Nil => write!(f, "nil"),
    }
  }
}