edn_format/
lib.rs

1use bigdecimal::{BigDecimal, ParseBigDecimalError};
2use chrono::FixedOffset;
3use itertools::Itertools;
4use num_bigint::{BigInt, ParseBigIntError};
5use ordered_float::OrderedFloat;
6use std::collections::{BTreeMap, BTreeSet};
7use std::fmt;
8use std::fmt::{Display, Formatter};
9use std::iter::{FromIterator, Peekable};
10use std::num::{ParseFloatError, ParseIntError};
11use std::str::{Chars, FromStr};
12use thiserror::Error;
13use uuid::Uuid;
14
15/// A keyword, as described in EDN data model, is identifier which should
16/// "designate itself".
17#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
18pub struct Keyword {
19    namespace: Option<String>,
20    name: String,
21}
22
23impl Keyword {
24    /// The namespace of the keyword, if there is one.
25    pub fn namespace(&self) -> Option<&str> {
26        self.namespace.as_deref()
27    }
28
29    /// The name of the keyword.
30    pub fn name(&self) -> &str {
31        self.name.as_str()
32    }
33
34    /// Construct a keyword from a name.
35    ///
36    /// There are no safeguards in place for ensuring that the name given would be valid EDN.
37    pub fn from_name(name: &str) -> Keyword {
38        Keyword {
39            namespace: Option::None,
40            name: name.to_string(),
41        }
42    }
43
44    /// Construct a keyword from a namespace and a name.
45    ///
46    /// There are no safeguards in place for ensuring that either the namespace or the name
47    /// given would be valid EDN.
48    pub fn from_namespace_and_name(namespace: &str, name: &str) -> Keyword {
49        Keyword {
50            namespace: Option::Some(namespace.to_string()),
51            name: name.to_string(),
52        }
53    }
54}
55
56/// If the namespace and name of the symbol follow the proper rules, displaying
57/// a keyword should give valid EDN.
58impl Display for Keyword {
59    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
60        match &self.namespace {
61            Some(ns) => write!(f, ":{}/{}", ns, self.name),
62            None => write!(f, ":{}", self.name),
63        }
64    }
65}
66
67/// A symbol, as described in EDN data model, is an identifier.
68#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
69pub struct Symbol {
70    namespace: Option<String>,
71    name: String,
72}
73
74impl Symbol {
75    /// The namespace of the symbol, if there is one.
76    pub fn namespace(&self) -> Option<&str> {
77        self.namespace.as_deref()
78    }
79
80    /// The name of the symbol.
81    pub fn name(&self) -> &str {
82        self.name.as_str()
83    }
84
85    /// Construct a symbol from a name.
86    ///
87    /// There are no safeguards in place for ensuring that the name given would be valid EDN.
88    pub fn from_name(name: &str) -> Symbol {
89        Symbol {
90            namespace: Option::None,
91            name: name.to_string(),
92        }
93    }
94
95    /// Construct a symbol from a namespace and a name.
96    ///
97    /// There are no safeguards in place for ensuring that either the namespace or the name
98    /// given would be valid EDN.
99    pub fn from_namespace_and_name(namespace: &str, name: &str) -> Symbol {
100        Symbol {
101            namespace: Option::Some(namespace.to_string()),
102            name: name.to_string(),
103        }
104    }
105}
106
107/// If the namespace and name of the symbol follow the proper rules, displaying
108/// a symbol should give valid EDN.
109impl Display for Symbol {
110    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
111        match &self.namespace {
112            Some(ns) => write!(f, "{}/{}", ns, self.name),
113            None => write!(f, "{}", self.name),
114        }
115    }
116}
117
118/// An EDN Value.
119#[derive(Debug, Clone, Ord, PartialOrd, Eq)]
120pub enum Value {
121    /// `nil`. Analogous to `null`, nothing, zip, zilch, and nada.
122    ///
123    /// <https://github.com/edn-format/edn#nil>
124    Nil,
125    /// A boolean value
126    ///
127    /// <https://github.com/edn-format/edn#booleans>
128    Boolean(bool),
129    /// A single character.
130    ///
131    /// <https://github.com/edn-format/edn#characters>
132    Character(char),
133    /// A string. Used to represent textual data.
134    ///
135    /// <https://github.com/edn-format/edn#strings>
136    String(String),
137    /// A symbol. Used to represent identifiers.
138    ///
139    /// <https://github.com/edn-format/edn#symbols>
140    Symbol(Symbol),
141    /// A keyword. An identifier that designates itself. For typical use,
142    /// these should be used for keys in [Value::Map] instead of [Value::String].
143    ///
144    /// <https://github.com/edn-format/edn#keywords>
145    Keyword(Keyword),
146    /// A signed integer
147    ///
148    /// <https://github.com/edn-format/edn#integers>
149    Integer(i64),
150    /// A floating point number with 64 bit precision.
151    ///
152    /// <https://github.com/edn-format/edn#floating-point-numbers>
153    Float(OrderedFloat<f64>),
154    /// An integer with arbitrary precision
155    ///
156    /// <https://github.com/edn-format/edn#integers>
157    BigInt(BigInt),
158    /// A decimal number with exact precision
159    ///
160    /// <https://github.com/edn-format/edn#floating-point-numbers>
161    BigDec(BigDecimal),
162    /// A list of values.
163    ///
164    /// <https://github.com/edn-format/edn#lists>
165    List(Vec<Value>),
166    /// A vector of values. The major difference between this and a [Value::List]
167    /// is that a vector is guaranteed by the spec to support random access of
168    /// elements. In this implementation the semantic difference is maintained,
169    /// but the underlying data structure for both is a [Vec], which supports random
170    /// access.
171    ///
172    /// <https://github.com/edn-format/edn#vectors>
173    Vector(Vec<Value>),
174    /// A collection of associations between keys and values. Supports any EDN value as a
175    /// key. No semantics should be associated with the order in which the pairs appear.
176    ///
177    /// <https://github.com/edn-format/edn#maps>
178    Map(BTreeMap<Value, Value>),
179    /// A collection of unique values. No semantics should be associated with the order the
180    /// items appear.
181    ///
182    /// <https://github.com/edn-format/edn#sets>
183    Set(BTreeSet<Value>),
184    /// An instant in time. Represented as a tagged element with tag `inst` and value
185    /// a [RFC-3339](https://www.ietf.org/rfc/rfc3339.txt) formatted string.
186    ///
187    /// <https://github.com/edn-format/edn#inst-rfc-3339-format>
188    Inst(chrono::DateTime<FixedOffset>),
189    /// A UUID. Represented as a tagged element with tag `uuid` and value
190    /// a canonical UUID string.
191    ///
192    /// <https://github.com/edn-format/edn#uuid-f81d4fae-7dec-11d0-a765-00a0c91e6bf6>
193    Uuid(Uuid),
194    /// A tagged element. This can be used to encode any kind of data as a distinct
195    /// readable element, with semantics determined by the reader and writer.
196    ///
197    /// Overriding the behavior of elements tagged with `inst` and `uuid` is not supported
198    /// in this implementation.
199    ///
200    /// <https://github.com/edn-format/edn#tagged-elements>
201    TaggedElement(Symbol, Box<Value>),
202}
203
204impl PartialEq for Value {
205    fn eq(&self, other: &Self) -> bool {
206        equal(self, other)
207    }
208}
209
210impl From<()> for Value {
211    fn from(_: ()) -> Self {
212        Value::Nil
213    }
214}
215
216impl<T: Into<Value>> From<Option<T>> for Value {
217    fn from(opt: Option<T>) -> Self {
218        opt.map(|o| o.into()).unwrap_or(Value::Nil)
219    }
220}
221
222impl From<char> for Value {
223    fn from(c: char) -> Self {
224        Value::Character(c)
225    }
226}
227
228impl From<&str> for Value {
229    fn from(s: &str) -> Self {
230        Value::String(s.to_string())
231    }
232}
233
234impl From<String> for Value {
235    fn from(s: String) -> Self {
236        Value::String(s)
237    }
238}
239
240impl From<Symbol> for Value {
241    fn from(sym: Symbol) -> Self {
242        Value::Symbol(sym)
243    }
244}
245
246impl From<Keyword> for Value {
247    fn from(kw: Keyword) -> Self {
248        Value::Keyword(kw)
249    }
250}
251
252impl From<i64> for Value {
253    fn from(i: i64) -> Self {
254        Value::Integer(i)
255    }
256}
257
258impl From<u32> for Value {
259    fn from(i: u32) -> Self {
260        Value::Integer(i as i64)
261    }
262}
263
264impl From<i32> for Value {
265    fn from(i: i32) -> Self {
266        Value::Integer(i as i64)
267    }
268}
269
270impl From<f64> for Value {
271    fn from(f: f64) -> Self {
272        Value::Float(OrderedFloat(f))
273    }
274}
275
276impl From<f32> for Value {
277    fn from(f: f32) -> Self {
278        Value::Float(OrderedFloat(f as f64))
279    }
280}
281
282impl From<OrderedFloat<f64>> for Value {
283    fn from(of: OrderedFloat<f64>) -> Self {
284        Value::Float(of)
285    }
286}
287
288impl From<BigInt> for Value {
289    fn from(bi: BigInt) -> Self {
290        Value::BigInt(bi)
291    }
292}
293
294impl From<BigDecimal> for Value {
295    fn from(bd: BigDecimal) -> Self {
296        Value::BigDec(bd)
297    }
298}
299
300impl From<bool> for Value {
301    fn from(b: bool) -> Self {
302        Value::Boolean(b)
303    }
304}
305
306impl From<chrono::DateTime<FixedOffset>> for Value {
307    fn from(date: chrono::DateTime<FixedOffset>) -> Self {
308        Value::Inst(date)
309    }
310}
311
312impl From<Uuid> for Value {
313    fn from(uuid: Uuid) -> Self {
314        Value::Uuid(uuid)
315    }
316}
317
318/// The errors that can be encountered during parsing.
319#[derive(Debug, Error, PartialEq)]
320pub enum ParserError {
321    #[error("The input was entirely blank")]
322    EmptyInput,
323
324    #[error("Unexpected end of input")]
325    UnexpectedEndOfInput,
326
327    #[error("Invalid escape sequence in string")]
328    InvalidStringEscape,
329
330    #[error("Duplicate value in a set")]
331    DuplicateValueInSet { value: Value },
332
333    #[error("Duplicate key in a map")]
334    DuplicateKeyInMap { value: Value },
335
336    #[error("Only symbols, and optionally non-namespaced keywords, can be used as tags")]
337    InvalidElementForTag { value: Value },
338
339    #[error("Value is not a map")]
340    NamespacedMapTagNeedsMap {
341        namespace: String,
342        got_instead_of_map: Value,
343    },
344
345    #[error("Invalid character specification")]
346    InvalidCharacterSpecification,
347
348    #[error("Unexpected character")]
349    UnexpectedCharacter(char),
350
351    #[error("Invalid keyword")]
352    InvalidKeyword,
353
354    #[error("Invalid Symbol")]
355    InvalidSymbol,
356
357    #[error("Map must have an even number of elements")]
358    OddNumberOfMapElements,
359
360    #[error("Error parsing #inst")]
361    InvalidInst(Option<chrono::format::ParseError>),
362
363    #[error("Error parsing #uuid")]
364    InvalidUuid(Option<uuid::Error>),
365
366    #[error("Cannot have slash at the beginning of symbol")]
367    CannotHaveSlashAtBeginningOfSymbol,
368
369    #[error("Cannot have slash at the end of symbol")]
370    CannotHaveSlashAtEndOfSymbol,
371
372    #[error("Cannot have more than one slash in a symbol")]
373    CannotHaveMoreThanOneSlashInSymbol,
374
375    #[error("Cannot have more a colon in a symbol")]
376    CannotHaveColonInSymbol,
377
378    #[error("Cannot have slash at the beginning of symbol")]
379    CannotHaveSlashAtBeginningOfKeyword,
380
381    #[error("Cannot have slash at the end of symbol")]
382    CannotHaveSlashAtEndOfKeyword,
383
384    #[error("Cannot have more than one slash in a symbol")]
385    CannotHaveMoreThanOneSlashInKeyword,
386
387    #[error("Cannot have more a colon in a keyword")]
388    CannotHaveColonInKeyword,
389
390    #[error("Only 0 can start with 0")]
391    OnlyZeroCanStartWithZero,
392
393    #[error("Invalid float")]
394    BadFloat {
395        parsing: String,
396        encountered: ParseFloatError,
397    },
398
399    #[error("Invalid int")]
400    BadInt {
401        parsing: String,
402        encountered: ParseIntError,
403    },
404
405    #[error("Invalid big decimal")]
406    BadBigDec {
407        parsing: String,
408        encountered: ParseBigDecimalError,
409    },
410
411    #[error("Invalid big int")]
412    BadBigInt {
413        parsing: String,
414        encountered: ParseBigIntError,
415    },
416
417    #[error("Unexpected Extra Input")]
418    ExtraInput { parsed_value: Value },
419}
420
421#[derive(Debug, Error, PartialEq)]
422pub struct ParserErrorWithContext {
423    /// Vector holding the context that the parser was working in.
424    ///
425    /// Intended to be useful for giving hints to a user about how to fix their input.
426    pub context: Vec<Context>,
427    /// The row where the error was detected. 1 indexed. 0 if no characters on the line have been read.
428    pub row: usize,
429    /// The col where the error was detected. 1 indexed. Starts at 1.
430    pub col: usize,
431    /// The error that the parser ran into.
432    pub error: ParserError,
433}
434
435impl Display for ParserErrorWithContext {
436    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
437        write!(f, "({}, {}): {}", self.row, self.col, self.error)
438    }
439}
440
441#[derive(Debug)]
442enum ParserState {
443    Begin,
444    ParsingList { values_so_far: Vec<Value> },
445    ParsingVector { values_so_far: Vec<Value> },
446    ParsingMap { values_so_far: Vec<Value> },
447    ParsingSet { values_so_far: Vec<Value> },
448    ParsingAtom { built_up: Vec<char> },
449    ParsingString { built_up: String },
450    ParsingCharacter,
451    SelectingDispatch,
452}
453
454/// Commas are considered whitespace for EDN
455fn is_whitespace(c: char) -> bool {
456    c.is_whitespace() || c == ','
457}
458
459fn is_allowed_atom_character(c: char) -> bool {
460    c == '.'
461        || c == '*'
462        || c == '+'
463        || c == '!'
464        || c == '-'
465        || c == '_'
466        || c == '?'
467        || c == '$'
468        || c == '%'
469        || c == '&'
470        || c == '='
471        || c == '<'
472        || c == '>'
473        || c == '/'
474        || c == ':'
475        || c.is_alphabetic()
476        || c.is_numeric()
477}
478
479fn equal(v1: &Value, v2: &Value) -> bool {
480    match (v1, v2) {
481        // nil, booleans, strings, characters, and symbols
482        // are equal to values of the same type with the same edn representation
483        (Value::Nil, Value::Nil) => true,
484        (Value::Boolean(b1), Value::Boolean(b2)) => b1 == b2,
485        (Value::String(s1), Value::String(s2)) => s1 == s2,
486        (Value::Character(c1), Value::Character(c2)) => c1 == c2,
487        (Value::Symbol(s1), Value::Symbol(s2)) => s1 == s2,
488        (Value::Keyword(k1), Value::Keyword(k2)) => k1 == k2,
489
490        // integers and floating point numbers should be considered equal to values only of the
491        // same magnitude, type, and precision. Comingling numeric types and precision in
492        // map/set key/elements, or constituents therein, is not advised.
493        (Value::Float(f1), Value::Float(f2)) => f1 == f2,
494        (Value::Integer(i1), Value::Integer(i2)) => i1 == i2,
495        (Value::BigInt(bi1), Value::BigInt(bi2)) => bi1 == bi2,
496        (Value::BigDec(bd1), Value::BigDec(bd2)) => bd1 == bd2,
497
498        // sequences (lists and vectors) are equal to other sequences whose count
499        // of elements is the same, and for which each corresponding pair of
500        // elements (by ordinal) is equal.
501        (Value::List(vals1) | Value::Vector(vals1), Value::List(vals2) | Value::Vector(vals2)) => {
502            vals1 == vals2
503        }
504
505        // sets are equal if they have the same count of elements and,
506        // for every element in one set, an equal element is in the other.
507        (Value::Set(vals1), Value::Set(vals2)) => vals1 == vals2,
508
509        // maps are equal if they have the same number of entries,
510        // and for every key/value entry in one map an equal key is present
511        // and mapped to an equal value in the other.
512        (Value::Map(entries1), Value::Map(entries2)) => entries1 == entries2,
513
514        // tagged elements must define their own equality semantics.
515        // #uuid elements are equal if their canonic representations are equal.
516        // #inst elements are equal if their representation strings designate
517        // the same timestamp per RFC-3339.
518        (Value::Uuid(uuid1), Value::Uuid(uuid2)) => uuid1 == uuid2,
519        (Value::Inst(dt1), Value::Inst(dt2)) => dt1 == dt2,
520        (Value::TaggedElement(tag1, value1), Value::TaggedElement(tag2, value2)) => {
521            equal(&Value::Symbol(tag1.clone()), &Value::Symbol(tag2.clone()))
522                && equal(value1, value2)
523        }
524
525        _ => false,
526    }
527}
528
529/// Struct holding a row position and a column position.
530#[derive(Debug, Copy, Clone, Eq, PartialEq)]
531struct RowCol {
532    /// The row. 1 indexed. 0 if no characters on the line have been read.
533    row: usize,
534    /// The col. 1 indexed. Starts at 1.
535    col: usize,
536}
537
538impl RowCol {
539    fn new() -> RowCol {
540        RowCol { row: 0, col: 1 }
541    }
542
543    fn chomp(&mut self, c: char) {
544        if c == '\n' {
545            self.row = 0;
546            self.col += 1;
547        } else {
548            self.row += 1;
549        }
550    }
551}
552
553/// The purpose of this interface is to keep track of a "context stack"
554/// so i can give better errors if parsing fails. This only has events for
555/// things that might have errors "within" some structure
556trait ParseObserver {
557    fn start_parsing_vector(&mut self);
558
559    fn start_parsing_list(&mut self);
560
561    fn start_parsing_map(&mut self);
562
563    fn start_parsing_set(&mut self);
564
565    fn start_parsing_string(&mut self);
566
567    fn start_parsing_atom(&mut self);
568
569    fn stop_parsing_current(&mut self);
570
571    fn advance_one_char(&mut self, c: char);
572}
573
574struct NoOpParseObserver;
575
576impl ParseObserver for NoOpParseObserver {
577    fn start_parsing_vector(&mut self) {}
578
579    fn start_parsing_list(&mut self) {}
580
581    fn start_parsing_map(&mut self) {}
582
583    fn start_parsing_set(&mut self) {}
584
585    fn start_parsing_string(&mut self) {}
586
587    fn start_parsing_atom(&mut self) {}
588
589    fn stop_parsing_current(&mut self) {}
590
591    fn advance_one_char(&mut self, _c: char) {}
592}
593
594/// An element of context about what the parser was doing when an error was detected.
595#[derive(Debug, Copy, Clone, Eq, PartialEq)]
596pub enum Context {
597    /// The parser started parsing a vector at the given row and col.
598    ParsingVector { row: usize, col: usize },
599    /// The parser started parsing a list at the given row and col.
600    ParsingList { row: usize, col: usize },
601    /// The parser started parsing a map at the given row and col.
602    ParsingMap { row: usize, col: usize },
603    /// The parser started parsing a set at the given row and col.
604    ParsingSet { row: usize, col: usize },
605    /// The parser started parsing a string at the given row and col.
606    ParsingString { row: usize, col: usize },
607    /// The parser started parsing an "atom" at the given row and col.
608    ///
609    /// An "atom" might be a symbol, keyword, number, true, false, or nil.
610    /// At the point the parser records this information it does not know which.
611    ParsingAtom { row: usize, col: usize },
612}
613
614#[derive(Debug)]
615struct ContextStackerObserver {
616    context: Vec<Context>,
617    row_col: RowCol,
618}
619
620impl ContextStackerObserver {
621    fn new() -> ContextStackerObserver {
622        ContextStackerObserver {
623            context: Vec::new(),
624            row_col: RowCol::new(),
625        }
626    }
627}
628
629impl ParseObserver for ContextStackerObserver {
630    fn start_parsing_vector(&mut self) {
631        self.context.push(Context::ParsingVector {
632            row: self.row_col.row,
633            col: self.row_col.col,
634        });
635    }
636
637    fn start_parsing_list(&mut self) {
638        self.context.push(Context::ParsingList {
639            row: self.row_col.row,
640            col: self.row_col.col,
641        });
642    }
643
644    fn start_parsing_map(&mut self) {
645        self.context.push(Context::ParsingMap {
646            row: self.row_col.row,
647            col: self.row_col.col,
648        });
649    }
650
651    fn start_parsing_set(&mut self) {
652        self.context.push(Context::ParsingSet {
653            row: self.row_col.row,
654            col: self.row_col.col,
655        });
656    }
657
658    fn start_parsing_string(&mut self) {
659        self.context.push(Context::ParsingString {
660            row: self.row_col.row,
661            col: self.row_col.col,
662        });
663    }
664
665    fn start_parsing_atom(&mut self) {
666        self.context.push(Context::ParsingAtom {
667            row: self.row_col.row,
668            col: self.row_col.col,
669        });
670    }
671
672    fn stop_parsing_current(&mut self) {
673        self.context.pop();
674    }
675
676    fn advance_one_char(&mut self, c: char) {
677        self.row_col.chomp(c)
678    }
679}
680
681fn interpret_atom(atom: &[char]) -> Result<Value, ParserError> {
682    let char_slice_to_str = |chars: &[char]| chars.iter().copied().collect::<String>();
683    let starts_like_number = |chars: &[char]| {
684        !chars.is_empty()
685            && (chars[0].is_numeric()
686                || (['+', '-'].contains(&chars[0]) && chars.len() >= 2 && chars[1].is_numeric()))
687    };
688    match atom {
689        &[] => Err(ParserError::UnexpectedEndOfInput),
690        &['n', 'i', 'l'] => Ok(Value::Nil),
691        &['t', 'r', 'u', 'e'] => Ok(Value::Boolean(true)),
692        &['f', 'a', 'l', 's', 'e'] => Ok(Value::Boolean(false)),
693        &[':'] => Err(ParserError::InvalidKeyword),
694        &[':', '/'] => Ok(Value::Keyword(Keyword::from_name("/"))),
695        &[':', '/', ..] => Err(ParserError::CannotHaveSlashAtBeginningOfKeyword),
696        &[':', .., '/'] => Err(ParserError::CannotHaveSlashAtEndOfKeyword),
697        &['/'] => Ok(Value::Symbol(Symbol::from_name("/"))),
698        &['/', ..] => Err(ParserError::CannotHaveSlashAtBeginningOfSymbol),
699        &[.., '/'] => Err(ParserError::CannotHaveSlashAtEndOfSymbol),
700        &[':', ref rest @ ..] => {
701            if rest.contains(&':') {
702                Err(ParserError::CannotHaveColonInKeyword)
703            } else {
704                let split: Vec<_> = rest.split(|c| *c == '/').collect();
705                match split[..] {
706                    [name] => Ok(Value::Keyword(Keyword::from_name(&char_slice_to_str(name)))),
707                    [namespace, name] => {
708                        if starts_like_number(namespace) {
709                            Err(ParserError::InvalidKeyword)
710                        } else {
711                            Ok(Value::Keyword(Keyword::from_namespace_and_name(
712                                &char_slice_to_str(namespace),
713                                &char_slice_to_str(name),
714                            )))
715                        }
716                    }
717                    _ => Err(ParserError::CannotHaveMoreThanOneSlashInKeyword),
718                }
719            }
720        }
721        chars => {
722            if chars.contains(&':') {
723                Err(ParserError::CannotHaveColonInSymbol)
724            } else {
725                let split: Vec<_> = chars.split(|c| *c == '/').collect();
726                match split[..] {
727                    [name] => {
728                        if starts_like_number(name) {
729                            if name.ends_with(&['M'])
730                                && name.iter().filter(|c| **c == 'M').count() == 1
731                            {
732                                Ok(Value::BigDec(
733                                    str::parse::<BigDecimal>(&char_slice_to_str(
734                                        &chars[..chars.len() - 1],
735                                    ))
736                                    .map_err(|err| {
737                                        ParserError::BadBigDec {
738                                            parsing: char_slice_to_str(chars),
739                                            encountered: err,
740                                        }
741                                    })?,
742                                ))
743                            } else if name.contains(&'.')
744                                || name.contains(&'e')
745                                || name.contains(&'E')
746                            {
747                                Ok(Value::Float(OrderedFloat(
748                                    str::parse::<f64>(&char_slice_to_str(chars)).map_err(
749                                        |err| ParserError::BadFloat {
750                                            parsing: char_slice_to_str(chars),
751                                            encountered: err,
752                                        },
753                                    )?,
754                                )))
755                            } else if name != ['0'] && (name.starts_with(&['0']))
756                                || (name != ['+', '0']
757                                    && (name.len() > 1
758                                        && name.starts_with(&['+'])
759                                        && name[1..].starts_with(&['0'])))
760                                || (name != ['-', '0']
761                                    && (name.len() > 1
762                                        && name.starts_with(&['-'])
763                                        && name[1..].starts_with(&['0'])))
764                            {
765                                // Only ints are subject to this restriction it seems
766                                Err(ParserError::OnlyZeroCanStartWithZero)
767                            } else if name.ends_with(&['N'])
768                                && name.iter().filter(|c| **c == 'N').count() == 1
769                            {
770                                Ok(Value::BigInt(
771                                    str::parse::<BigInt>(&char_slice_to_str(
772                                        &chars[..chars.len() - 1],
773                                    ))
774                                    .map_err(|err| {
775                                        ParserError::BadBigInt {
776                                            parsing: char_slice_to_str(chars),
777                                            encountered: err,
778                                        }
779                                    })?,
780                                ))
781                            } else {
782                                Ok(Value::Integer(
783                                    str::parse::<i64>(&char_slice_to_str(chars)).map_err(
784                                        |err| ParserError::BadInt {
785                                            parsing: char_slice_to_str(chars),
786                                            encountered: err,
787                                        },
788                                    )?,
789                                ))
790                            }
791                        } else {
792                            Ok(Value::Symbol(Symbol::from_name(&char_slice_to_str(name))))
793                        }
794                    }
795                    [namespace, name] => {
796                        if starts_like_number(namespace) {
797                            Err(ParserError::InvalidSymbol)
798                        } else {
799                            Ok(Value::Symbol(Symbol::from_namespace_and_name(
800                                &char_slice_to_str(namespace),
801                                &char_slice_to_str(name),
802                            )))
803                        }
804                    }
805                    _ => Err(ParserError::CannotHaveMoreThanOneSlashInSymbol),
806                }
807            }
808        }
809    }
810}
811
812/// Likely suboptimal parsing. Focus for now is just on getting correct results.
813fn parse_helper<Observer: ParseObserver, Iter: Iterator<Item = char> + Clone>(
814    s: &mut Peekable<Iter>,
815    mut parser_state: ParserState,
816    observer: &mut Observer,
817    opts: &ParserOptions,
818) -> Result<Value, ParserError> {
819    'parsing: loop {
820        // Strip out comments
821        match parser_state {
822            ParserState::ParsingString { .. } => {}
823            _ => {
824                if let Some(';') = s.peek() {
825                    loop {
826                        match s.next() {
827                            None => {
828                                break;
829                            }
830                            Some('\n') => {
831                                observer.advance_one_char('\n');
832                                break;
833                            }
834                            Some(c) => {
835                                observer.advance_one_char(c);
836                            }
837                        }
838                    }
839                }
840            }
841        };
842        match &mut parser_state {
843            ParserState::Begin => match s.peek().copied() {
844                None => return Err(ParserError::EmptyInput),
845                Some(c) => {
846                    observer.advance_one_char(c);
847                    if is_whitespace(c) {
848                        s.next();
849                        parser_state = ParserState::Begin;
850                    } else if c == '(' {
851                        s.next();
852                        observer.start_parsing_list();
853                        parser_state = ParserState::ParsingList {
854                            values_so_far: vec![],
855                        };
856                    } else if c == '[' {
857                        s.next();
858                        observer.start_parsing_vector();
859                        parser_state = ParserState::ParsingVector {
860                            values_so_far: vec![],
861                        };
862                    } else if c == '{' {
863                        s.next();
864                        observer.start_parsing_map();
865                        parser_state = ParserState::ParsingMap {
866                            values_so_far: vec![],
867                        };
868                    } else if c == '"' {
869                        s.next();
870                        observer.start_parsing_string();
871                        parser_state = ParserState::ParsingString {
872                            built_up: "".to_string(),
873                        };
874                    } else if c == '\\' {
875                        s.next();
876                        parser_state = ParserState::ParsingCharacter;
877                    } else if c == '#' {
878                        s.next();
879                        parser_state = ParserState::SelectingDispatch;
880                    } else if is_allowed_atom_character(c) || c == ':' {
881                        s.next();
882                        let built_up = vec![c];
883                        observer.start_parsing_atom();
884                        parser_state = ParserState::ParsingAtom { built_up };
885                    } else if c == ';' {
886                        parser_state = ParserState::Begin;
887                    } else {
888                        s.next();
889                        return Err(ParserError::UnexpectedCharacter(c));
890                    }
891                }
892            },
893
894            ParserState::ParsingList {
895                ref mut values_so_far,
896            } => {
897                let next = s.peek();
898                match next {
899                    None => return Err(ParserError::UnexpectedEndOfInput),
900                    Some(c) => {
901                        if is_whitespace(*c) {
902                            observer.advance_one_char(*c);
903                            s.next();
904                        } else if *c == ')' {
905                            observer.advance_one_char(*c);
906                            s.next();
907                            observer.stop_parsing_current();
908                            return Ok(Value::List(values_so_far.clone()));
909                        } else {
910                            let value = parse_helper(s, ParserState::Begin, observer, opts)?;
911                            values_so_far.push(value);
912                        }
913                    }
914                }
915            }
916
917            // Almost total duplicate of ParsingList
918            ParserState::ParsingVector {
919                ref mut values_so_far,
920            } => match s.peek() {
921                None => {
922                    return Err(ParserError::UnexpectedEndOfInput);
923                }
924                Some(c) => {
925                    if is_whitespace(*c) {
926                        observer.advance_one_char(*c);
927                        s.next();
928                    } else if *c == ']' {
929                        observer.stop_parsing_current();
930                        observer.advance_one_char(*c);
931                        s.next();
932                        return Ok(Value::Vector(values_so_far.clone()));
933                    } else {
934                        let value = parse_helper(s, ParserState::Begin, observer, opts)?;
935                        values_so_far.push(value);
936                    }
937                }
938            },
939
940            ParserState::ParsingMap {
941                ref mut values_so_far,
942            } => {
943                match s.peek() {
944                    None => {
945                        return Err(ParserError::UnexpectedEndOfInput);
946                    }
947                    Some(c) => {
948                        if is_whitespace(*c) {
949                            observer.advance_one_char(*c);
950                            s.next();
951                        } else if *c == '}' {
952                            if values_so_far.len() % 2 != 0 {
953                                return Err(ParserError::OddNumberOfMapElements);
954                            } else {
955                                // I'm confident there has to be a better way to do this
956                                let entries: Vec<(Value, Value)> = values_so_far
957                                    .iter_mut()
958                                    .map(|v| v.clone())
959                                    .batching(|it| match it.next() {
960                                        None => None,
961                                        Some(x) => it.next().map(|y| (x, y)),
962                                    })
963                                    .collect();
964
965                                let mut seen = BTreeSet::new();
966                                for (k, _) in entries.iter() {
967                                    if seen.contains(k) {
968                                        return Err(ParserError::DuplicateKeyInMap {
969                                            value: k.clone(),
970                                        });
971                                    }
972                                    seen.insert(k);
973                                }
974                                let value = Value::Map(BTreeMap::from_iter(entries));
975
976                                observer.stop_parsing_current();
977                                observer.advance_one_char(*c);
978                                s.next();
979                                return Ok(value);
980                            }
981                        } else {
982                            let value = parse_helper(s, ParserState::Begin, observer, opts)?;
983                            values_so_far.push(value);
984                        }
985                    }
986                }
987            }
988
989            ParserState::ParsingSet {
990                ref mut values_so_far,
991            } => match s.peek() {
992                None => {
993                    return Err(ParserError::UnexpectedEndOfInput);
994                }
995                Some(c) => {
996                    if is_whitespace(*c) {
997                        observer.advance_one_char(*c);
998                        s.next();
999                    } else if *c == '}' {
1000                        let mut seen = BTreeSet::new();
1001                        for v in values_so_far.iter() {
1002                            if seen.contains(v) {
1003                                return Err(ParserError::DuplicateValueInSet { value: v.clone() });
1004                            }
1005                            seen.insert(v);
1006                        }
1007                        observer.stop_parsing_current();
1008                        observer.advance_one_char(*c);
1009                        s.next();
1010                        return Ok(Value::Set(values_so_far.iter().cloned().collect()));
1011                    } else {
1012                        let value = parse_helper(s, ParserState::Begin, observer, opts)?;
1013                        values_so_far.push(value);
1014                    }
1015                }
1016            },
1017
1018            ParserState::ParsingAtom { ref mut built_up } => match s.peek() {
1019                None => {
1020                    return if built_up.is_empty() {
1021                        Err(ParserError::UnexpectedEndOfInput)
1022                    } else {
1023                        let value = interpret_atom(built_up)?;
1024                        observer.stop_parsing_current();
1025                        Ok(value)
1026                    }
1027                }
1028                Some(c) => {
1029                    if !is_allowed_atom_character(*c) {
1030                        let value = interpret_atom(built_up)?;
1031                        observer.stop_parsing_current();
1032                        return Ok(value);
1033                    } else {
1034                        built_up.push(*c);
1035                        observer.advance_one_char(*c);
1036                        s.next();
1037                    }
1038                }
1039            },
1040
1041            ParserState::ParsingString { ref mut built_up } => match s.peek() {
1042                None => return Err(ParserError::UnexpectedEndOfInput),
1043                Some(c) => {
1044                    if *c == '"' {
1045                        observer.stop_parsing_current();
1046                        observer.advance_one_char(*c);
1047                        s.next();
1048                        return Ok(Value::String(built_up.clone()));
1049                    } else if *c == '\\' {
1050                        observer.advance_one_char(*c);
1051                        s.next();
1052                        match s.next() {
1053                            None => return Err(ParserError::InvalidStringEscape),
1054                            Some(c) => {
1055                                observer.advance_one_char(c);
1056                                match c {
1057                                    't' => built_up.push('\t'),
1058                                    'r' => built_up.push('\r'),
1059                                    'n' => built_up.push('\n'),
1060
1061                                    '\\' => built_up.push('\\'),
1062                                    '"' => built_up.push('"'),
1063                                    'u' => match (s.next(), s.next(), s.next(), s.next()) {
1064                                        (Some(c1), Some(c2), Some(c3), Some(c4)) => {
1065                                            observer.advance_one_char(c1);
1066                                            observer.advance_one_char(c2);
1067                                            observer.advance_one_char(c3);
1068                                            observer.advance_one_char(c4);
1069                                            let str: String =
1070                                                [c1, c2, c3, c4].iter().copied().collect();
1071                                            let unicode = u32::from_str_radix(&str, 16)
1072                                                .map_err(|_| ParserError::InvalidStringEscape)?;
1073                                            match char::from_u32(unicode) {
1074                                                None => {
1075                                                    return Err(ParserError::InvalidStringEscape)
1076                                                }
1077                                                Some(c) => built_up.push(c),
1078                                            }
1079                                            continue 'parsing;
1080                                        }
1081                                        (Some(c1), Some(c2), Some(c3), _) => {
1082                                            observer.advance_one_char(c1);
1083                                            observer.advance_one_char(c2);
1084                                            observer.advance_one_char(c3);
1085                                            return Err(ParserError::InvalidStringEscape);
1086                                        }
1087                                        (Some(c1), Some(c2), _, _) => {
1088                                            observer.advance_one_char(c1);
1089                                            observer.advance_one_char(c2);
1090                                            return Err(ParserError::InvalidStringEscape);
1091                                        }
1092                                        (Some(c1), _, _, _) => {
1093                                            observer.advance_one_char(c1);
1094                                            return Err(ParserError::InvalidStringEscape);
1095                                        }
1096                                        _ => {
1097                                            return Err(ParserError::InvalidStringEscape);
1098                                        }
1099                                    },
1100                                    _ => return Err(ParserError::InvalidStringEscape),
1101                                }
1102                            }
1103                        }
1104                    } else {
1105                        built_up.push(*c);
1106                        observer.advance_one_char(*c);
1107                        s.next();
1108                    }
1109                }
1110            },
1111            ParserState::SelectingDispatch => {
1112                match s.peek() {
1113                    None => {
1114                        return Err(ParserError::UnexpectedEndOfInput);
1115                    }
1116                    Some(c) => {
1117                        if *c == '_' {
1118                            // Drop the next form. Still error if that form is malformed
1119                            observer.advance_one_char(*c);
1120                            s.next();
1121                            let _ = parse_helper(s, ParserState::Begin, observer, opts)?;
1122                            parser_state = ParserState::Begin;
1123                        } else if *c == '{' {
1124                            observer.advance_one_char(*c);
1125                            s.next();
1126                            observer.start_parsing_set();
1127                            parser_state = ParserState::ParsingSet {
1128                                values_so_far: vec![],
1129                            };
1130                        } else {
1131                            // We expect to read a symbol next and we will associate that symbol as the tag of
1132                            // the following element
1133                            let value = parse_helper(s, ParserState::Begin, observer, opts)?;
1134                            match value {
1135                                Value::Symbol(symbol) => {
1136                                    let next_success =
1137                                        parse_helper(s, ParserState::Begin, observer, opts)?;
1138
1139                                    // Handle builtin #inst
1140                                    if symbol.namespace.is_none() && symbol.name == "inst" {
1141                                        if let Value::String(timestamp) = next_success {
1142                                            let datetime =
1143                                                chrono::DateTime::parse_from_rfc3339(&timestamp)
1144                                                    .map_err(|parse_error| {
1145                                                        ParserError::InvalidInst(Some(parse_error))
1146                                                    })?;
1147                                            return Ok(Value::Inst(datetime));
1148                                        } else {
1149                                            return Err(ParserError::InvalidInst(None));
1150                                        }
1151                                    }
1152                                    // Handle builtin #uuid
1153                                    else if symbol.namespace.is_none() && symbol.name == "uuid" {
1154                                        if let Value::String(uuid_str) = next_success {
1155                                            let uuid = Uuid::parse_str(&uuid_str).map_err(
1156                                                |parse_error| {
1157                                                    ParserError::InvalidUuid(Some(parse_error))
1158                                                },
1159                                            )?;
1160                                            return Ok(Value::Uuid(uuid));
1161                                        } else {
1162                                            return Err(ParserError::InvalidUuid(None));
1163                                        }
1164                                    }
1165                                    // Everything else becomes a generic TaggedElement
1166                                    else {
1167                                        return Ok(Value::TaggedElement(
1168                                            symbol,
1169                                            Box::new(next_success),
1170                                        ));
1171                                    }
1172                                }
1173                                Value::Keyword(ref ns) => {
1174                                    if !opts.allow_namespaced_map_syntax || ns.namespace.is_some() {
1175                                        return Err(ParserError::InvalidElementForTag { value });
1176                                    } else {
1177                                        let next_success =
1178                                            parse_helper(s, ParserState::Begin, observer, opts)?;
1179                                        if let Value::Map(following_map) = next_success {
1180                                            let mut new_map = BTreeMap::new();
1181                                            for (k, v) in following_map.into_iter() {
1182                                                new_map.insert(
1183                                                    match &k {
1184                                                        Value::Keyword(keyword) => {
1185                                                            if keyword.namespace.is_some() {
1186                                                                k
1187                                                            } else {
1188                                                                Value::Keyword(
1189                                                                    Keyword::from_namespace_and_name(
1190                                                                        &ns.name,
1191                                                                        &keyword.name,
1192                                                                    ),
1193                                                                )
1194                                                            }
1195                                                        }
1196                                                        _ => k,
1197                                                    },
1198                                                    v,
1199                                                );
1200                                            }
1201                                            return Ok(Value::Map(new_map));
1202                                        } else {
1203                                            return Err(ParserError::NamespacedMapTagNeedsMap {
1204                                                namespace: ns.name.to_string(),
1205                                                got_instead_of_map: value.clone(),
1206                                            });
1207                                        }
1208                                    }
1209                                }
1210                                _ => return Err(ParserError::InvalidElementForTag { value }),
1211                            }
1212                        }
1213                    }
1214                }
1215            }
1216
1217            ParserState::ParsingCharacter => {
1218                let c = read_character(s)?;
1219                return Ok(Value::Character(c));
1220            }
1221        }
1222    }
1223}
1224
1225fn read_character<I>(iter: &mut Peekable<I>) -> Result<char, ParserError>
1226where
1227    I: Iterator<Item = char> + Clone,
1228{
1229    let mut temp_iter = iter.clone();
1230    let mut lookahead = String::new();
1231
1232    // Fill the lookahead string with a snapshot of the next characters (up to 7 in this case)
1233    for _ in 0..7 {
1234        if let Some(c) = temp_iter.next() {
1235            lookahead.push(c);
1236        } else {
1237            break;
1238        }
1239    }
1240
1241    // Now analyze the lookahead string
1242    match &lookahead[..] {
1243        s if s.starts_with("newline") => {
1244            for _ in 0..7 {
1245                iter.next();
1246            }
1247            Ok('\n')
1248        }
1249        s if s.starts_with("return") => {
1250            for _ in 0..6 {
1251                iter.next();
1252            }
1253            Ok('\r')
1254        }
1255        s if s.starts_with("space") => {
1256            for _ in 0..5 {
1257                iter.next();
1258            }
1259            Ok(' ')
1260        }
1261        s if s.starts_with("tab") => {
1262            for _ in 0..3 {
1263                iter.next();
1264            }
1265            Ok('\t')
1266        }
1267        s if s.starts_with('u') && s.len() >= 5 => {
1268            let unicode_repr = &s[1..5];
1269            if let Ok(u) = u16::from_str_radix(unicode_repr, 16) {
1270                if let Some(chr) = char::from_u32(u as u32) {
1271                    for _ in 0..5 {
1272                        iter.next();
1273                    }
1274                    Ok(chr)
1275                } else {
1276                    Err(ParserError::InvalidCharacterSpecification)
1277                }
1278            } else {
1279                Err(ParserError::InvalidCharacterSpecification)
1280            }
1281        }
1282
1283        s if !s.is_empty() => {
1284            let first_char = s.chars().next().unwrap();
1285            let second_char = s.chars().nth(1);
1286
1287            match second_char {
1288                Some(second_char) => {
1289                    if is_allowed_atom_character(second_char) {
1290                        Err(ParserError::InvalidCharacterSpecification)
1291                    } else {
1292                        iter.next();
1293                        Ok(first_char)
1294                    }
1295                }
1296                None => {
1297                    iter.next();
1298                    Ok(first_char)
1299                }
1300            }
1301        }
1302
1303        _ => Err(ParserError::InvalidCharacterSpecification),
1304    }
1305}
1306
1307/// Options you can pass to the EDN parser.
1308#[derive(Debug, Copy, Clone)]
1309pub struct ParserOptions {
1310    /// Whether to allow the #some.ns{:key "val"} syntax that was introduced in clojure 1.9
1311    /// but not reflected in the EDN spec.
1312    ///
1313    /// Defaults to true.
1314    pub allow_namespaced_map_syntax: bool,
1315}
1316
1317impl Default for ParserOptions {
1318    fn default() -> Self {
1319        ParserOptions {
1320            allow_namespaced_map_syntax: true,
1321        }
1322    }
1323}
1324
1325/// Parse EDN from the given input string with the given options.
1326pub fn parse_str_with_options(
1327    s: &str,
1328    opts: ParserOptions,
1329) -> Result<Value, ParserErrorWithContext> {
1330    let mut chars = s.chars().peekable();
1331    let mut context = ContextStackerObserver::new();
1332    let value =
1333        parse_helper(&mut chars, ParserState::Begin, &mut context, &opts).map_err(|err| {
1334            ParserErrorWithContext {
1335                context: context.context.clone(),
1336                row: context.row_col.row,
1337                col: context.row_col.col,
1338                error: err,
1339            }
1340        })?;
1341    Ok(value)
1342}
1343
1344/// Parse EDN from the given input string with default options.
1345pub fn parse_str(s: &str) -> Result<Value, ParserErrorWithContext> {
1346    parse_str_with_options(s, ParserOptions::default())
1347}
1348
1349impl FromStr for Value {
1350    type Err = ParserErrorWithContext;
1351
1352    fn from_str(s: &str) -> Result<Self, Self::Err> {
1353        parse_str(s)
1354    }
1355}
1356
1357impl Display for Value {
1358    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1359        match self {
1360            Value::Nil => {
1361                write!(f, "nil")?;
1362            }
1363            Value::String(s) => {
1364                write!(f, "\"")?;
1365                for c in s.chars() {
1366                    match c {
1367                        '\t' => write!(f, "\\t")?,
1368                        '\r' => write!(f, "\\r")?,
1369                        '\n' => write!(f, "\\n")?,
1370
1371                        '\\' => write!(f, "\\\\")?,
1372                        '\"' => write!(f, "\\\"")?,
1373                        _ => write!(f, "{}", c)?,
1374                    };
1375                }
1376                write!(f, "\"")?;
1377            }
1378            Value::Character(c) => {
1379                match c {
1380                    '\n' => write!(f, "\\newline")?,
1381                    '\r' => write!(f, "\\return")?,
1382                    ' ' => write!(f, "\\space")?,
1383                    '\t' => write!(f, "\\tab")?,
1384                    _ => write!(f, "\\{}", c)?,
1385                };
1386            }
1387            Value::Symbol(symbol) => {
1388                write!(f, "{}", symbol)?;
1389            }
1390            Value::Keyword(keyword) => {
1391                write!(f, "{}", keyword)?;
1392            }
1393            Value::Integer(i) => {
1394                write!(f, "{}", i)?;
1395            }
1396            Value::Float(fl) => {
1397                write!(f, "{}", fl)?;
1398            }
1399            Value::BigInt(bi) => {
1400                write!(f, "{}N", bi)?;
1401            }
1402            Value::BigDec(bd) => {
1403                write!(f, "{}M", bd)?;
1404            }
1405            Value::List(elements) => {
1406                write!(f, "(")?;
1407                let mut i = 0;
1408                while i < elements.len() {
1409                    write!(f, "{}", elements[i])?;
1410                    if i != elements.len() - 1 {
1411                        write!(f, " ")?;
1412                    }
1413                    i += 1;
1414                }
1415                write!(f, ")")?;
1416            }
1417            Value::Vector(elements) => {
1418                write!(f, "[")?;
1419                let mut i = 0;
1420                while i < elements.len() {
1421                    write!(f, "{}", elements[i])?;
1422                    if i != elements.len() - 1 {
1423                        write!(f, " ")?;
1424                    }
1425                    i += 1;
1426                }
1427                write!(f, "]")?;
1428            }
1429            Value::Map(entries) => {
1430                write!(f, "{{")?;
1431                let mut i = 0;
1432                let entries: Vec<_> = entries.iter().collect();
1433                while i < entries.len() {
1434                    let (k, v) = &entries[i];
1435                    write!(f, "{} {}", k, v)?;
1436                    if i != entries.len() - 1 {
1437                        write!(f, " ")?;
1438                    }
1439                    i += 1;
1440                }
1441                write!(f, "}}")?;
1442            }
1443            Value::Set(elements) => {
1444                write!(f, "#{{")?;
1445                let elements: Vec<_> = elements.iter().collect();
1446                let mut i = 0;
1447                while i < elements.len() {
1448                    write!(f, "{}", elements[i])?;
1449                    if i != elements.len() - 1 {
1450                        write!(f, " ")?;
1451                    }
1452                    i += 1;
1453                }
1454                write!(f, "}}")?;
1455            }
1456            Value::Boolean(b) => {
1457                write!(f, "{}", b)?;
1458            }
1459            Value::Inst(inst) => {
1460                write!(f, "#inst \"{}\"", inst.to_rfc3339())?;
1461            }
1462            Value::Uuid(uuid) => {
1463                write!(f, "#uuid \"{}\"", uuid)?;
1464            }
1465            Value::TaggedElement(tag, value) => {
1466                write!(f, "#{} {}", tag, value)?;
1467            }
1468        }
1469        Ok(())
1470    }
1471}
1472
1473/// Emit the given EDN value as a String.
1474pub fn emit_str(value: &Value) -> String {
1475    format!("{}", value)
1476}
1477
1478/// Parser which can yield multiple forms from a single iterator of
1479/// chars
1480pub struct Parser<Iter: Iterator<Item = char>> {
1481    opts: ParserOptions,
1482    iter: Peekable<Iter>,
1483}
1484
1485impl<'a> Parser<Chars<'a>> {
1486    /// Construct a parser from a &str,
1487    pub fn from_str(s: &'a str, opts: ParserOptions) -> Parser<Chars<'a>> {
1488        Parser {
1489            opts,
1490            iter: s.chars().peekable(),
1491        }
1492    }
1493}
1494
1495impl<Iter: Iterator<Item = char>> Parser<Iter> {
1496    /// Construct a parser from an arbitrary iterator,
1497    pub fn from_iter(iter: Iter, opts: ParserOptions) -> Parser<Iter> {
1498        Parser {
1499            opts,
1500            iter: iter.peekable(),
1501        }
1502    }
1503}
1504
1505impl<Iter: Iterator<Item = char> + Clone> Iterator for Parser<Iter> {
1506    type Item = Result<Value, ParserError>;
1507
1508    fn next(&mut self) -> Option<Self::Item> {
1509        match parse_helper(
1510            &mut self.iter,
1511            ParserState::Begin,
1512            &mut NoOpParseObserver,
1513            &self.opts,
1514        ) {
1515            Err(error) => {
1516                if error == ParserError::EmptyInput {
1517                    None
1518                } else {
1519                    Some(Err(error))
1520                }
1521            }
1522            Ok(value) => Some(Ok(value)),
1523        }
1524    }
1525}
1526
1527#[cfg(test)]
1528mod tests {
1529    use super::*;
1530    use chrono::DateTime;
1531    use std::vec;
1532
1533    #[test]
1534    fn test_display_symbol() {
1535        assert_eq!(format!("{}", Symbol::from_name("abc")), "abc");
1536        assert_eq!(
1537            format!("{}", Symbol::from_namespace_and_name("abc", "def")),
1538            "abc/def"
1539        );
1540    }
1541
1542    #[test]
1543    fn test_display_keyword() {
1544        assert_eq!(format!("{}", Keyword::from_name("abc")), ":abc");
1545        assert_eq!(
1546            format!("{}", Keyword::from_namespace_and_name("abc", "def")),
1547            ":abc/def"
1548        );
1549    }
1550
1551    #[test]
1552    fn test_access_symbol_parts() {
1553        let sym = Symbol::from_name("abc");
1554        assert_eq!((None, "abc"), (sym.namespace(), sym.name()));
1555
1556        let sym = Symbol::from_namespace_and_name("abc", "def");
1557        assert_eq!((Some("abc"), "def"), (sym.namespace(), sym.name()));
1558    }
1559
1560    #[test]
1561    fn test_access_keyword_parts() {
1562        let kw = Keyword::from_name("abc");
1563        assert_eq!((None, "abc"), (kw.namespace(), kw.name()));
1564
1565        let kw = Keyword::from_namespace_and_name("abc", "def");
1566        assert_eq!((Some("abc"), "def"), (kw.namespace(), kw.name()));
1567    }
1568
1569    #[test]
1570    fn test_parsing_empty_list() {
1571        assert_eq!(Value::List(vec![]), parse_str("()").unwrap())
1572    }
1573
1574    #[test]
1575    fn test_parsing_empty_vector() {
1576        assert_eq!(Value::Vector(vec![]), parse_str("[]").unwrap())
1577    }
1578
1579    #[test]
1580    fn test_parsing_nested_empty_collections() {
1581        assert_eq!(
1582            Value::Vector(vec![
1583                Value::List(vec![]),
1584                Value::Vector(vec![]),
1585                Value::List(vec![]),
1586                Value::Vector(vec![])
1587            ]),
1588            parse_str("[()[]()[]]").unwrap()
1589        )
1590    }
1591
1592    #[test]
1593    fn test_parsing_nested_empty_collections_with_whitespace() {
1594        assert_eq!(
1595            Value::Vector(vec![
1596                Value::List(vec![]),
1597                Value::Vector(vec![]),
1598                Value::List(vec![]),
1599                Value::Vector(vec![])
1600            ]),
1601            parse_str("   ,, , [ ,, , ,()[,,,]( ) []]").unwrap()
1602        )
1603    }
1604
1605    #[test]
1606    fn test_parsing_empty_map() {
1607        assert_eq!(
1608            Value::Map(BTreeMap::from_iter(vec![])),
1609            parse_str("{}").unwrap()
1610        )
1611    }
1612
1613    #[test]
1614    fn test_parsing_uneven_map() {
1615        assert_eq!(
1616            Err(ParserError::OddNumberOfMapElements),
1617            parse_str("{()}").map_err(|err| err.error)
1618        );
1619        assert_eq!(
1620            Err(ParserError::OddNumberOfMapElements),
1621            parse_str("{() [] []}").map_err(|err| err.error)
1622        )
1623    }
1624
1625    #[test]
1626    fn test_parsing_even_map() {
1627        assert_eq!(
1628            Value::Map(BTreeMap::from_iter(vec![(
1629                Value::List(vec![]),
1630                Value::List(vec![])
1631            )])),
1632            parse_str("{() ()}").unwrap()
1633        );
1634        assert_eq!(
1635            Value::Map(BTreeMap::from_iter(vec![
1636                (Value::List(vec![]), Value::Vector(vec![])),
1637                (Value::Keyword(Keyword::from_name("a")), Value::List(vec![]))
1638            ])),
1639            parse_str("{()[] :a ()}").unwrap()
1640        )
1641    }
1642
1643    #[test]
1644    fn test_parsing_duplicate_map_keys() {
1645        assert_eq!(
1646            Value::Map(BTreeMap::from_iter(vec![(
1647                Value::List(vec![]),
1648                Value::List(vec![])
1649            )])),
1650            parse_str("{() ()}").unwrap()
1651        );
1652        assert_eq!(
1653            Err(ParserError::DuplicateKeyInMap {
1654                value: Value::List(vec![])
1655            }),
1656            parse_str("{()[] () ()}").map_err(|err| err.error)
1657        )
1658    }
1659
1660    #[test]
1661    fn test_equals_for_list_and_vector() {
1662        assert!(equal(&Value::List(vec![]), &Value::Vector(vec![])));
1663        assert!(equal(
1664            &Value::List(vec![Value::Boolean(true)]),
1665            &Value::Vector(vec![Value::Boolean(true)])
1666        ));
1667        assert!(!equal(
1668            &Value::List(vec![Value::Boolean(true)]),
1669            &Value::Vector(vec![Value::Boolean(false)])
1670        ));
1671        assert!(!equal(
1672            &Value::List(vec![Value::Boolean(true)]),
1673            &Value::Vector(vec![Value::Boolean(true), Value::Boolean(true)])
1674        ));
1675    }
1676
1677    #[test]
1678    fn test_parsing_string() {
1679        assert_eq!(
1680            Value::String("ꪪ".to_string()),
1681            parse_str("\"\\uAAAA\"").unwrap()
1682        )
1683    }
1684
1685    #[test]
1686    fn test_parsing_string_nested() {
1687        assert_eq!(
1688            Value::Vector(vec![Value::String("ꪪ".to_string())]),
1689            parse_str("[\"\\uAAAA\"]").unwrap()
1690        )
1691    }
1692
1693    #[test]
1694    fn test_parsing_multiline_string() {
1695        assert_eq!(
1696            Value::String("abc\n    \ndef    \n".to_string()),
1697            parse_str("\"abc\n    \ndef    \n\"").unwrap()
1698        )
1699    }
1700
1701    #[test]
1702    fn test_parsing_string_map() {
1703        assert_eq!(
1704            Value::Map(BTreeMap::from_iter(vec![(
1705                Value::String("abc".to_string()),
1706                Value::String("def".to_string())
1707            )])),
1708            parse_str("{\"abc\" \"def\"}").unwrap()
1709        );
1710
1711        assert_eq!(
1712            Value::Map(BTreeMap::from_iter(vec![(
1713                Value::String("abc".to_string()),
1714                Value::String("def".to_string())
1715            )])),
1716            parse_str("{\"abc\"\"def\"}").unwrap()
1717        )
1718    }
1719
1720    #[test]
1721    fn test_parsing_inst() {
1722        assert_eq!(
1723            Value::Inst(DateTime::parse_from_rfc3339("1985-04-12T23:20:50.52Z").unwrap()),
1724            parse_str("#inst\"1985-04-12T23:20:50.52Z\"").unwrap()
1725        )
1726    }
1727
1728    #[test]
1729    fn test_parsing_uuid() {
1730        assert_eq!(
1731            Value::Uuid(Uuid::parse_str("f81d4fae-7dec-11d0-a765-00a0c91e6bf6").unwrap()),
1732            parse_str("#uuid\"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"").unwrap()
1733        )
1734    }
1735
1736    #[test]
1737    fn test_parsing_symbol() {
1738        assert_eq!(
1739            Value::Vector(vec![
1740                Value::Symbol(Symbol::from_name("a")),
1741                Value::Symbol(Symbol::from_name("abc")),
1742                Value::Symbol(Symbol::from_namespace_and_name("abc", "def")),
1743                Value::Symbol(Symbol::from_name("->")),
1744                Value::Symbol(Symbol::from_name("/")),
1745                Value::Symbol(Symbol::from_namespace_and_name("my.org", "stuff")),
1746            ]),
1747            parse_str("[ a  abc abc/def -> / my.org/stuff ]").unwrap()
1748        );
1749    }
1750
1751    #[test]
1752    fn test_parsing_symbol_errs() {
1753        assert_eq!(
1754            Err(ParserError::CannotHaveSlashAtBeginningOfSymbol),
1755            parse_str("/abc").map_err(|err| err.error)
1756        );
1757        assert_eq!(
1758            Err(ParserError::CannotHaveSlashAtEndOfSymbol),
1759            parse_str("abc/").map_err(|err| err.error)
1760        );
1761        assert_eq!(
1762            Err(ParserError::CannotHaveSlashAtEndOfSymbol),
1763            parse_str("abc/ ").map_err(|err| err.error)
1764        );
1765        assert_eq!(
1766            Err(ParserError::CannotHaveSlashAtEndOfSymbol),
1767            parse_str("abc/ []").map_err(|err| err.error)
1768        );
1769        assert_eq!(
1770            Err(ParserError::CannotHaveMoreThanOneSlashInSymbol),
1771            parse_str("a/b/c").map_err(|err| err.error)
1772        );
1773    }
1774
1775    #[test]
1776    fn test_parsing_keyword() {
1777        assert_eq!(
1778            Value::Vector(vec![
1779                Value::Keyword(Keyword::from_name("a")),
1780                Value::Keyword(Keyword::from_name("abc")),
1781                Value::Keyword(Keyword::from_namespace_and_name("abc", "def")),
1782                Value::Keyword(Keyword::from_name("->")),
1783                Value::Keyword(Keyword::from_name("/")),
1784                Value::Keyword(Keyword::from_namespace_and_name("my.org", "stuff")),
1785            ]),
1786            parse_str("[ :a  :abc :abc/def :-> :/ :my.org/stuff ]").unwrap()
1787        );
1788    }
1789
1790    #[test]
1791    fn test_parsing_keyword_errs() {
1792        assert_eq!(
1793            Err(ParserError::CannotHaveSlashAtBeginningOfKeyword),
1794            parse_str(":/abc").map_err(|err| err.error)
1795        );
1796        assert_eq!(
1797            Err(ParserError::CannotHaveSlashAtEndOfKeyword),
1798            parse_str(":abc/").map_err(|err| err.error)
1799        );
1800        assert_eq!(
1801            Err(ParserError::CannotHaveSlashAtEndOfKeyword),
1802            parse_str(":abc/ ").map_err(|err| err.error)
1803        );
1804        assert_eq!(
1805            Err(ParserError::CannotHaveSlashAtEndOfKeyword),
1806            parse_str(":abc/ []").map_err(|err| err.error)
1807        );
1808        assert_eq!(
1809            Err(ParserError::CannotHaveMoreThanOneSlashInKeyword),
1810            parse_str(":a/b/c").map_err(|err| err.error)
1811        );
1812        assert_eq!(
1813            Err(ParserError::CannotHaveColonInKeyword),
1814            parse_str("::namespaced").map_err(|err| err.error)
1815        );
1816    }
1817
1818    #[test]
1819    fn test_parse_set() {
1820        assert_eq!(
1821            Value::Set(BTreeSet::from_iter(
1822                vec![
1823                    Value::Keyword(Keyword::from_name("abc")),
1824                    Value::Keyword(Keyword::from_name("def")),
1825                    Value::Keyword(Keyword::from_namespace_and_name("ghi", "jkl"))
1826                ]
1827                .into_iter()
1828            )),
1829            parse_str("#{:abc :def :ghi/jkl }").unwrap()
1830        );
1831
1832        assert_eq!(
1833            Err(ParserError::DuplicateValueInSet {
1834                value: Value::Symbol(Symbol::from_name("a"))
1835            }),
1836            parse_str("#{a b c d e f a g h}").map_err(|err| err.error)
1837        )
1838    }
1839
1840    #[test]
1841    fn test_set_equals() {
1842        assert!(equal(
1843            &Value::Set(BTreeSet::from_iter(
1844                vec![
1845                    Value::Keyword(Keyword::from_name("def")),
1846                    Value::Keyword(Keyword::from_namespace_and_name("ghi", "jkl")),
1847                    Value::Keyword(Keyword::from_name("abc"))
1848                ]
1849                .into_iter()
1850            )),
1851            &Value::Set(BTreeSet::from_iter(
1852                vec![
1853                    Value::Keyword(Keyword::from_name("abc")),
1854                    Value::Keyword(Keyword::from_name("def")),
1855                    Value::Keyword(Keyword::from_namespace_and_name("ghi", "jkl"))
1856                ]
1857                .into_iter()
1858            ))
1859        ))
1860    }
1861    #[test]
1862    fn test_example_map() {
1863        assert_eq!(
1864            Value::Map(BTreeMap::from_iter(vec![
1865                (
1866                    Value::Keyword(Keyword::from_namespace_and_name("person", "name")),
1867                    Value::String("Joe".to_string())
1868                ),
1869                (
1870                    Value::Keyword(Keyword::from_namespace_and_name("person", "parent")),
1871                    Value::String("Bob".to_string())
1872                ),
1873                (
1874                    Value::Keyword(Keyword::from_name("ssn")),
1875                    Value::String("123".to_string())
1876                ),
1877                (
1878                    Value::Symbol(Symbol::from_name("friends")),
1879                    Value::Vector(vec![
1880                        Value::String("sally".to_string()),
1881                        Value::String("john".to_string()),
1882                        Value::String("linda".to_string())
1883                    ])
1884                ),
1885                (
1886                    Value::String("other".to_string()),
1887                    Value::Map(BTreeMap::from_iter(vec![(
1888                        Value::Keyword(Keyword::from_name("stuff")),
1889                        Value::Keyword(Keyword::from_name("here"))
1890                    )]))
1891                )
1892            ])),
1893            parse_str(
1894                "\
1895            {:person/name \"Joe\"\
1896             :person/parent \"Bob\"\
1897             :ssn \"123\"\
1898             friends [\"sally\" \"john\" \"linda\"]\
1899             \"other\" {:stuff :here}}"
1900            )
1901            .unwrap()
1902        )
1903    }
1904
1905    #[test]
1906    fn test_basic_keyword_and_symbol() {
1907        assert!(equal(
1908            &parse_str("name").unwrap(),
1909            &parse_str("name").unwrap()
1910        ));
1911        assert!(equal(
1912            &parse_str("person/name").unwrap(),
1913            &parse_str("person/name").unwrap()
1914        ));
1915        assert!(equal(
1916            &parse_str(":name").unwrap(),
1917            &parse_str(":name").unwrap()
1918        ));
1919        assert!(equal(
1920            &parse_str(":person/name").unwrap(),
1921            &parse_str(":person/name").unwrap()
1922        ));
1923
1924        // Had an issue with whitespace
1925        assert!(equal(
1926            &parse_str("name ").unwrap(),
1927            &parse_str("name ").unwrap()
1928        ));
1929        assert!(equal(
1930            &parse_str("person/name ").unwrap(),
1931            &parse_str("person/name ").unwrap()
1932        ));
1933        assert!(equal(
1934            &parse_str(":name ").unwrap(),
1935            &parse_str(":name ").unwrap()
1936        ));
1937        assert!(equal(
1938            &parse_str(":person/name ").unwrap(),
1939            &parse_str(":person/name ").unwrap()
1940        ));
1941    }
1942
1943    #[test]
1944    fn test_complex_equals() {
1945        assert!(equal(
1946            &parse_str(
1947                "\
1948            {:person/parent \"Bob\"\
1949             :person/name \"Joe\"\
1950             :ssn \"123\"\
1951             friends [\"sally\" \"john\" \"linda\"]\
1952             \"other\" {:stuff :here}}"
1953            )
1954            .unwrap(),
1955            &parse_str(
1956                "\
1957            {:person/name \"Joe\"\
1958             :person/parent \"Bob\"\
1959             :ssn \"123\"\
1960             friends [\"sally\" \"john\" \"linda\"]\
1961             \"other\" {:stuff :here}}"
1962            )
1963            .unwrap()
1964        ))
1965    }
1966
1967    #[test]
1968    fn test_nil_false_true() {
1969        assert_eq!(
1970            Value::List(vec![
1971                Value::Nil,
1972                Value::Boolean(false),
1973                Value::Boolean(true)
1974            ]),
1975            parse_str("(nil false true)").unwrap()
1976        )
1977    }
1978
1979    #[test]
1980    fn test_parse_char() {
1981        assert_eq!(Value::Character('a'), parse_str("\\a").unwrap());
1982        assert_eq!(Value::Character(' '), parse_str("\\space").unwrap());
1983        assert_eq!(Value::Character('\n'), parse_str("\\newline").unwrap());
1984        assert_eq!(Value::Character('\t'), parse_str("\\tab").unwrap());
1985        assert_eq!(Value::Character('\\'), parse_str("\\\\").unwrap());
1986        assert_eq!(Value::Character('a'), parse_str("\\u0061").unwrap());
1987        assert_eq!(
1988            Value::Vector(vec![Value::Character('e'), Value::Character('d')]),
1989            parse_str("[\\e \\d]").unwrap()
1990        );
1991        assert_eq!(
1992            Value::Map(BTreeMap::from_iter(vec![
1993                (Value::Character(' '), Value::Character('z')),
1994                (Value::Character('a'), Value::Character('\n')),
1995                (Value::Character('b'), Value::Character('\r')),
1996                (Value::Character('r'), Value::Character('c')),
1997                (Value::Character('\t'), Value::Character('d')),
1998            ])),
1999            parse_str("{\\space \\z\\a \\newline \\b \\return \\r \\c \\tab \\d}").unwrap()
2000        )
2001    }
2002
2003    #[test]
2004    fn test_parse_int() {
2005        assert_eq!(Value::Integer(123), parse_str("123").unwrap())
2006    }
2007
2008    #[test]
2009    fn test_parse_float() {
2010        assert_eq!(Value::Float(OrderedFloat(12.1)), parse_str("12.1").unwrap())
2011    }
2012
2013    #[test]
2014    fn test_parse_neg_int() {
2015        assert_eq!(Value::Integer(-123), parse_str("-123").unwrap())
2016    }
2017
2018    #[test]
2019    fn test_parse_neg_float() {
2020        assert_eq!(
2021            Value::Float(OrderedFloat(-12.1)),
2022            parse_str("-12.1").unwrap()
2023        )
2024    }
2025
2026    #[test]
2027    fn test_parse_pos_int() {
2028        assert_eq!(Value::Integer(123), parse_str("+123").unwrap())
2029    }
2030
2031    #[test]
2032    fn test_parse_pos_float() {
2033        assert_eq!(
2034            Value::Float(OrderedFloat(12.1)),
2035            parse_str("+12.1").unwrap()
2036        )
2037    }
2038
2039    #[test]
2040    fn test_parse_zero() {
2041        assert_eq!(Value::Integer(0), parse_str("+0").unwrap(),);
2042        assert_eq!(Value::Integer(0), parse_str("0").unwrap(),);
2043        assert_eq!(Value::Integer(0), parse_str("-0").unwrap(),);
2044    }
2045
2046    #[test]
2047    fn test_parse_zero_float() {
2048        assert_eq!(Value::Float(OrderedFloat(0f64)), parse_str("+0.").unwrap());
2049        assert_eq!(Value::Float(OrderedFloat(0f64)), parse_str("0.").unwrap());
2050        assert_eq!(Value::Float(OrderedFloat(0f64)), parse_str("-0.").unwrap());
2051    }
2052
2053    #[test]
2054    fn test_parse_e() {
2055        assert_eq!(
2056            Value::Float(OrderedFloat(1000.0)),
2057            parse_str("10e+2").unwrap()
2058        );
2059        assert_eq!(
2060            Value::Float(OrderedFloat(1200.0)),
2061            parse_str("12e+2").unwrap()
2062        );
2063        assert_eq!(
2064            Value::Float(OrderedFloat(1200.0)),
2065            parse_str("12e2").unwrap()
2066        );
2067        assert_eq!(
2068            Value::Float(OrderedFloat(1200.0)),
2069            parse_str("12E2").unwrap()
2070        );
2071        assert_eq!(
2072            Value::Float(OrderedFloat(5200.0)),
2073            parse_str("52E+2").unwrap()
2074        );
2075        assert_eq!(
2076            Value::Float(OrderedFloat(1.2)),
2077            parse_str("120e-2").unwrap()
2078        );
2079        assert_eq!(
2080            Value::Float(OrderedFloat(1.2)),
2081            parse_str("120E-2").unwrap()
2082        );
2083        assert_eq!(
2084            Value::Float(OrderedFloat(1422141241242142142141241.124)),
2085            parse_str("1422141241242142142141241.124E0").unwrap()
2086        );
2087    }
2088
2089    #[test]
2090    fn test_parse_bigint() {
2091        assert_eq!(Value::BigInt(BigInt::from(123)), parse_str("123N").unwrap());
2092    }
2093
2094    #[test]
2095    fn test_parse_bigdec() {
2096        assert_eq!(
2097            Value::BigDec(BigDecimal::from(123)),
2098            parse_str("123M").unwrap()
2099        );
2100    }
2101
2102    #[test]
2103    fn test_bad_bigdec() {
2104        assert!(match parse_str("12a3M").map_err(|err| err.error) {
2105            Err(ParserError::BadBigDec { .. }) => true,
2106            _ => false,
2107        });
2108    }
2109
2110    #[test]
2111    fn test_bad_bigint() {
2112        assert!(match parse_str("12a3N").map_err(|err| err.error) {
2113            Err(ParserError::BadBigInt { .. }) => true,
2114            _ => false,
2115        });
2116    }
2117
2118    #[test]
2119    fn test_with_comments() {
2120        assert_eq!(
2121            Value::List(
2122                vec![
2123                    Value::Integer(1),
2124                    Value::Integer(2),
2125                    Value::Integer(3),
2126                    Value::String("abc".to_string()),
2127                    Value::Vector(
2128                        vec![
2129                            Value::Symbol(Symbol::from_name("a")),
2130                            Value::Symbol(Symbol::from_namespace_and_name("b", "qq")),
2131                            Value::Symbol(Symbol::from_name("c")),
2132                            Value::Map(BTreeMap::from_iter(vec![
2133                                (Value::Integer(12), Value::Float(OrderedFloat(34.5))),
2134                                (Value::Keyword(Keyword::from_name("a")),
2135                                 Value::Symbol(Symbol::from_name("b")))
2136                            ]))
2137                        ]
2138                    )
2139                ]
2140
2141            ),
2142            parse_str("( 1 2 3 \"abc\"\n;; so here is where we do some wacky stuff \n [a b/qq ; and then here\n c \n \n;; aaa\n{12 34.5 :a \n;;aaadeafaef\nb}])").unwrap()
2143        );
2144    }
2145
2146    #[test]
2147    fn test_round_trips() {
2148        let v1 = Value::List(vec![
2149            Value::Integer(1),
2150            Value::Integer(2),
2151            Value::Integer(3),
2152            Value::String("abc".to_string()),
2153            Value::Vector(vec![
2154                Value::Symbol(Symbol::from_name("a")),
2155                Value::Symbol(Symbol::from_namespace_and_name("b", "qq")),
2156                Value::Symbol(Symbol::from_name("c")),
2157                Value::Map(BTreeMap::from_iter(vec![
2158                    (Value::Integer(12), Value::Float(OrderedFloat(34.5))),
2159                    (
2160                        Value::Keyword(Keyword::from_name("a")),
2161                        Value::Symbol(Symbol::from_name("b")),
2162                    ),
2163                ])),
2164            ]),
2165        ]);
2166        let v2 = Value::Map(BTreeMap::from_iter(vec![
2167            (
2168                Value::Keyword(Keyword::from_namespace_and_name("person", "name")),
2169                Value::String("Joe".to_string()),
2170            ),
2171            (
2172                Value::Keyword(Keyword::from_namespace_and_name("person", "parent")),
2173                Value::String("Bob".to_string()),
2174            ),
2175            (
2176                Value::Keyword(Keyword::from_name("ssn")),
2177                Value::String("123".to_string()),
2178            ),
2179            (
2180                Value::Symbol(Symbol::from_name("friends")),
2181                Value::Vector(vec![
2182                    Value::String("sally".to_string()),
2183                    Value::String("john".to_string()),
2184                    Value::String("linda".to_string()),
2185                ]),
2186            ),
2187            (
2188                Value::String("other".to_string()),
2189                Value::Map(BTreeMap::from_iter(vec![(
2190                    Value::Keyword(Keyword::from_name("stuff")),
2191                    Value::Keyword(Keyword::from_name("here")),
2192                )])),
2193            ),
2194            (
2195                Value::Inst(DateTime::parse_from_rfc3339("1985-04-12T23:20:50.52Z").unwrap()),
2196                Value::Set(BTreeSet::from_iter(
2197                    vec![
2198                        Value::TaggedElement(
2199                            Symbol::from_namespace_and_name("person", "ssn"),
2200                            Box::new(Value::String("123".to_string())),
2201                        ),
2202                        Value::Nil,
2203                        Value::Boolean(false),
2204                        Value::List(vec![
2205                            Value::Integer(1),
2206                            Value::Float(OrderedFloat(2.0)),
2207                            Value::BigDec(BigDecimal::from((BigInt::from(4), 9))),
2208                            Value::BigInt(BigInt::from(4)),
2209                        ]),
2210                    ]
2211                    .into_iter(),
2212                )),
2213            ),
2214        ]));
2215        assert_eq!(emit_str(&v1), emit_str(&parse_str(&emit_str(&v1)).unwrap()));
2216        assert_eq!(emit_str(&v2), emit_str(&parse_str(&emit_str(&v2)).unwrap()));
2217
2218        assert_eq!(
2219            parse_str(&emit_str(&v1)).unwrap(),
2220            parse_str(&emit_str(&parse_str(&emit_str(&v1)).unwrap())).unwrap()
2221        );
2222        assert_eq!(
2223            parse_str(&emit_str(&v2)).unwrap(),
2224            parse_str(&emit_str(&parse_str(&emit_str(&v2)).unwrap())).unwrap()
2225        );
2226    }
2227
2228    #[test]
2229    fn test_big_vector() {
2230        let mut vals: Vec<Value> = vec![];
2231        for i in 0..100000 {
2232            vals.push(Value::Integer(i))
2233        }
2234        let ser = emit_str(&Value::Vector(vals.clone()));
2235        // shouldn't stack overflow
2236        assert_eq!(parse_str(&ser).unwrap(), Value::Vector(vals));
2237    }
2238
2239    #[test]
2240    fn test_big_list() {
2241        let mut vals: Vec<Value> = vec![];
2242        for i in 0..100000 {
2243            vals.push(Value::Integer(i))
2244        }
2245        let ser = emit_str(&Value::List(vals.clone()));
2246        assert_eq!(parse_str(&ser).unwrap(), Value::List(vals));
2247    }
2248
2249    #[test]
2250    fn test_big_set() {
2251        let mut vals: Vec<Value> = vec![];
2252        for i in 0..100000 {
2253            vals.push(Value::Integer(i))
2254        }
2255        let ser = emit_str(&Value::Set(BTreeSet::from_iter(vals.clone())));
2256        assert_eq!(
2257            parse_str(&ser).unwrap(),
2258            Value::Set(BTreeSet::from_iter(vals))
2259        );
2260    }
2261
2262    #[test]
2263    fn test_big_map() {
2264        let mut vals: Vec<(Value, Value)> = vec![];
2265        for i in 0..10000 {
2266            vals.push((
2267                Value::Keyword(Keyword::from_name(&i.to_string())),
2268                Value::Integer(i),
2269            ))
2270        }
2271        let ser = emit_str(&Value::Map(BTreeMap::from_iter(vals.clone())));
2272        assert_eq!(
2273            parse_str(&ser).unwrap(),
2274            Value::Map(BTreeMap::from_iter(vals))
2275        );
2276    }
2277
2278    #[test]
2279    fn test_two_colons() {
2280        assert_eq!(
2281            Err(ParserError::CannotHaveColonInKeyword),
2282            parse_str("::").map_err(|err| err.error)
2283        )
2284    }
2285
2286    #[test]
2287    fn test_row_col_tracking() {
2288        assert_eq!(
2289            Err(ParserErrorWithContext {
2290                context: vec![Context::ParsingAtom { row: 5, col: 1 }],
2291                row: 6,
2292                col: 1,
2293                error: ParserError::CannotHaveColonInKeyword
2294            }),
2295            parse_str("    ::",)
2296        );
2297        assert_eq!(
2298            Err(ParserErrorWithContext {
2299                context: Vec::new(),
2300                row: 0,
2301                col: 1,
2302                error: ParserError::EmptyInput
2303            }),
2304            parse_str("",)
2305        );
2306        assert_eq!(
2307            Err(ParserErrorWithContext {
2308                context: vec![Context::ParsingAtom { row: 4, col: 1 }],
2309                row: 5,
2310                col: 1,
2311                error: ParserError::CannotHaveColonInKeyword
2312            }),
2313            parse_str("   ::",)
2314        );
2315        assert_eq!(
2316            Err(ParserErrorWithContext {
2317                context: vec![Context::ParsingAtom { row: 1, col: 3 }],
2318                row: 2,
2319                col: 3,
2320                error: ParserError::CannotHaveColonInKeyword
2321            }),
2322            parse_str("   \n\n::",)
2323        );
2324    }
2325
2326    #[test]
2327    fn test_context_maintaining() {
2328        assert_eq!(
2329            Err(ParserErrorWithContext {
2330                context: vec![
2331                    Context::ParsingVector { row: 2, col: 1 },
2332                    Context::ParsingAtom { row: 8, col: 1 }
2333                ],
2334                row: 10,
2335                col: 1,
2336                error: ParserError::CannotHaveColonInKeyword
2337            }),
2338            parse_str(" [ 1 2 ::a]",)
2339        );
2340
2341        assert_eq!(
2342            Err(ParserErrorWithContext {
2343                context: vec![
2344                    Context::ParsingList { row: 2, col: 1 },
2345                    Context::ParsingSet { row: 2, col: 2 },
2346                    Context::ParsingMap { row: 1, col: 3 },
2347                    Context::ParsingVector { row: 3, col: 3 },
2348                    Context::ParsingAtom { row: 3, col: 5 }
2349                ],
2350                row: 5,
2351                col: 5,
2352                error: ParserError::CannotHaveColonInKeyword
2353            }),
2354            parse_str(" ( a b c \n#{ \n{ [ \n1 2 4\n  ::a  \n3]  3} } )",)
2355        );
2356        assert_eq!(
2357            Err(ParserErrorWithContext {
2358                context: vec![Context::ParsingList { row: 2, col: 1 }],
2359                row: 8,
2360                col: 1,
2361                error: ParserError::UnexpectedEndOfInput
2362            }),
2363            parse_str(" ( [] {}",)
2364        );
2365    }
2366
2367    #[test]
2368    fn test_namespaced_maps() {
2369        assert_eq!(
2370            Value::Map(BTreeMap::from_iter(vec![
2371                (
2372                    Value::Keyword(Keyword::from_namespace_and_name("apple.tree", "c")),
2373                    Value::Integer(1)
2374                ),
2375                (Value::String("a".to_string()), Value::Integer(2)),
2376                (
2377                    Value::Keyword(Keyword::from_namespace_and_name("apple.tree", "d")),
2378                    Value::Integer(3)
2379                ),
2380                (
2381                    Value::Keyword(Keyword::from_namespace_and_name("d.e", "f")),
2382                    Value::Keyword(Keyword::from_name("a"))
2383                ),
2384            ])),
2385            parse_str_with_options(
2386                "#:apple.tree{:c 1 \"a\" 2 :d 3 :d.e/f :a}",
2387                ParserOptions {
2388                    allow_namespaced_map_syntax: true,
2389                    ..ParserOptions::default()
2390                }
2391            )
2392            .unwrap()
2393        )
2394    }
2395
2396    #[test]
2397    fn test_parsing_symbols_that_might_be_mistaken_for_numbers() {
2398        assert_eq!(
2399            parse_str("a1b").unwrap(),
2400            Value::Symbol(Symbol::from_name("a1b"))
2401        );
2402        assert_eq!(
2403            parse_str("ab1").unwrap(),
2404            Value::Symbol(Symbol::from_name("ab1"))
2405        );
2406        assert_eq!(
2407            parse_str("ab1/c1d").unwrap(),
2408            Value::Symbol(Symbol::from_namespace_and_name("ab1", "c1d"))
2409        );
2410        assert_eq!(
2411            parse_str("ab1/cd1").unwrap(),
2412            Value::Symbol(Symbol::from_namespace_and_name("ab1", "cd1"))
2413        )
2414    }
2415
2416    #[test]
2417    fn test_bad_unicode_string_escape() {
2418        assert_eq!(
2419            parse_str("\"\\u\"").map_err(|err| err.error),
2420            Err(ParserError::InvalidStringEscape)
2421        );
2422        assert_eq!(
2423            parse_str("\"\\u1\"").map_err(|err| err.error),
2424            Err(ParserError::InvalidStringEscape)
2425        );
2426        assert_eq!(
2427            parse_str("\"\\u12\"").map_err(|err| err.error),
2428            Err(ParserError::InvalidStringEscape)
2429        );
2430        assert_eq!(
2431            parse_str("\"\\u123\"").map_err(|err| err.error),
2432            Err(ParserError::InvalidStringEscape)
2433        );
2434
2435        assert_eq!(
2436            parse_str("\"\\u").map_err(|err| err.error),
2437            Err(ParserError::InvalidStringEscape)
2438        );
2439        assert_eq!(
2440            parse_str("\"\\u\"").map_err(|err| err.error),
2441            Err(ParserError::InvalidStringEscape)
2442        );
2443        assert_eq!(
2444            parse_str("\"\\u1").map_err(|err| err.error),
2445            Err(ParserError::InvalidStringEscape)
2446        );
2447        assert_eq!(
2448            parse_str("\"\\u12").map_err(|err| err.error),
2449            Err(ParserError::InvalidStringEscape)
2450        );
2451        assert_eq!(
2452            parse_str("\"\\u123").map_err(|err| err.error),
2453            Err(ParserError::InvalidStringEscape)
2454        );
2455    }
2456
2457    // Tests here taken from
2458    // https://github.com/utkarshkukreti/edn.rs/blob/master/tests/from_tests.rs#L9
2459    #[test]
2460    fn from_bool() {
2461        assert_eq!(Value::from(true), Value::Boolean(true));
2462        assert_eq!(Value::from(false), Value::Boolean(false));
2463    }
2464    #[test]
2465    fn from_str() {
2466        assert_eq!(Value::from(""), Value::String("".to_string()));
2467        assert_eq!(Value::from("hello"), Value::String("hello".to_string()));
2468    }
2469
2470    #[test]
2471    fn from_string() {
2472        assert_eq!(Value::from("".to_string()), Value::String("".to_string()));
2473        assert_eq!(
2474            Value::from("hello".to_string()),
2475            Value::String("hello".to_string())
2476        );
2477    }
2478
2479    #[test]
2480    fn from_char() {
2481        assert_eq!(Value::from('c'), Value::Character('c'));
2482    }
2483
2484    #[test]
2485    fn from_num() {
2486        assert_eq!(Value::from(0_i64), Value::Integer(0));
2487        assert_eq!(Value::from(0), Value::Integer(0));
2488        assert_eq!(Value::from(-1i64), Value::Integer(-1));
2489        assert_eq!(Value::from(1_u32), Value::Integer(1));
2490        assert_eq!(Value::from(2_i32), Value::Integer(2));
2491        assert_eq!(Value::from(3_f32), Value::Float(OrderedFloat(3.0)));
2492
2493        assert_eq!(Value::from(0_f64), Value::Float(OrderedFloat(0_f64)));
2494        assert_eq!(Value::from(0_f64), Value::Float(OrderedFloat(0_f64)));
2495
2496        assert_eq!(Value::from(0_f64), Value::Float(OrderedFloat(0_f64)));
2497        assert_eq!(
2498            Value::from(OrderedFloat(0_f64)),
2499            Value::Float(OrderedFloat(0_f64))
2500        );
2501    }
2502    // -------------------------------------------------------------------------
2503
2504    #[test]
2505    fn from_unit() {
2506        assert_eq!(Value::Nil, Value::from(()))
2507    }
2508
2509    #[test]
2510    fn from_symbol() {
2511        assert_eq!(
2512            Value::Symbol(Symbol::from_name("abc")),
2513            Value::from(Symbol::from_name("abc"))
2514        );
2515
2516        assert_eq!(
2517            Value::Symbol(Symbol::from_namespace_and_name("abc", "def")),
2518            Value::from(Symbol::from_namespace_and_name("abc", "def"))
2519        );
2520    }
2521
2522    #[test]
2523    fn from_keyword() {
2524        assert_eq!(
2525            Value::Keyword(Keyword::from_name("abc")),
2526            Value::from(Keyword::from_name("abc"))
2527        );
2528
2529        assert_eq!(
2530            Value::Keyword(Keyword::from_namespace_and_name("abc", "def")),
2531            Value::from(Keyword::from_namespace_and_name("abc", "def"))
2532        );
2533    }
2534
2535    #[test]
2536    fn from_bigint() {
2537        assert_eq!(
2538            Value::BigInt(BigInt::from(123)),
2539            Value::from(BigInt::from(123))
2540        );
2541    }
2542
2543    #[test]
2544    fn from_bigdec() {
2545        assert_eq!(
2546            Value::BigDec(BigDecimal::from(123)),
2547            Value::from(BigDecimal::from(123))
2548        );
2549    }
2550
2551    #[test]
2552    fn from_datetime() {
2553        assert_eq!(
2554            Value::Inst(DateTime::parse_from_rfc3339("1985-04-12T23:20:50.52Z").unwrap()),
2555            Value::from(DateTime::parse_from_rfc3339("1985-04-12T23:20:50.52Z").unwrap())
2556        )
2557    }
2558
2559    #[test]
2560    fn from_uuid() {
2561        assert_eq!(
2562            Value::Uuid(Uuid::parse_str("f81d4fae-7dec-11d0-a765-00a0c91e6bf6").unwrap()),
2563            Value::from(Uuid::parse_str("f81d4fae-7dec-11d0-a765-00a0c91e6bf6").unwrap())
2564        )
2565    }
2566
2567    #[test]
2568    fn test_symbols_with_colons() {
2569        assert_eq!(
2570            parse_str("a:").map_err(|err| err.error),
2571            Err(ParserError::CannotHaveColonInSymbol)
2572        );
2573        assert_eq!(
2574            parse_str("a:b").map_err(|err| err.error),
2575            Err(ParserError::CannotHaveColonInSymbol)
2576        );
2577        assert_eq!(
2578            parse_str("a:b/c").map_err(|err| err.error),
2579            Err(ParserError::CannotHaveColonInSymbol)
2580        );
2581        assert_eq!(
2582            parse_str("ab/c:").map_err(|err| err.error),
2583            Err(ParserError::CannotHaveColonInSymbol)
2584        );
2585        assert_eq!(
2586            parse_str("ab/c:d").map_err(|err| err.error),
2587            Err(ParserError::CannotHaveColonInSymbol)
2588        );
2589        assert_eq!(
2590            parse_str("ab/c: ").map_err(|err| err.error),
2591            Err(ParserError::CannotHaveColonInSymbol)
2592        );
2593    }
2594
2595    #[test]
2596    fn test_many_values() {
2597        let mut parser = Parser::from_str("123 456 [] [[]]", ParserOptions::default());
2598        assert_eq!(
2599            (
2600                Some(Ok(Value::from(123))),
2601                Some(Ok(Value::from(456))),
2602                Some(Ok(Value::Vector(vec![]))),
2603                Some(Ok(Value::Vector(vec![Value::Vector(vec![])]))),
2604                None,
2605                None
2606            ),
2607            (
2608                parser.next(),
2609                parser.next(),
2610                parser.next(),
2611                parser.next(),
2612                parser.next(),
2613                parser.next()
2614            )
2615        )
2616    }
2617
2618    #[test]
2619    fn test_many_values_with_errors() {
2620        let mut parser = Parser::from_str("123 456 :: [] :: [[]]", ParserOptions::default());
2621        assert_eq!(
2622            (
2623                Some(Ok(Value::from(123))),
2624                Some(Ok(Value::from(456))),
2625                Some(Err(ParserError::CannotHaveColonInKeyword)),
2626                Some(Ok(Value::Vector(vec![]))),
2627                Some(Err(ParserError::CannotHaveColonInKeyword)),
2628                Some(Ok(Value::Vector(vec![Value::Vector(vec![])]))),
2629                None,
2630                None
2631            ),
2632            (
2633                parser.next(),
2634                parser.next(),
2635                parser.next(),
2636                parser.next(),
2637                parser.next(),
2638                parser.next(),
2639                parser.next(),
2640                parser.next()
2641            )
2642        );
2643    }
2644
2645    #[test]
2646    fn test_many_values_with_errors_iter() {
2647        let mut parser = Parser::from_iter(
2648            "123 456 :: [] :: [[]] ({#{}\"\"})".chars(),
2649            ParserOptions::default(),
2650        );
2651        assert_eq!(
2652            (
2653                Some(Ok(Value::from(123))),
2654                Some(Ok(Value::from(456))),
2655                Some(Err(ParserError::CannotHaveColonInKeyword)),
2656                Some(Ok(Value::Vector(vec![]))),
2657                Some(Err(ParserError::CannotHaveColonInKeyword)),
2658                Some(Ok(Value::Vector(vec![Value::Vector(vec![])]))),
2659                Some(Ok(Value::List(vec![Value::Map(BTreeMap::from([(
2660                    Value::Set(BTreeSet::new()),
2661                    Value::from("")
2662                )]))]))),
2663                None,
2664                None
2665            ),
2666            (
2667                parser.next(),
2668                parser.next(),
2669                parser.next(),
2670                parser.next(),
2671                parser.next(),
2672                parser.next(),
2673                parser.next(),
2674                parser.next(),
2675                parser.next()
2676            )
2677        );
2678    }
2679
2680    #[test]
2681    fn test_only_zero_can_start_like_zero() {
2682        assert_eq!(
2683            parse_str("08").map_err(|err| err.error),
2684            Err(ParserError::OnlyZeroCanStartWithZero)
2685        )
2686    }
2687
2688    #[test]
2689    fn test_bad_float() {
2690        assert!(match parse_str("8.j4").map_err(|err| err.error) {
2691            Err(ParserError::BadFloat { .. }) => true,
2692            _ => false,
2693        })
2694    }
2695
2696    #[test]
2697    fn test_bad_int() {
2698        assert!(match parse_str("8j4").map_err(|err| err.error) {
2699            Err(ParserError::BadInt { .. }) => true,
2700            _ => false,
2701        })
2702    }
2703
2704    #[test]
2705    fn test_symbol_starting_like_number() {
2706        assert!(match parse_str("8j/ab").map_err(|err| err.error) {
2707            Err(ParserError::InvalidSymbol) => true,
2708            _ => false,
2709        })
2710    }
2711    #[test]
2712    fn test_comments() {
2713        assert_eq!(
2714            Ok(Value::from(Symbol::from_name("ced"))),
2715            parse_str(";; abc \n ;; def \n\n ced").map_err(|err| err.error)
2716        )
2717    }
2718
2719    #[test]
2720    fn test_parse_immediately_ending_vector() {
2721        assert_eq!(
2722            Err(ParserError::UnexpectedEndOfInput),
2723            parse_str("[").map_err(|err| err.error)
2724        )
2725    }
2726
2727    #[test]
2728    fn test_string_with_semicolon_in_it() {
2729        assert_eq!(
2730            Ok(Value::from("hello ;;;; world")),
2731            parse_str("\"hello ;;;; world\"").map_err(|err| err.error)
2732        )
2733    }
2734
2735    #[test]
2736    fn test_string_escapes() {
2737        assert_eq!(
2738            Ok(Value::from("\t\n\\\"\r")),
2739            parse_str("\"\\t\\n\\\\\\\"\\r\"").map_err(|err| err.error)
2740        )
2741    }
2742
2743    #[test]
2744    fn test_bad_string_escape() {
2745        assert_eq!(
2746            Err(ParserError::InvalidStringEscape),
2747            parse_str("\"\\f\"").map_err(|err| err.error)
2748        )
2749    }
2750
2751    #[test]
2752    fn test_nothing_after_dispatch_char() {
2753        assert_eq!(
2754            Err(ParserError::UnexpectedEndOfInput),
2755            parse_str("#").map_err(|err| err.error)
2756        )
2757    }
2758
2759    #[test]
2760    fn test_drop_form() {
2761        assert_eq!(
2762            Ok(Value::Vector(vec![
2763                Value::from(1),
2764                Value::from(2),
2765                Value::from(3)
2766            ])),
2767            parse_str("[ 1 #_(3 4) #_{} #_[a a a a a a a] 2 #_\"aaa\" 3]").map_err(|err| err.error)
2768        )
2769    }
2770
2771    #[test]
2772    fn test_comment_with_spaces() {
2773        let parse = parse_str(";; abc\n;; def \n\n ced");
2774        assert_eq!(Ok(Value::from(Symbol::from_name("ced"))), parse);
2775    }
2776}