cirru_edn 0.7.5

Parser/Writer for Cirru EDN
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! # Cirru EDN
//!
//! Extensible Data Notation (EDN) implementation using Cirru syntax.
//!
//! This crate provides a data format similar to EDN but using Cirru's syntax instead of
//! traditional s-expressions. It supports rich data types including primitives, collections,
//! and special constructs like records and tuples.
//!
//! ## Features
//!
//! - **Rich data types**: nil, boolean, number, string, symbol, tag, list, set, map, record, tuple, buffer, atom
//! - **Serde integration**: Seamless serialization/deserialization with Rust structs
//! - **Efficient string handling**: Uses `Arc<str>` for string deduplication
//! - **Runtime references**: Support for arbitrary Rust data via `AnyRef`
//! - **Type-safe API**: Strong typing with convenient conversion methods
//!
//! ## Basic Usage
//!
//! ```rust
//! use cirru_edn::{parse, format, Edn};
//!
//! // Parse Cirru EDN from string
//! let data = parse("[] 1 2 3").unwrap();
//!
//! // Create EDN values programmatically
//! let map = Edn::map_from_iter([
//!     (Edn::tag("name"), Edn::str("Alice")),
//!     (Edn::tag("age"), Edn::Number(30.0)),
//! ]);
//!
//! // Format back to string
//! let formatted = format(&map, true).unwrap();
//! ```
//!
//! ## Type Checking and Conversion
//!
//! The library provides type-safe methods for checking and converting values:
//!
//! ```rust
//! use cirru_edn::Edn;
//!
//! let value = Edn::Number(42.0);
//!
//! // Type checking
//! assert!(value.is_number());
//! assert!(!value.is_string());
//!
//! // Safe conversion
//! let number: f64 = value.read_number().unwrap();
//! assert_eq!(number, 42.0);
//!
//! // Get type name for debugging
//! assert_eq!(value.type_name(), "number");
//! ```
//!
//! ## Working with Collections
//!
//! ```rust
//! use cirru_edn::Edn;
//!
//! // Create and access lists
//! let list = Edn::List(vec![
//!     Edn::Number(1.0),
//!     Edn::str("hello"),
//!     Edn::Bool(true)
//! ].into());
//!
//! if let Some(first) = list.get_list_item(0) {
//!     assert_eq!(first.read_number().unwrap(), 1.0);
//! }
//!
//! // Create and access maps
//! let map = Edn::map_from_iter([
//!     (Edn::tag("name"), Edn::str("Bob")),
//!     (Edn::tag("age"), Edn::Number(25.0)),
//! ]);
//!
//! if let Some(name) = map.get_map_value(&Edn::tag("name")) {
//!     assert_eq!(name.read_string().unwrap(), "Bob");
//! }
//! ```
//!
//! ## Serde Integration
//!
//! The crate includes built-in serde support for seamless serialization:
//!
//! ```rust
//! use cirru_edn::{to_edn, from_edn};
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct Person {
//!     name: String,
//!     age: u32,
//! }
//!
//! let person = Person { name: "Bob".to_string(), age: 25 };
//! let edn_value = to_edn(&person).unwrap();
//! let recovered: Person = from_edn(edn_value).unwrap();
//! ```

mod edn;
mod error;
mod tag;

pub mod serde_support;

use std::cmp::Ordering::*;
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;
use std::sync::Arc;
use std::vec;

use cirru_parser::Cirru;

pub use edn::{
  DynEq, Edn, EdnAnyRef, EdnListView, EdnMapView, EdnRecordView, EdnSetView, EdnTupleView, is_simple_char,
};
pub use error::{EdnError, EdnResult, Position};
pub use tag::EdnTag;

/// Returns the version of the crate.
pub fn version() -> &'static str {
  env!("CARGO_PKG_VERSION")
}

// Backward compatible type alias
#[deprecated(since = "0.7.0", note = "Use EdnError instead")]
pub type EdnResultString<T> = Result<T, String>;

