crypt-configs 0.2.0

A modern config file format
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
//! Crypt Configuration
//!
//! Created 7/25/2026 - Nyx
//!
//! A modern readable file format.
//!
//! Crypt files are similar to json with additional support for enums
//! special tags, identifiers, and includes. Crypt is essentially a superset of json
//! meaning any json file can parsed as if it was a crypt file.
//!
//! Using the beauty of Rust crypt files can be parsed directly into rust
//! native structs and enums using the [Cryptic] derivation. To parse a crypt
//! file a [CryptParserServer] is used which automatically caches opened files and
//! reuses them when requested.

pub use crypt_macro::Cryptic;

use std::{
    cell::LazyCell,
    collections::HashMap,
    ffi::OsString,
    iter::Peekable,
    path::{Path, PathBuf},
    vec::IntoIter
};

use indexmap::IndexMap;
use oaken::{
    Lexer, Registry,
    TokenPosition, TracedToken,
    TracedTokenStream,
    util::{
        numeric_state::{DecimalState, numeric_entry_rule},
        string_state::StringState
    }
};

////////////
// TOKENS //
////////////

#[derive(Debug, Clone)]
/// Tokens collected by the crypt parser.
enum Token {
    Identifier(String),
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool), // true | false
    Null, // null

    Import, // !import

    Assign, // = or :
    SingleTag, // #
    TagOpen, // (
    TagClose, // )
    BodyOpen, // {
    BodyClose, // }
    ListOpen, // [
    ListClose, // ]
    Break, // ,
}

impl std::fmt::Display for Token {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Identifier(ident) => write!(f, "'{}'", ident),
            Self::String(str) => write!(f, "\"{}\"", str),
            Self::Integer(int) => write!(f, "{}", int),
            Self::Float(fl) => write!(f, "{}", fl),
            Self::Boolean(bool) => write!(f, "{}", bool),
            Self::Null => write!(f, "null"),
            Self::Import => write!(f, "!import"),
            Self::Assign => write!(f, ": | ="),
            Self::SingleTag => write!(f, "#"),
            Self::TagOpen => write!(f, "("),
            Self::TagClose => write!(f, ")"),
            Self::ListOpen => write!(f, "["),
            Self::ListClose => write!(f, "]"),
            Self::BodyOpen => write!(f, "{{"),
            Self::BodyClose => write!(f, "}}"),
            Self::Break => write!(f, ","),
        }
    }
}

impl Token {
    fn get_binding_power(&self) -> isize {
        match self {
            Self::Break => 1,
            Self::Assign => 2,

            _ => 0,
        }
    }
}

impl From<String> for Token {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

macro_rules! from_int {
    ($($ty:ty)+) => {
        $(
            impl From<$ty> for Token {
                fn from(value: $ty) -> Self {
                    Self::Integer(value as _)
                }
            }
        )+
    };
}
from_int!(i8 u8 i16 u16 i32 u32 i64 u64);

impl From<f32> for Token {
    fn from(value: f32) -> Self {
        Self::Float(value as _)
    }
}
impl From<f64> for Token {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

const TOKENS: LazyCell<Vec<(&'static str, Token, bool)>> =
LazyCell::new(||vec![
    ("true", Token::Boolean(true), false),
    ("false", Token::Boolean(false), false),
    ("null", Token::Null, false),
    ("!import", Token::Import, false),
    ("#", Token::SingleTag, true),
    ("(", Token::TagOpen, true),
    (")", Token::TagClose, true),
    ("{", Token::BodyOpen, true),
    ("}", Token::BodyClose, true),
    ("[", Token::ListOpen, true),
    ("]", Token::ListClose, true),
    (",", Token::Break, true),
    ("=", Token::Assign, true),
    (":", Token::Assign, true),
]);

fn identifier_fallback(str: &String) -> Token {
    Token::Identifier(str.clone())
}


///////////////////
// PARSER SERVER //
///////////////////


/// Sets up a parsing server for parsing crypt files.
///
/// # Example
///
/// ```no_run
/// use crypt_config::{CryptParserServer, Cryptic};
///
/// #[derive(Cryptic)]
/// struct MyStruct {
///     str: String
/// }
///
/// let mut server = CryptParserServer::new();
/// let my_struct: MyStruct = server.open("path/to/my/file.crypt").expect("Failed to parse file");
/// ```
///
/// The parser will automatically convert the resulting crypt file into the
/// desired [Cryptic] type.
pub struct CryptParserServer {
    /// The [oaken] registry used to parse files
    register: Registry<Token>,
    /// Already opened files are cached and reused if requested.
    opened_files: HashMap<OsString, TracedObject>,
}

impl CryptParserServer {
    /// Creates a new parser server that can be reused while opening crypt files.
    pub fn new() -> Self {
        let mut reg= Registry::new(identifier_fallback);

        for (kw, tk, br) in &*TOKENS {
            reg = reg.new_keyword(kw, tk.clone(), *br).unwrap();
        }

        Self {
            register: reg
                .new_special_state('"', StringState::new('"'))
                .add_new_entry_rule(numeric_entry_rule, DecimalState::default()),
            opened_files: HashMap::new(),
        }
    }

    /// Opens a crypt file from a path and automatically converts it to
    /// the desired [Cryptic] type.
    pub fn open<P, T>(&mut self, path: P) -> Result<T, CryptError>
    where
        P: AsRef<Path>,
        T: Cryptic,
    {
        let path_str = path.as_ref().canonicalize()?.as_os_str().to_os_string();

        if let Some(built) = self.opened_files.get(&path_str) {
            return T::cryptic(built.clone())
        }

        let tokens = self.tokenize(path)?;
        let mut iter = tokens.into_iter().peekable();
        let ast = parse_body(&mut iter)?;
        let object = resolve(ast, self)?;

        self.opened_files.insert(path_str, object.clone());

        // Nuance for parsing json files that have the main body
        if let CryptObject::ObjectList(body) = &object.object
            && body.len() == 1 && matches!(&body.iter().next().unwrap().object, &CryptObject::ObjectBody(_))
        {
            let CryptObject::ObjectList(body) = object.object else { unreachable!() };
            let object = body.into_iter().next().unwrap();
            T::cryptic(object)
        } else {
            T::cryptic(object)
        }
    }

    /// Opens a tokenizes a crypt file.
    fn tokenize<P>(&self, path: P) -> std::io::Result<TracedTokenStream<Token>>
    where
        P: AsRef<Path>,
    {
        let mut lexer = Lexer::from(&self.register);
        lexer.traced();
        lexer.lex_file(path, None)?;
        Ok(lexer.finish_as_trace())
    }
}


/////////////
// PARSING //
/////////////

#[derive(Debug)]
/// A parsed node containing information regarding the source of the node.
/// This information is used in the case of an error.
struct TracedNode {
    position: TokenPosition,
    node: Node,
}

#[derive(Debug)]
/// A node parsed from a crypt file.
enum Node {
    Identifier(String),
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Null,

    Import(String),
    Assignment(String, Box<TracedNode>),
    Tag(Vec<TracedNode>, Box<TracedNode>),
    Body(Vec<TracedNode>),
    List(Vec<TracedNode>),
}

type TokenIterator = Peekable<IntoIter<TracedToken<Token>>>;

/// Parses a stream of tokens into a tree of nodes representing the crypt file.
fn parse_body(iter: &mut TokenIterator) -> Result<TracedNode, CryptError> {
    let mut items = Vec::new();
    while let Some(_) = iter.peek() {
        let item = parse(iter, 1)?;
        items.push(item);

        if let Some(t) = iter.peek() && matches!(t.get_type(), Token::Break) {
            iter.next();
        } else {
            break;
        }
    }
    if let Some(t) = iter.next() {
        return Err(CryptError(Some(t.get_position().clone()), CryptErrorType::UnexpectedToken(t.into_type())))
    }

    Ok(TracedNode { position: TokenPosition { line: 0, column_start: 0, column_end: 0, path: None }, node: Node::List(items) })
}

fn parse(iter: &mut TokenIterator, current_binding_power: isize, ) -> Result<TracedNode, CryptError> {
    let Some(current) = iter.next() else {
        return Err(CryptError(None, CryptErrorType::UnexpectedEOF))
    };

    let mut left = parse_nud(iter, current)?;

    while let Some(t) = iter.peek() && t.get_type().get_binding_power() > current_binding_power {
        let current = iter.next().unwrap();
        left = parse_led(iter, left, current)?;
    }

    Ok(left)
}

fn parse_nud(iter: &mut TokenIterator, current: TracedToken<Token>) -> Result<TracedNode, CryptError> {
    let pos = current.get_position().clone();
    let token = current.into_type();
    let node = match token.clone() {
        Token::Identifier(ident) => Node::Identifier(ident),
        Token::String(str) => Node::String(str),
        Token::Integer(int) => Node::Integer(int),
        Token::Float(fl) => Node::Float(fl),
        Token::Boolean(bool) => Node::Boolean(bool),
        Token::Null => Node::Null,

        Token::Import => {
            let Some(t) = iter.next() else {
                return Err(CryptError(None, CryptErrorType::UnexpectedEOF))
            };

            let path_token_pos = t.get_position().clone();
            let t = t.into_type();
            let Token::String(str) = t.clone() else {
                return Err(CryptError(Some(path_token_pos), CryptErrorType::ExpectedOther("path string", t)))
            };

            Node::Import(str)
        },

        Token::SingleTag => {
            if let Some(t) = iter.peek() && matches!(t.get_type(), Token::TagOpen) {
                iter.next();
                let mut tags = Vec::new();
                while let Some(t) = iter.peek() && !matches!(t.get_type(), Token::TagClose) {
                    let tag = parse(iter, 1)?;
                    tags.push(tag);

                    if let Some(t) = iter.peek() && matches!(t.get_type(), Token::Break) {
                        iter.next();
                    } else {
                        break;
                    }
                }
                if let Some(t) = iter.next() && !matches!(t.get_type(), Token::TagClose) {
                    return Err(CryptError(Some(t.get_position().clone()), CryptErrorType::ExpectedOther("closing ')'", t.into_type())))
                }
                Node::Tag(tags, Box::new(parse(iter, 1)?))
            } else {
                let tag = parse(iter, 1)?;
                Node::Tag(vec![tag], Box::new(parse(iter, 1)?))
            }
        }

        Token::BodyOpen => {
            let mut items = Vec::new();
            while let Some(t) = iter.peek() && !matches!(t.get_type(), Token::BodyClose) {
                let item = parse(iter, 1)?;
                items.push(item);

                if let Some(t) = iter.peek() && matches!(t.get_type(), Token::Break) {
                    iter.next();
                } else {
                    break;
                }
            }
            if let Some(t) = iter.next() && !matches!(t.get_type(), Token::BodyClose) {
                return Err(CryptError(Some(t.get_position().clone()), CryptErrorType::ExpectedOther("closing '}'", t.into_type())))
            }
            Node::Body(items)
        }

        Token::ListOpen => {
            let mut items = Vec::new();
            while let Some(t) = iter.peek() && !matches!(t.get_type(), Token::ListClose) {
                let item = parse(iter, 1)?;
                items.push(item);

                if let Some(t) = iter.peek() && matches!(t.get_type(), Token::Break) {
                    iter.next();
                } else {
                    break;
                }
            }
            if let Some(t) = iter.next() && !matches!(t.get_type(), Token::ListClose) {
                return Err(CryptError(Some(t.get_position().clone()), CryptErrorType::ExpectedOther("closing ']'", t.into_type())))
            }
            Node::List(items)
        }

        _ => return Err(CryptError(Some(pos), CryptErrorType::UnexpectedToken(token)))
    };

    Ok(TracedNode { position: pos, node, })
}

fn parse_led(iter: &mut TokenIterator, left: TracedNode, current: TracedToken<Token>) -> Result<TracedNode, CryptError> {
    let pos = current.get_position().clone();
    let token = current.into_type();
    let node = match token.clone() {
        Token::Assign => {
            let ident = match left.node {
                Node::Identifier(ident) => ident,
                Node::String(str) => str,
                _ => return Err(CryptError(Some(left.position), CryptErrorType::ExpectedIdentifier))
            };

            let object = parse(iter, 1)?;
            Node::Assignment(ident, Box::new(object))
        }

        _ => return Err(CryptError(Some(pos), CryptErrorType::UnexpectedToken(token)))
    };

    Ok(TracedNode { position: pos, node, })
}




fn resolve(node: TracedNode, server: &mut CryptParserServer) -> Result<TracedObject, CryptError> {
    let pos = node.position;

    let obj = match node.node {
        Node::Identifier(ident) => CryptObject::FloatingIdentifier(ident),
        Node::String(str) => CryptObject::ConstantString(str),
        Node::Integer(int) => CryptObject::ConstantInteger(int),
        Node::Float(fl) => CryptObject::ConstantFloat(fl),
        Node::Boolean(bool) => CryptObject::ConstantBoolean(bool),
        Node::Null => CryptObject::Null,
        Node::Assignment(ident, item) => CryptObject::IdentifiedObject(ident, Box::new(resolve(*item, server)?)),
        Node::Body(items) => {
            let mut body = IndexMap::new();
            for item in items {
                let item = resolve(item, server)?;
                match item.object {
                    CryptObject::IdentifiedObject(ident, item) => {
                        body.insert(ident, *item);
                    }
                    CryptObject::TaggedObject(tags, tagged_item) =>
                        if let CryptObject::IdentifiedObject(ident, tagged_item) = tagged_item.object {
                            body.insert(ident, TracedObject { position: item.position, object: CryptObject::TaggedObject(tags, tagged_item) });
                        } else {
                            return Err(CryptError(Some(item.position), CryptErrorType::ExpectedIdentifier))
                        },
                    _ => return Err(CryptError(Some(item.position), CryptErrorType::ExpectedIdentifier))
                }
            }
            CryptObject::ObjectBody(body)
        }
        Node::List(items) => {
            let mut resolved_items = Vec::new();
            for item in items {
                let item = resolve(item, server)?;
                resolved_items.push(item);
            }
            CryptObject::ObjectList(resolved_items)
        }
        Node::Tag(tags, object) => {
            let mut resolved_tags = Vec::new();
            for tag in tags {
                let tag = resolve(tag, server)?;
                resolved_tags.push(tag);
            }
            CryptObject::TaggedObject(resolved_tags, Box::new(resolve(*object, server)?))
        }
        Node::Import(path) => {
            let Some(current_path) = pos.path else {
                return Err(CryptError(Some(pos), CryptErrorType::CannotImport))
            };

            let path_buf =
                PathBuf::from(current_path.as_ref())
                .canonicalize().unwrap(); // TODO propagate
            let final_path = path_buf.parent().unwrap().join(path);

            return server.open(final_path)
        }
    };

    Ok(TracedObject { position: pos, object: obj })
}




/////////////
// OBJECTS //
/////////////

#[derive(Debug, Clone)]
/// An object parsed from a crypt file that also contains
/// debug information in the case of an error.
///
/// This is the main interface type for building [Cryptic] objects.
/// Traced objects can be easily cast to other types while also providing
/// debug information. If you need to handle ambiguous types use [CrypticObject]
/// which strips away the added debug information.
pub struct TracedObject {
    position: TokenPosition,
    object: CryptObject,
}

#[derive(Debug, Clone)]
/// An object taken from a crypt file.
enum CryptObject {
    ConstantString(String),
    ConstantInteger(i64),
    ConstantFloat(f64),
    ConstantBoolean(bool),
    Null,
    FloatingIdentifier(String),
    IdentifiedObject(String, Box<TracedObject>),

    TaggedObject (Vec<TracedObject>, Box<TracedObject>),

    ObjectBody(IndexMap<String, TracedObject>),
    ObjectList(Vec<TracedObject>),
}

#[derive(Debug, Clone)]
/// An ambiguous object parsed from a crypt file.
///
/// This should only be used if the object you want parsed is expected
/// to be multiple different types and should be handled manually. In any other
/// case simply using that type is preferred.
pub enum CrypticObject {
    ConstantString(String),
    ConstantInteger(i64),
    ConstantFloat(f64),
    ConstantBoolean(bool),
    Null,
    FloatingIdentifier(String),
    IdentifiedObject(String, Box<CrypticObject>),

    TaggedObject (Vec<CrypticObject>, Box<CrypticObject>),

    ObjectBody(HashMap<String, CrypticObject>),
    ObjectList(Vec<CrypticObject>),
}

#[derive(Debug, Clone)]
/// A custom tagged object parsed from a crypt file.
pub struct Tagged<T, O> {
    pub tag: T,
    pub object: O
}

#[derive(Debug, Clone)]
/// A custom tagged object parsed from a crypt file.
pub struct HashTagged<T, O> {
    pub tags: HashMap<String, T>,
    pub object: O
}

#[derive(Debug, Clone)]
/// A custom tagged object parsed from a crypt file.
pub struct ListTagged<T, O> {
    pub tags: Vec<T>,
    pub object: O
}



//////////////////
// CONSTRUCTING //
//////////////////

/// An object that can be parsed from a crypt file.
///
/// A derive macro exists for this type and is expected to be used over manually
/// implementing it.
pub trait Cryptic: Sized {
    /// Attempts to convert an AST from a crypt file into a desired type.
    ///
    /// In most cases it is recommended to use [CryptParserServer] which will
    /// automatically call this method an opened file.
    fn cryptic(object: TracedObject) -> Result<Self, CryptError>;
}

impl TryInto<String> for TracedObject {
    type Error = CryptError;

    fn try_into(self) -> Result<String, Self::Error> {
        match self.object {
            CryptObject::ConstantString(str) => Ok(str),
            CryptObject::FloatingIdentifier(ident) => Ok(ident),
            CryptObject::ConstantInteger(int) => Ok(int.to_string()),
            CryptObject::ConstantFloat(fl) => Ok(fl.to_string()),
            CryptObject::ConstantBoolean(b) => Ok(b.to_string()),
            CryptObject::Null => Ok(String::new()),
            CryptObject::IdentifiedObject(_, obj) => (*obj).try_into(),
            CryptObject::TaggedObject(_, obj) => (*obj).try_into(),
            _ => Err(CryptError(Some(self.position), CryptErrorType::UnexpectedType))
        }
    }
}

impl TryInto<bool> for TracedObject {
    type Error = CryptError;

    fn try_into(self) -> Result<bool, Self::Error> {
        match self.object {
            CryptObject::ConstantString(str) => Ok(str != ""),
            CryptObject::FloatingIdentifier(_) => Ok(true),
            CryptObject::ConstantInteger(int) => Ok(int != 0),
            CryptObject::ConstantFloat(fl) => Ok(fl != 0.0),
            CryptObject::ConstantBoolean(b) => Ok(b),
            CryptObject::Null => Ok(false),
            CryptObject::IdentifiedObject(_, obj) => (*obj).try_into(),
            CryptObject::TaggedObject(_, obj) => (*obj).try_into(),
            _ => Err(CryptError(Some(self.position), CryptErrorType::UnexpectedType))
        }
    }
}

macro_rules! try_into_int {
    ($($ty:ty)+) => {
        $(
            impl TryInto<$ty> for TracedObject {
                type Error = CryptError;

                fn try_into(self) -> Result<$ty, Self::Error> {
                    match self.object {
                        CryptObject::ConstantInteger(int) => Ok(int as _),
                        CryptObject::ConstantFloat(fl) => Ok(fl as _),
                        CryptObject::ConstantBoolean(b) => Ok(if b {1 as _} else {0 as _}),
                        CryptObject::ConstantString(str) => match str.parse() {
                            Ok(i) => Ok(i),
                            Err(_) => Err(CryptError(Some(self.position), CryptErrorType::ParseError))
                        },
                        CryptObject::IdentifiedObject(_, item) => (*item).try_into(),
                        CryptObject::TaggedObject(_, obj) => (*obj).try_into(),
                        _ => Err(CryptError(Some(self.position), CryptErrorType::UnexpectedType))
                    }
                }
            }
        )+
    };
}
try_into_int!(i8 u8 i16 u16 i32 u32 i64 u64 isize usize f32 f64);

impl<T> TryInto<Vec<T>> for TracedObject
where
    T: Cryptic
{
    type Error = CryptError;

    fn try_into(self) -> Result<Vec<T>, Self::Error> {
        match self.object {
            CryptObject::ObjectList(list) =>
                list
                    .into_iter()
                    .map(|i| T::cryptic(i))
                    .collect(),
            CryptObject::ObjectBody(body) =>
                body
                    .into_values()
                    .into_iter()
                    .map(|i| T::cryptic(i))
                    .collect(),

            CryptObject::IdentifiedObject(_, obj) => (*obj).try_into(),
            CryptObject::TaggedObject(_, obj) => (*obj).try_into(),

            _ => Ok(vec![T::cryptic(self)?])
        }
    }
}

impl<T> TryInto<HashMap<String, T>> for TracedObject
where
    T: Cryptic
{
    type Error = CryptError;

    fn try_into(self) -> Result<HashMap<String, T>, Self::Error> {
        match self.object {
            CryptObject::ObjectBody(body) =>
                body
                    .into_iter()
                    .map(|(k, i)| T::cryptic(i).map(|i| (k, i)))
                    .collect(),
            CryptObject::ObjectList(list) => {
                let mut body = HashMap::new();
                let mut idx: usize = 0;
                for item in list {
                    if let CryptObject::IdentifiedObject(ident, item) = item.object {
                        body.insert(ident, T::cryptic(*item)?);
                    } else {
                        body.insert(idx.to_string(), T::cryptic(item)?);
                        idx += 1;
                    }
                }
                Ok(body)
            },

            CryptObject::IdentifiedObject(ident, item) => Ok(vec![(ident, T::cryptic(*item)?)].into_iter().collect()),
            CryptObject::TaggedObject(_, item) => (*item).try_into(),

            _ => Err(CryptError(Some(self.position), CryptErrorType::UnexpectedType))
        }
    }
}


impl<T, O> TryInto<Tagged<T, O>> for TracedObject
where
    T: Cryptic,
    O: Cryptic
{
    type Error = CryptError;

    fn try_into(self) -> Result<Tagged<T, O>, Self::Error> {
        match self.object {
            CryptObject::TaggedObject(tags, obj) => {
                let Some(tag) = tags.into_iter().next() else {
                    return Err(CryptError(Some(self.position), CryptErrorType::ExpectedTag))
                };
                let tag = T::cryptic(tag)?;

                Ok(Tagged { tag: tag, object: O::cryptic(*obj)? })
            }

            _ => Err(CryptError(Some(self.position), CryptErrorType::UnexpectedType))

        }
    }
}

impl<T, O> TryInto<ListTagged<T, O>> for TracedObject
where
    T: Cryptic,
    O: Cryptic
{
    type Error = CryptError;

    fn try_into(self) -> Result<ListTagged<T, O>, Self::Error> {
        match self.object {
            CryptObject::TaggedObject(tags, obj) => {
                let tags = tags.into_iter().map(|i| T::cryptic(i)).collect::<Result<Vec<T>, CryptError>>()?;
                Ok(ListTagged { tags, object: O::cryptic(*obj)? })
            }

            _ => Ok(ListTagged { tags: Vec::new(), object: O::cryptic(self)? })
        }
    }
}

impl<T, O> TryInto<HashTagged<T, O>> for TracedObject
where
    T: Cryptic,
    O: Cryptic
{
    type Error = CryptError;

    fn try_into(self) -> Result<HashTagged<T, O>, Self::Error> {
        match self.object {
            CryptObject::TaggedObject(tags, item) => {
                let mut built_tags = HashMap::new();
                let mut idx: usize = 0;
                for tag in tags {
                    if let CryptObject::IdentifiedObject(ident, item) = tag.object {
                        built_tags.insert(ident, T::cryptic(*item)?);
                    } else {
                        built_tags.insert(idx.to_string(), T::cryptic(tag)?);
                        idx += 1;
                    }
                }
                Ok(HashTagged { tags: built_tags, object: O::cryptic(*item)? })
            }

            _ => Ok(HashTagged { tags: HashMap::new(), object: O::cryptic(self)? })
        }
    }
}

impl<T> Cryptic for T
where
    TracedObject: TryInto<T, Error = CryptError>,
{
    fn cryptic(object: TracedObject) -> Result<Self, CryptError> {
        object.try_into()
    }
}

impl Cryptic for CryptObject {
    fn cryptic(object: TracedObject) -> Result<Self, CryptError> {
        Ok(object.object)
    }
}

impl Cryptic for CrypticObject {
    fn cryptic(object: TracedObject) -> Result<Self, CryptError> {
        Ok(match object.object {
            CryptObject::ConstantString(str) => CrypticObject::ConstantString(str),
            CryptObject::ConstantInteger(int) => CrypticObject::ConstantInteger(int),
            CryptObject::ConstantFloat(fl) => CrypticObject::ConstantFloat(fl),
            CryptObject::ConstantBoolean(b) => CrypticObject::ConstantBoolean(b),
            CryptObject::Null => CrypticObject::Null,
            CryptObject::FloatingIdentifier(ident) => CrypticObject::FloatingIdentifier(ident),
            CryptObject::IdentifiedObject(ident, item) => CrypticObject::IdentifiedObject(ident, Box::new(CrypticObject::cryptic(*item).unwrap())),
            CryptObject::TaggedObject (tags, item) => CrypticObject::TaggedObject(tags.into_iter().map(|i| CrypticObject::cryptic(i).unwrap()).collect(), Box::new(CrypticObject::cryptic(*item).unwrap())),
            CryptObject::ObjectBody(body) => CrypticObject::ObjectBody(body.into_iter().map(|(ident, item)| (ident, CrypticObject::cryptic(item).unwrap())).collect()),
            CryptObject::ObjectList(list) => CrypticObject::ObjectList(list.into_iter().map(|i| CrypticObject::cryptic(i).unwrap()).collect()),
        })
    }
}

impl<T> Cryptic for Option<T>
where
    T: Cryptic
{
    fn cryptic(object: TracedObject) -> Result<Self, CryptError> {
        match object.object {
            CryptObject::Null => Ok(None),
            _ => Ok(Some(Cryptic::cryptic(object)?))
        }
    }
}

impl Cryptic for TracedObject {
    fn cryptic(object: TracedObject) -> Result<Self, CryptError> {
        Ok(object)
    }
}

#[derive(Debug)]
/// An error that can happen during the parsing and building of crypt files.
pub struct CryptError(Option<TokenPosition>, CryptErrorType);

impl CryptError {
    pub const fn cannot_find_ident(name: &'static str) -> Self {
        Self(None, CryptErrorType::NoItemOfIdentifier(name))
    }
    pub const fn not_enough_items() -> Self {
        Self(None, CryptErrorType::NotEnoughItems)
    }
    pub fn invalid_enum_variant(variant: String) -> Self {
        Self(None, CryptErrorType::InvalidEnumVariant(variant))
    }
}

#[derive(Debug)]
enum CryptErrorType {
    UnexpectedToken(Token),
    ExpectedOther(&'static str, Token),
    UnexpectedEOF,
    ExpectedIdentifier,
    CannotImport,
    UnexpectedType,
    ParseError,
    ExpectedTag,

    NoItemOfIdentifier(&'static str),
    NotEnoughItems,
    InvalidEnumVariant(String),

    OsError(std::io::Error),
}

impl std::fmt::Display for CryptError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.1 {
            CryptErrorType::UnexpectedToken(t) => writeln!(f, "Unexpected token: {}", t),
            CryptErrorType::ExpectedOther(desc, t) => writeln!(f, "Unexpected token: {}, expected {}", t, desc),
            CryptErrorType::UnexpectedEOF => writeln!(f, "Unexpected end of file"),
            CryptErrorType::ExpectedIdentifier => writeln!(f, "Expected an identifier"),
            CryptErrorType::CannotImport => writeln!(f, "Cannot import here"),
            CryptErrorType::UnexpectedType => writeln!(f, "Unexpected type"),
            CryptErrorType::ParseError => writeln!(f, "Failed to parse"),
            CryptErrorType::ExpectedTag => writeln!(f, "Expected a tag"),
            CryptErrorType::OsError(e) => writeln!(f, "{}", e),
            CryptErrorType::NoItemOfIdentifier(ident) => write!(f, "Couldn't find item: {}", ident),
            CryptErrorType::NotEnoughItems => write!(f, "Not enough items found"),
            CryptErrorType::InvalidEnumVariant(v) => write!(f, "Invalid enum variant: {}", v),
        }?;

        if let Some(pos) = &self.0 {
            writeln!(f, "at: {:?}", pos)?;
        }

        Ok(())
    }
}

impl std::error::Error for CryptError {}

impl From<std::io::Error> for CryptError {
    fn from(value: std::io::Error) -> Self {
        CryptError(None, CryptErrorType::OsError(value))
    }
}