// Convenience type aliases for common patterns
pub type EdnList = EdnListView;
pub type EdnMap = EdnMapView;
pub type EdnSet = EdnSetView;
pub type EdnRecord = EdnRecordView;
pub type EdnTuple = EdnTupleView;

// Common constants for convenience
impl Edn {
  /// Predefined nil constant for convenience
  pub const NIL: Edn = Edn::Nil;

  /// Predefined true constant for convenience
  pub const TRUE: Edn = Edn::Bool(true);

  /// Predefined false constant for convenience
  pub const FALSE: Edn = Edn::Bool(false);

  /// Convert an EDN value into a Cirru AST node.
  pub fn cirru(&self) -> Cirru {
    assemble_cirru_node(self)
  }
}

pub use serde_support::{from_edn, to_edn};

/// Parse Cirru code into Edn data.
///
/// This function takes a string containing Cirru syntax and converts it into an Edn value.
/// The input must contain exactly one expression.
///
/// # Arguments
///
/// * `s` - A string slice containing the Cirru code to parse
///
/// # Returns
///
/// * `Result<Edn, String>` - Returns the parsed Edn value on success, or an error message on failure
///
/// # Examples
///
/// ```
/// use cirru_edn::parse;
///
/// // Parse a simple number
/// let result = parse("do 42").unwrap();
///
/// // Parse a list
/// let result = parse("[] 1 2 3").unwrap();
///
/// // Parse a map
/// let result = parse("{} (:name |Alice) (:age 30)").unwrap();
///
/// // Parse nested structures
/// let result = parse("{} (:items $ [] 1 2 3) (:meta $ {} (:version 1))").unwrap();
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The input contains no expressions or more than one expression
/// - The syntax is invalid
/// - The input contains unsupported constructs
pub fn parse(s: &str) -> EdnResult<Edn> {
  let xs = cirru_parser::parse(s).map_err(|e| EdnError::from_parse_error_detailed(e, s))?;
  if xs.len() == 1 {
    match &xs[0] {
      Cirru::Leaf(s) => Err(EdnError::structure(
        format!("expected expr for data, got leaf: {s}"),
        vec![],
        Some(&xs[0]),
      )),
      Cirru::List(_) => extract_cirru_edn(&xs[0]),
    }
  } else {
    Err(EdnError::structure(
      format!("Expected 1 expr for edn, got length {}: {:?} ", xs.len(), xs),
      vec![],
      None,
    ))
  }
}

/// Extract EDN value from a Cirru AST node.
///
/// This is useful when caller already has parsed Cirru tree and wants
/// to decode one expression without going through string parsing again.
pub fn extract_cirru_edn(node: &Cirru) -> EdnResult<Edn> {
  extract_cirru_edn_with_path(node, vec![])
}

fn extract_cirru_edn_with_path(node: &Cirru, path: Vec<usize>) -> EdnResult<Edn> {
  match node {
    Cirru::Leaf(s) => match &**s {
      "nil" => Ok(Edn::Nil),
      "true" => Ok(Edn::Bool(true)),
      "false" => Ok(Edn::Bool(false)),
      "" => Err(EdnError::value(
        "empty string is invalid for edn",
        path.clone(),
        Some(node),
      )),
      s1 => match s1.chars().next().unwrap() {
        '\'' => Ok(Edn::Symbol(s1[1..].into())),
        ':' => Ok(Edn::tag(&s1[1..])),
        '"' | '|' => Ok(Edn::Str(s1[1..].into())),
        _ => {
          if let Ok(f) = s1.trim().parse::<f64>() {
            Ok(Edn::Number(f))
          } else {
            Err(EdnError::value(
              format!("unknown token for edn value: {s1:?}"),
              path.clone(),
              Some(node),
            ))
          }
        }
      },
    },
    Cirru::List(xs) => {
      if xs.is_empty() {
        Err(EdnError::structure(
          "empty expr is invalid for edn",
          path.clone(),
          Some(node),
        ))
      } else {
        match &xs[0] {
          Cirru::Leaf(s) => match &**s {
            "quote" => {
              if xs.len() == 2 {
                Ok(Edn::Quote(xs[1].to_owned()))
              } else {
                Err(EdnError::structure("missing edn quote value", path.clone(), Some(node)))
              }
            }
            "do" => {
              let mut ret: Option<Edn> = None;

              for (i, x) in xs.iter().enumerate().skip(1) {
                if is_comment(x) {
                  continue;
                }
                if ret.is_some() {
                  return Err(EdnError::structure("multiple values in do", path.clone(), Some(node)));
                }
                let mut child_path = path.clone();
                child_path.push(i);
                ret = Some(extract_cirru_edn_with_path(x, child_path)?);
              }
              if ret.is_none() {
                return Err(EdnError::structure("missing edn do value", path.clone(), Some(node)));
              }
              ret.ok_or_else(|| EdnError::structure("missing edn do value", path.clone(), Some(node)))
            }
            "::" => {
              let mut tag: Option<Edn> = None;
              let mut extra: Vec<Edn> = vec![];
              for (i, x) in xs.iter().enumerate().skip(1) {
                if is_comment(x) {
                  continue;
                }
                let mut child_path = path.clone();
                child_path.push(i);
                if tag.is_some() {
                  extra.push(extract_cirru_edn_with_path(x, child_path)?);
                  continue;
                } else {
                  tag = Some(extract_cirru_edn_with_path(x, child_path)?);
                }
              }
              if let Some(x0) = tag {
                Ok(Edn::Tuple(EdnTupleView {
                  tag: Arc::new(x0),
                  enum_tag: None,
                  extra,
                }))
              } else {
                Err(EdnError::structure(
                  "missing edn :: fst value",
                  path.clone(),
                  Some(node),
                ))
              }
            }
            "%::" => {
              let mut enum_tag: Option<Edn> = None;
              let mut tag: Option<Edn> = None;
              let mut extra: Vec<Edn> = vec![];
              for (i, x) in xs.iter().enumerate().skip(1) {
                if is_comment(x) {
                  continue;
                }
                let mut child_path = path.clone();
                child_path.push(i);
                if enum_tag.is_none() {
                  enum_tag = Some(extract_cirru_edn_with_path(x, child_path)?);
                } else if tag.is_none() {
                  tag = Some(extract_cirru_edn_with_path(x, child_path)?);
                } else {
                  extra.push(extract_cirru_edn_with_path(x, child_path)?);
                }
              }
              if let (Some(e0), Some(x0)) = (enum_tag, tag) {
                Ok(Edn::Tuple(EdnTupleView {
                  tag: Arc::new(x0),
                  enum_tag: Some(Arc::new(e0)),
                  extra,
                }))
              } else {
                Err(EdnError::structure(
                  "missing edn %:: enum_tag or tag value",
                  path.clone(),
                  Some(node),
                ))
              }
            }
            "[]" => {
              let mut ys: Vec<Edn> = Vec::with_capacity(xs.len() - 1);
              for (i, x) in xs.iter().enumerate().skip(1) {
                if is_comment(x) {
                  continue;
                }
                let mut child_path = path.clone();
                child_path.push(i);
                let v = extract_cirru_edn_with_path(x, child_path)?;
                ys.push(v);
              }
              Ok(Edn::List(EdnListView(ys)))
            }
            "#{}" => {
              #[allow(clippy::mutable_key_type)]
              let mut ys: HashSet<Edn> = HashSet::new();
              for (i, x) in xs.iter().enumerate().skip(1) {
                if is_comment(x) {
                  continue;
                }
                let mut child_path = path.clone();
                child_path.push(i);
                let v = extract_cirru_edn_with_path(x, child_path)?;
                ys.insert(v);
              }
              Ok(Edn::Set(EdnSetView(ys)))
            }
            "{}" => {
              #[allow(clippy::mutable_key_type)]
              let mut zs: HashMap<Edn, Edn> = HashMap::new();
              for (i, x) in xs.iter().enumerate().skip(1) {
                if is_comment(x) {
                  continue;
                }
                let mut child_path = path.clone();
                child_path.push(i);
                match x {
                  Cirru::Leaf(s) => {
                    return Err(EdnError::structure(
                      format!("expected a pair, invalid map entry: {s}"),
                      child_path,
                      Some(node),
                    ));
                  }
                  Cirru::List(ys) => {
                    if ys.len() == 2 {
                      let mut k_path = child_path.clone();
                      k_path.push(0);
                      let mut v_path = child_path.clone();
                      v_path.push(1);
                      match (
                        extract_cirru_edn_with_path(&ys[0], k_path.clone()),
                        extract_cirru_edn_with_path(&ys[1], v_path.clone()),
                      ) {
                        (Ok(k), Ok(v)) => {
                          zs.insert(k, v);
                        }
                        (Err(e), _) => {
                          return Err(EdnError::structure(
                            format!("invalid map entry `{}` from `{}`", e, &ys[0]),
                            k_path,
                            Some(node),
                          ));
                        }
                        (Ok(k), Err(e)) => {
                          return Err(EdnError::structure(
                            format!("invalid map entry for `{k}`, got {e}"),
                            v_path,
                            Some(node),
                          ));
                        }
                      }
                    }
                  }
                }
              }
              Ok(Edn::Map(EdnMapView(zs)))
            }
            "%{}" => {
              if xs.len() >= 3 {
                let name = match &xs[1] {
                  Cirru::Leaf(s) => EdnTag::new(s.strip_prefix(':').unwrap_or(s)),
                  Cirru::List(e) => {
                    let mut name_path = path.clone();
                    name_path.push(1);
                    return Err(EdnError::structure(
                      format!("expected record name in string: {e:?}"),
                      name_path,
                      Some(node),
                    ));
                  }
                };
                let mut entries: Vec<(EdnTag, Edn)> = Vec::with_capacity(xs.len() - 1);

                for (i, x) in xs.iter().enumerate().skip(2) {
                  if is_comment(x) {
                    continue;
                  }
                  let mut child_path = path.clone();
                  child_path.push(i);
                  match x {
                    Cirru::Leaf(s) => {
                      return Err(EdnError::structure(
                        format!("expected record, invalid record entry: {s}"),
                        child_path,
                        Some(node),
                      ));
                    }
                    Cirru::List(ys) => {
                      if ys.len() == 2 {
                        let mut v_path = child_path.clone();
                        v_path.push(1);
                        match (&ys[0], extract_cirru_edn_with_path(&ys[1], v_path.clone())) {
                          (Cirru::Leaf(s), Ok(v)) => {
                            entries.push((EdnTag::new(s.strip_prefix(':').unwrap_or(s)), v));
                          }
                          (Cirru::Leaf(s), Err(e)) => {
                            return Err(EdnError::structure(
                              format!("invalid record value for `{s}`, got: {e}"),
                              v_path,
                              Some(node),
                            ));
                          }
                          (Cirru::List(zs), _) => {
                            let mut k_path = child_path.clone();
                            k_path.push(0);
                            return Err(EdnError::structure(
                              format!("invalid list as record key: {zs:?}"),
                              k_path,
                              Some(node),
                            ));
                          }
                        }
                      } else {
                        return Err(EdnError::structure(
                          format!("expected pair of 2: {ys:?}"),
                          child_path,
                          Some(node),
                        ));
                      }
                    }
                  }
                }
                if entries.is_empty() {
                  return Err(EdnError::structure("empty record is invalid", path.clone(), Some(node)));
                }
                Ok(Edn::Record(EdnRecordView {
                  tag: name,
                  pairs: entries,
                }))
              } else {
                Err(EdnError::structure(
                  "insufficient items for edn record",
                  path.clone(),
                  Some(node),
                ))
              }
            }
            "buf" => {
              let mut ys: Vec<u8> = Vec::with_capacity(xs.len() - 1);
              for (i, x) in xs.iter().enumerate().skip(1) {
                if is_comment(x) {
                  continue;
                }
                let mut child_path = path.clone();
                child_path.push(i);
                match x {
                  Cirru::Leaf(y) => {
                    if y.len() == 2 {
                      match hex::decode(&(**y)) {
                        Ok(b) => {
                          if b.len() == 1 {
                            ys.push(b[0])
                          } else {
                            return Err(EdnError::value(
                              format!("hex for buffer might be too large, got: {b:?}"),
                              child_path,
                              Some(node),
                            ));
                          }
                        }
                        Err(e) => {
                          return Err(EdnError::value(
                            format!("expected length 2 hex string in buffer, got: {y} {e}"),
                            child_path,
                            Some(node),
                          ));
                        }
                      }
                    } else {
                      return Err(EdnError::value(
                        format!("expected length 2 hex string in buffer, got: {y}"),
                        child_path,
                        Some(node),
                      ));
                    }
                  }
                  _ => {
                    return Err(EdnError::value(
                      format!("expected hex string in buffer, got: {x}"),
                      child_path,
                      Some(node),
                    ));
                  }
                }
              }
              Ok(Edn::Buffer(ys))
            }
            "atom" => {
              if xs.len() == 2 {
                let mut child_path = path.clone();
                child_path.push(1);
                Ok(Edn::Atom(Box::new(extract_cirru_edn_with_path(&xs[1], child_path)?)))
              } else {
                Err(EdnError::structure("missing edn atom value", path.clone(), Some(node)))
              }
            }
            a => Err(EdnError::structure(
              format!("invalid operator for edn: {a}"),
              path.clone(),
              Some(node),
            )),
          },
          Cirru::List(a) => Err(EdnError::structure(
            format!("invalid nodes for edn: {a:?}"),
            path.clone(),
            Some(node),
          )),
        }
      }
    }
  }
}

fn is_comment(node: &Cirru) -> bool {
  match node {
    Cirru::Leaf(_) => false,
    Cirru::List(xs) => xs.first() == Some(&Cirru::Leaf(";".into())),
  }
}

fn assemble_cirru_node(data: &Edn) -> Cirru {
  match data {
    Edn::Nil => "nil".into(),
    Edn::Bool(v) => v.to_string().as_str().into(),
    Edn::Number(n) => n.to_string().as_str().into(),
    Edn::Symbol(s) => format!("'{s}").as_str().into(),
    Edn::Tag(s) => format!(":{s}").as_str().into(),
    Edn::Str(s) => format!("|{s}").as_str().into(),
    Edn::Quote(v) => Cirru::List(vec!["quote".into(), (*v).to_owned()]),
    Edn::List(xs) => {
      let mut ys: Vec<Cirru> = Vec::with_capacity(xs.len() + 1);
      ys.push("[]".into());
      for x in xs {
        ys.push(assemble_cirru_node(x));
      }
      Cirru::List(ys)
    }
    Edn::Set(xs) => {
      let mut ys: Vec<Cirru> = Vec::with_capacity(xs.len() + 1);
      ys.push("#{}".into());
      let mut items = xs.0.iter().collect::<Vec<_>>();
      items.sort();
      for x in items {
        ys.push(assemble_cirru_node(x));
      }
      Cirru::List(ys)
    }
    Edn::Map(xs) => {
      let mut ys: Vec<Cirru> = Vec::with_capacity(xs.len() + 1);
      ys.push("{}".into());
      let mut items = Vec::from_iter(xs.0.iter());
      items.sort_by(|(a1, a2): &(&Edn, &Edn), (b1, b2): &(&Edn, &Edn)| {
        match (a1.is_literal(), b1.is_literal(), a2.is_literal(), b2.is_literal()) {
          (true, true, true, false) => Less,
          (true, true, false, true) => Greater,
          (true, false, ..) => Less,
          (false, true, ..) => Greater,
          _ => a1.cmp(b1),
        }
      });
      for (k, v) in items {
        ys.push(Cirru::List(vec![assemble_cirru_node(k), assemble_cirru_node(v)]))
      }
      Cirru::List(ys)
    }
    Edn::Record(EdnRecordView {
      tag: name,
      pairs: entries,
    }) => {
      let mut ys: Vec<Cirru> = Vec::with_capacity(entries.len() + 2);
      ys.push("%{}".into());
      ys.push(format!(":{name}").as_str().into());
      let mut ordered_entries = entries.to_owned();
      ordered_entries.sort_by(|(a1, a2), (b1, b2)| match (a2.is_literal(), b2.is_literal()) {
        (true, false) => Less,
        (false, true) => Greater,
        _ => a1.cmp(b1),
      });
      for entry in ordered_entries {
        let v = &entry.1;
        ys.push(Cirru::List(vec![
          format!(":{}", entry.0).as_str().into(),
          assemble_cirru_node(v),
        ]));
      }

      Cirru::List(ys)
    }
    Edn::Tuple(EdnTupleView { tag, enum_tag, extra }) => {
      let mut ys: Vec<Cirru> = if let Some(et) = enum_tag {
        vec!["%::".into(), assemble_cirru_node(et), assemble_cirru_node(tag)]
      } else {
        vec!["::".into(), assemble_cirru_node(tag)]
      };
      for item in extra {
        ys.push(assemble_cirru_node(item))
      }
      Cirru::List(ys)
    }
    Edn::Buffer(buf) => {
      let mut ys: Vec<Cirru> = Vec::with_capacity(buf.len() + 1);
      ys.push("buf".into());
      for b in buf {
        ys.push(hex::encode(vec![b.to_owned()]).as_str().into());
      }
      Cirru::List(ys)
    }
    Edn::AnyRef(..) => unreachable!("AnyRef is not serializable"),
    Edn::Atom(v) => {
      let ys = vec!["atom".into(), assemble_cirru_node(v)];
      Cirru::List(ys)
    }
  }
}

/// Generate formatted string from Edn data.
///
/// This function converts an Edn value into its Cirru syntax representation.
///
/// # Arguments
///
/// * `data` - The Edn value to format
/// * `use_inline` - Whether to use inline formatting (more compact) or multiline formatting
///
/// # Returns
///
/// * `Result<String, String>` - Returns the formatted string on success, or an error message on failure
///
/// # Examples
///
/// ```
/// use cirru_edn::{Edn, format};
///
/// let data = Edn::Number(42.0);
/// let result = format(&data, true).unwrap();
/// assert_eq!(result.trim(), "do 42");
///
/// // Format a list with inline style
/// let data = Edn::List(vec![
///     Edn::Number(1.0),
///     Edn::Number(2.0),
///     Edn::Number(3.0),
/// ].into());
/// let result = format(&data, true).unwrap();
/// // Output: ([] 1 2 3)
///
/// // Format a map with multiline style
/// let data = Edn::map_from_iter([
///     (Edn::tag("name"), Edn::str("Alice")),
///     (Edn::tag("age"), Edn::Number(30.0)),
/// ]);
/// let result = format(&data, false).unwrap();
/// ```
///
/// # Notes
///
/// - AnyRef values cannot be formatted and will cause an error
/// - The function automatically wraps single literals in `do` expressions
/// - Inline formatting produces more compact output, while multiline formatting is more readable
pub fn format(data: &Edn, use_inline: bool) -> Result<String, String> {
  match data.cirru() {
    Cirru::Leaf(s) => cirru_parser::format(&[vec!["do", &*s].into()], use_inline.into()),
    Cirru::List(xs) => cirru_parser::format(&[(Cirru::List(xs))], use_inline.into()),
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn exposes_extract_api_for_cirru_ast() {
    let node = Cirru::List(vec![Cirru::leaf("[]"), Cirru::leaf("1"), Cirru::leaf("2")]);
    let value = extract_cirru_edn(&node).expect("should decode list from AST");
    assert!(matches!(value, Edn::List(_)));
  }

  #[test]
  fn exposes_short_cirru_method_on_edn() {
    let value = Edn::map_from_iter([(Edn::tag("a"), Edn::Number(1.0))]);
    let node = value.cirru();
    let Cirru::List(items) = node else {
      panic!("map should assemble into list node");
    };
    assert_eq!(items.first(), Some(&Cirru::leaf("{}")));
  }
}