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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! # SML
//!
//! `SML` is a simple markup language. It is designed to convert human readable information into
//! Rust data-structures.
//!
//! # Data Format
//!
//! 1. Indentation has meaning and is 4 spaces. The first key determines the alignment of
//!    indentation.
//! 2. All values must be double quoted.
//! 3. Every key/value combination must be nested in a key. For example
//! ```
//!     hobbit: "Frodo"
//! ```
//! by itself is invalid. It can be written:
//! ```
//!     hobbit:
//!         name: "Frodo"
//! ```
//! 4. Separation of lines has meaning.
//! 5. Keys may not include `:`.
//! 6. Double quotes in values must be escaped using `\"`.
//! 7. There can be an arbitary amount of whitespace and returns before the first key and after the
//!    last key.
//! 8. Characters after the second double-quote in the value are ignored.
//!
//! # Example
//!
//! ```
//! use small::{Data, Small, SmallError};
//! 
//! #[derive(Debug)]
//! struct Hobbit {
//!     name:    String,
//!     age:     u32,
//!     friends: Vec<Hobbit>,
//!     bicycle: Option<String>,
//! }
//! 
//! impl Small for Hobbit {
//!     fn from_data(data: Data) -> Result<Self, SmallError> {
//!         Ok(Self {
//!             name:    String::sml(&data, "hobbit::name")?,
//!             age:     u32::sml(&data, "hobbit::age")?,
//!             friends: Vec::<Hobbit>::sml(&data, "hobbit::friends::hobbit")?,
//!             bicycle: Option::<String>::sml(&data, "hobbit::bicycle")?,
//!         })
//!     }
//! }
//! 
//! fn main() {
//!     let s = r#"
//!         hobbit:
//!             name:         "Frodo Baggins"
//!             age:          "98"
//!             friends:
//!                 hobbit:
//!                     name: "Bilbo Baggins"
//!                     age:  "176"
//!                 hobbit:
//!                     name: "Samwise Gamgee"
//!                     age:  "66""#;
//!     
//!     let frodo = Hobbit::from_str_debug(s);
//! }
//! ```

#![feature(try_trait)]

use colored::Colorize;
use std::error::Error;
use std::fmt::Display;
use std::ops::Index;
use core::slice::Iter;
use std::fmt;
use std::process::exit;

const INDENTSTEP: usize = 4;

fn spaces(i: usize) -> String {
    let mut s = String::new();
    for _n in 0..i { s.push_str(" ") };
    s
}

#[derive(Debug)]
pub enum SmallError {
    BoolParse(Token),
    EmptyKey(Token, usize), 
    Indent(Token, usize),          // usize refers to root_indent.
    Empty,
    FloatParse(Token),
    PathIsEmpty,
    IsKey(Token),
    IsValue(String),
    KeyParse(String),
    IntegerParse(Token),
    NoColon(Token, usize),         // usize refers to position of colon.
    NoQuoteAfterKey(Token, usize),
    NoSecondQuote(Token, usize),
    NoSpaceAfterKey(Token),
    NotUnique(usize),
    QuotemarkInKey(Token, usize),  // usize refers to position of quote.
    Quotes(usize, String),

    Reduction,
    TopValueMismatch,
    User(String),
}

impl Error for SmallError {
}

impl fmt::Display for SmallError {

    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {

            SmallError::BoolParse(token) => {
                write!(f, "Line {}:{} [{}] The number could not be parsed as a boolean.",
                       token.line,
                       token.start_val.unwrap(),
                       token.text.trim().cyan().bold(),
                )
            },

            SmallError::EmptyKey(token, pos) => {
                write!(f, "Line {}:{} Empty key.", token.line, pos)
            },

            SmallError::Indent(token, _) => {
                write!(f, "Line {}:{} Indentation should be aligned by {} to the top key ",
                    token.line,
                    token.start_key.unwrap(),
                    INDENTSTEP
                )
            },

            SmallError::Empty => {
                write!(f, "The input string is empty.")
            },

            SmallError::FloatParse(token) => {
                write!(f, "Line {}:{} [{}] The number could not be parsed as a float.",
                       token.line,
                       token.start_val.unwrap(),
                       token.text.trim().cyan().bold(),
                )
            },

            SmallError::IsKey(s) => {
                write!(f, "Expected 'key: value' but found only key \"{}\"", s)
            },

            SmallError::IsValue(s) => {
                write!(f, "\"{}\" is a value, not a key.", s)
            },

            SmallError::IntegerParse(token) => {
                write!(f, "Line {}:{} [{}] The number could not be parsed as an integer.",
                       token.line,
                       token.start_val.unwrap(),
                       token.text.trim().cyan().bold(),
                )
            },

            SmallError::KeyParse(s) => {
                write!(f,
                       "\"{}\" cannot be parsed.", s)
            },

            SmallError::NoQuoteAfterKey(token, pos) => {
                write!(f, "Line {}:{} Value must start with double quotemark", token.line, pos)
            },

            SmallError::NoSecondQuote(token, pos) => {
                write!(f, "Line {}:{} No second quote.", token.line, pos)
            },

            SmallError::NoSpaceAfterKey(token) => {
                write!(f, "Line {}:{} No space after .", token.line, token.end_key.unwrap())
            },

            SmallError::PathIsEmpty => {
                write!(f, "There is no data in that path.")
            },

            SmallError::QuotemarkInKey(token, pos) => {
                write!(f, "Line {}:{} Quote mark in key.", token.line, pos)
            },

            SmallError::Quotes(line, tok_s) => {
                write!(f,
                       "line {}: \"{}\" is not correctly quoted.",
                       line,
                       tok_s,
                )
            },

            SmallError::NoColon(token, pos) => {
                write!(f, "Line {}: [{}] should have a colon after the key at position {}.", token.line, token.text, pos)
            },

            SmallError::NotUnique(n) => {
                write!(f,
                       "Resulted in {} keys, but expected 1.", n)
            },

            SmallError::Reduction => {
                write!(f, "{}", "reduction")
            },
            SmallError::TopValueMismatch => {
                write!(f, "{}", "top_value_mismatch")
            },

            SmallError::User(s) => {
                write!(f, "{}", s)
            },
        }
    }
}

struct KeyPath(Vec<Key>);

impl KeyPath {
    pub fn from_str(s: &str) -> Result<Self, SmallError> {
        let mut v = Vec::new();
        for key in s.split("::") {
        
            if key.contains(":") {
                return Err(SmallError::KeyParse(key.to_string()))
            };
            v.push(Key::from_str(key));
        };
        Ok(KeyPath(v))
    }

    fn iter(&self) -> Iter<Key> {
        self.0.iter() 
    }
}

// A key_path looks like 'hobbit::friends::name'.
impl fmt::Display for KeyPath {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut s = String::new();
        for i in self.iter() {
            s.push_str(&format!("{}::", i));
        };
        s.pop();
        s.pop();
        write!(f, "{}", s)
    }
}

// A key_path looks like hobbit::friends::name. A key looks like 'friends'.
#[derive(Clone, Debug, PartialEq)]
struct Key(String);

impl Key {
    fn from_str(s: &str) -> Self {
        Key(s.to_string())
    }

    fn len(&self) -> usize {
        self.0.len()
    }
}

// This doesn't display the colon at the end. This has to appended when required.
impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Clone, Debug)]
pub struct Token {
    text:      String,
    line:      usize,          // This is line in original input string.  
    start_key: Option<usize>,
    end_key:   Option<usize>,
    start_val: Option<usize>,
    end_val:   Option<usize>,
}

enum PS {     // Parse State.
    BK,       // Before key.
    IK,       // In key.
    RAK,      // Right after key.
    AK,       // After key.
    IV,       // In value.
    AV,       // After value.
}


impl Token {

    fn new(
        text:       &str,
        line:       usize,
        start_key:  Option<usize>,
        end_key:    Option<usize>,
        start_val:  Option<usize>,
        end_val:    Option<usize>) -> Self {

        Token {
            text:       text.to_string(),
            line:       line,
            start_key:  start_key,
            end_key:    end_key,
            start_val:  start_val,
            end_val:    end_val,
        }
    }

    // Parses a line of text and return a Token. Iterate over the characters, one at a time. The
    // parse state (enum PS) changes as we go through the string.
    fn from_str(s: &str, line: usize, root_indent: usize) -> Result<Option<Self>, SmallError> {

        let mut ps = PS::BK;
        let mut escape = false;
        let mut start_key:   Option<usize> = None;
        let mut end_key:     Option<usize> = None;
        let mut start_val:   Option<usize> = None;
        let mut end_val:     Option<usize> = None;
        
        for (pos, c) in s.char_indices() {
            
            // Before key.
            if let PS::BK = ps {
                if c == ':' {
                    start_key = Some(pos);
                    let token = Token::new(s, line, start_key, end_key, start_val, end_val);
                    return Err(SmallError::EmptyKey(token, pos));
                };
                if !c.is_whitespace() {
                    start_key = Some(pos);
                    if (pos - root_indent) % INDENTSTEP != 0 {
                        let token = Token::new(s, line, start_key, end_key, start_val, end_val);
                        return Err(SmallError::Indent(token, root_indent));
                    };
                    ps = PS::IK;
                };
                continue; // Next char.
            };

            // In key.
            if let PS::IK = ps {
                if c == '"' {
                    let token = Token::new(s, line, start_key, end_key, start_val, end_val);
                    return Err(SmallError::QuotemarkInKey(token, pos));
                };
                if c.is_whitespace() {
                    let token = Token::new(s, line, start_key, end_key, start_val, end_val);
                    return Err(SmallError::NoColon(token, pos));
                };
                if c == ':' {
                    if Some(pos) == start_key {
                        let token = Token::new(s, line, start_key, end_key, start_val, end_val);
                        return Err(SmallError::EmptyKey(token, pos))
                    } else {
                        end_key = Some(pos);
                        ps = PS::RAK;
                        continue;
                    };
                };
            };

            // Right after key.
            if let PS::RAK = ps {
                if !c.is_whitespace() {
                    let token = Token::new(s, line, start_key, end_key, start_val, end_val);
                    return Err(SmallError::NoSpaceAfterKey(token))
                } else {
                    ps = PS::AK;
                    continue;
                }
            };

            // After key.
            if let PS::AK = ps {
                if c.is_whitespace() {
                    continue;
                } else {
                    if c != '"' {
                        let token = Token::new(s, line, start_key, end_key, start_val, end_val);
                        return Err(SmallError::NoQuoteAfterKey(token, pos))
                    } else {
                        start_val = Some(pos);
                        ps = PS::IV;
                        continue;
                    }
                }
            };

            // In value.
            if let PS::IV = ps {
                if c == '\\' {
                    escape = true;
                } else if c == '"' && escape {
                        continue;
                } else if c == '"' {
                    ps = PS::AV;
                    end_val = Some(pos);
                } else {
                    escape = false;
                    continue;
                }
            };

            // After value.
            if let PS::AV = ps {
                break;
            }
        };

        let token = Token::new(s, line, start_key, end_key, start_val, end_val);

        if let PS::BK = ps {
            return Ok(None)
        };

        if let PS::IK = ps {
            return Err(SmallError::NoColon(token, s.char_indices().count()))
        }

        if let PS::RAK = ps {
            return Ok(Some(token))
        }

        if let PS::AK = ps {
            return Ok(Some(token))
        }

        if let PS::IV = ps {
            return Err(SmallError::NoSecondQuote(token, s.char_indices().count()))
        }

        Ok(Some(token))
    }

    fn key(&self) -> Key {
        Key::from_str(&self.text[self.start_key.unwrap()..=self.end_key.unwrap() - 1].to_string())
    }

    // This function shouldn't fail, as indentation should be checked during parsing.
    fn indent(&self) -> usize {
        self.start_key.unwrap()
    }

    fn line(&self) -> usize {
        self.line
    }

    fn is_value(&self) -> bool {
        if let (Some(_), Some(_), Some(_), Some(_)) = 
               (self.start_key, self.end_key, self.start_val, self.end_val) {
                   true
               } else {
                   false
               }
    }

    fn value(&self) -> Result<String, SmallError> {
        if self.is_value() {
            Ok(self.text[self.start_val.unwrap() + 1..=self.end_val.unwrap() - 1].to_string())
        } else {
            Err(SmallError::IsKey(self.clone()))
        }
    }
}

impl Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.text)
    }
}

// `Token` maps each line of a `Small` string to a Token.
#[derive(Debug)]
pub struct Tokens(Vec<Token>);

impl Tokens {
    pub fn from_str(s: &str) -> Result<Self, SmallError> {
        let mut v = Vec::new();

        let root_indent = match s.lines().find(|&ln| ln.chars().any(|c| c.is_whitespace())) {
            Some(line) => {
                line.chars().position(|c| !c.is_whitespace()).unwrap()
            },
            None => {
                return Err(SmallError::Empty);
            },
        };

        for (line, tok_str) in s.lines().enumerate() {
            match Token::from_str(tok_str, line, root_indent)? {
                Some(ts) => {
                    v.push(ts);
                },
                None => {},
            };
        };
        Ok(Tokens(v))
    }
}

impl Index<usize> for Tokens {
    type Output = Token;

    fn index(&self, i: usize) -> &Token {
        &self.0[i]
    }
}

impl fmt::Display for Tokens {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut s = String::new();
        self.0.iter().for_each(|token| s.push_str(&format!("{}\n", token.to_string())));
        s.pop();
        write!(f, "{}", s)
    }
}

#[derive(Clone, Debug)]
pub struct Data<'a> {
    // A vector of each line in the string, converted to a Token. This does not mutate.
    pub tokens:     &'a Tokens,

    // A reduction involves reducing valid tokens by walking down the tree of tokens
    // ("key1::key2::.."). The slice points to a single value or a structure within the tokens.
    // The Vec holds all the values or structs that comply with a reduction. For example
    //
    //  name:         "Frodo Baggins"
    //  age:          "98"
    //  friends:
    //      hobbit:                     <----          
    //          name: "Bilbo Baggins"        slice1 <-- vec[0]
    //          age:  "176"             <----
    //      hobbit:                     <----
    //          name: "Samwise Gamgee"       slice2 <-- vec[1]
    //          age:  "66""#;           <----           
    //
    reduction:  Vec<&'a [Token]>,
}

impl<'a> Data<'a> {

    fn tokens(&self) -> Vec<String> {
        let mut v = Vec::new();

        for key_set in self.reduction.iter() {
            for token in key_set.iter() {
                v.push(token.to_string())
            }
        }
        v
    }

    // If the key cannot be found, the Data.reduction will be empty.
    fn reduce_once(self, s: &str) -> Result<Data<'a>, SmallError> {
        let key = Key::from_str(s);
        let mut reduction: Vec<&[Token]> = Vec::new();

        for &slice in self.reduction.iter() {
            let root_indent = slice[0].indent();
            let mut i = 0usize;
            'outer: loop {
                if slice[i].key() == key && (slice[i].indent() - root_indent) / INDENTSTEP == 1 {
                    let start_index = i;
                    'inner: loop {

                        // Process the case where the slice is not the last token and the next
                        // token is a different key.
                        if (i < slice.len() - 1) &&
                           ((slice[i + 1].indent() - root_indent) / INDENTSTEP <= 1) {
                            let end_index = i;
                            reduction.push(&slice[start_index..=end_index]);
                            break 'inner;
                        }

                        //Process the case where the slice in the last token.
                        if i == slice.len() - 1 {
                            let end_index = i;
                            reduction.push(&slice[start_index..=end_index]);
                            break 'outer;
                        };

                        i += 1
                    }
                };
                i += 1;
                if i == slice.len() { break 'outer };
            };
        };
        Ok(Data {
            tokens:     self.tokens,
            reduction:  reduction, 
        })
    }

    fn reduce(&self, s: &str) -> Result<Data, SmallError> {
        let key_path = KeyPath::from_str(s)?;
        let mut reduction = self.clone();
        for (i, key) in key_path.iter().enumerate() {
            if i > 0 {
                reduction = reduction.reduce_once(&key.to_string())?;
            };
        }
        Ok(reduction)
    }
}

impl<'a> Display for Data<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut s = String::new();
        s.push_str("reductions:\n");
        for slice in self.reduction.iter() {
            s.push_str("[\n");
            for token in slice.iter() {
                s.push_str(&token.to_string());
                s.push('\n');
            }
            s.push_str("]\n");
        }
        s.pop();
        write!(f, "{}", s)
    }
}

impl<'a> Data<'a> {
    // Helper function that checks that self has only one 'key: value', and returns the `Token` if
    // this is the case.
    fn unique_value(&self) -> Result<Token, SmallError> {
        if  self.reduction.is_empty() {
            return Err(SmallError::PathIsEmpty)
        };
        if self.reduction.len() > 1 {
            return Err(SmallError::NotUnique(self.reduction.len()))
        };

        let token = &self.reduction[0][0];
        if token.is_value() {
            Ok(token.clone())
        } else {
            Err(SmallError::IsKey(token.clone()))
        }
    }
}

/// Data-structures that implement the `Small` trait can be constructed from a `Small` formatted
/// string.
///
pub trait Small {

    /// Takes a `String` in the small data format to a data-structure. `Data` is a partial
    /// compilation of the the small data-formatted string. You don't need to know anything about
    /// `Data` other than that it is a argument to the `sml()` function.
    ///
    /// ```
    /// use small::{Data, Small, SmallError};
    /// 
    /// #[derive(Debug)]
    /// struct Hobbit {
    ///     name:    String,
    ///     age:     u32,
    ///     friends: Vec<Hobbit>,
    ///     bicycle: Option<String>,
    /// }
    /// 
    /// impl Small for Hobbit {
    ///     fn from_data(data: Data) -> Result<Self, SmallError> {
    ///         Ok(Self {
    ///             name:    String::sml(&data, "hobbit::name")?,
    ///             age:     u32::sml(&data, "hobbit::age")?,
    ///             friends: Vec::<Hobbit>::sml(&data, "hobbit::friends::hobbit")?,
    ///             bicycle: Option::<String>::sml(&data, "hobbit::bicycle")?,
    ///         })
    ///     }
    /// }
    /// 
    /// fn main() {
    ///     let s = r#"
    ///         hobbit:
    ///             name:         "Frodo Baggins"
    ///             age:          "98"
    ///             friends:
    ///                 hobbit:
    ///                     name: "Bilbo Baggins"
    ///                     age:  "176"
    ///                 hobbit:
    ///                     name: "Samwise Gamgee"
    ///                     age:  "66""#;
    ///     
    ///     let frodo = Hobbit::from_str_debug(s);
    /// }
    /// ```
    fn from_data(data: Data) -> Result<Self, SmallError>
        where Self: std::marker::Sized;


    // Reduces data and pass it on to from_data().
    /// If stepping through the key path results in a `key: value` pair (usually representing a
    /// field) then the value is passed to the `from_data()` functon as a `String`. If stepping
    /// through the key path resulting in a `key:` only then a `String` of all the children
    /// (usually representing a data-structure) of that key is returned.
    ///
    ///
    ///
    /// Takes a partial compilation of a small data-formatted string, and a series of keys stepping
    /// into the data format, and returns a data structure or a value. See the main example for a
    /// better understanding.
    ///
    /// If you need something more complex than a `u32`, `String` etc. you can either implement
    /// this using `from_data()` or simply convert from one of the existing conversions, for
    /// example,
    ///
    /// ```
    /// let first_name = String::sml(&data, "hobbit::name")?.first_word();
    /// let last_name = String::sml(&data, "hobbit::name")?.last_word();
    /// ```
    ///
    /// The `from_data()` function is the same as the `sml()` function except that it doesn't do
    /// any transformation by stepping through a key path, so its main role is to convert from
    /// `Data` to some other type.
    ///
    fn sml(data: &Data, key_path: &str) -> Result<Self, SmallError>
        where Self: std::marker::Sized {

        Ok(Self::from_data(data.reduce(key_path)?)?)
    }

    /// Converts a `Small` markup into a data-structure.
    fn from_str(s: &str) -> Result<Self, SmallError>
        where Self: std::marker::Sized {

        let tokens = Tokens::from_str(s)?;
        let data = Data {
            tokens:         &tokens,
            reduction:      vec!(&tokens.0[..]),
        };
        Ok(Self::from_data(data)?)
    }

    /// Converts a small data-formatted string into a data-structure. This function is designed to
    /// give helpful error messages for debugging and then to exit. See the main example for a
    /// better understanding.
    /// 
    fn from_str_debug(s: &str) -> Self
        where Self: std::marker::Sized {

        match Self::from_str(s) {
            Ok(s) => s,
            Err(e) => {
                match e {

                    SmallError::BoolParse(token) => {
                        let info = &format!(
                               "{}{} {}",
                               " ".repeat(token.start_val.unwrap() + 1),
                               "^".repeat(token.value().unwrap().char_indices().count()).yellow().bold(),
                               "number could not be parsed as bool".yellow().bold(),
                        );
                        in_context(s, info, token.line);
                    },

                    SmallError::Empty => {
                        eprintln!("The input data string is empty.");
                    }


                    SmallError::EmptyKey(token, pos) => {
                        let info = &format!(
                            "{}{} {}",
                            " ".repeat(pos),
                            "^".yellow().bold(),
                            "missing key".yellow().bold(),
                        );
                        in_context(s, info, token.line);
                    },

                    SmallError::FloatParse(token) => {
                        let info = &format!(
                               "{}{} {}",
                               " ".repeat(token.start_val.unwrap() + 1),
                               "^".repeat(token.value().unwrap().char_indices().count()).yellow().bold(),
                               "number could not be parsed as float".yellow().bold(),
                        );
                        in_context(s, info, token.line);
                    },

                    SmallError::Indent(token, _) => {

                        let info = &format!(
                            "{}{}{}{} {} {} {}",
                            " ".repeat(token.start_key.unwrap() - 4 - (token.start_key.unwrap() % 4)),
                            "|".yellow().bold(),
                            "_".repeat(3).yellow().bold(),
                            "|".yellow().bold(),
                            "indent".yellow().bold(),
                            INDENTSTEP.to_string().yellow().bold(),
                            "spaces only".yellow().bold()

                        );
                        in_context(s, info, token.line);
                    },

                    SmallError::IntegerParse(token) => {
                        let info = &format!(
                               "{}{} {}",
                               " ".repeat(token.start_val.unwrap() + 1),
                               "^".repeat(token.value().unwrap().char_indices().count()).yellow().bold(),
                               "number could not be parsed as integer".yellow().bold(),
                        );
                        in_context(s, info, token.line);
                    },

                    SmallError::NoColon(token, pos) => {
                        let info = &format!(
                            "{}{} {}",
                            " ".repeat(token.start_key.unwrap()),
                            "^".repeat(pos - token.start_key.unwrap()).yellow().bold(),
                            "key requires colon".yellow().bold()
                        );
                        in_context(s, info, token.line);
                    },

                    SmallError::QuotemarkInKey(token, pos) => {
                        let info = &format!(
                            "{}{} {}",
                            " ".repeat(pos),
                            "^".yellow().bold(),
                            "no double quotes allowed in key".yellow().bold(),
                        );
                        in_context(s, info, token.line);
                    }

                    SmallError::NoSecondQuote(token, pos) => {
                        let info = &format!(
                            "{}{} {}",
                            " ".repeat(pos),
                            "^".yellow().bold(),
                            "missing second quotemark".yellow().bold(),
                        );
                        in_context(s, info, token.line);
                    }

                    SmallError::NoSpaceAfterKey(token) => {
                        let info = &format!(
                            "{}{}{} {}",
                            " ".repeat(token.start_key.unwrap()),
                            " ".repeat(token.end_key.unwrap() + 1 - token.start_key.unwrap()),
                            "^".yellow().bold(),
                            "requires at least one space after key".yellow().bold()
                        );
                        in_context(s, info, token.line);
                    },
                    _ => eprintln!("{}", e.to_string()),
                };
                exit(1);
            },
        }
    }
}

fn in_context(s: &str, info: &str, line: usize) {
    for (i, ln) in s.lines().take(20).enumerate() {
        eprintln!("{}", ln);
        if i == line {
            eprintln!("{}", info);
        };
    };

}

impl Small for String {
    fn from_data(data: Data) -> Result<Self, SmallError> {
        let token = data.unique_value()?;
        Ok(token.value()?)
    }
}

impl Small for u32 {
    fn from_data(data: Data) -> Result<Self, SmallError> {
        let token = data.unique_value()?;
        match token.value()?.parse::<u32>() {
            Ok(n) => Ok(n),
            Err(_) => Err(SmallError::IntegerParse(token)),
        }
    }
}

impl Small for f32 {
    fn from_data(data: Data) -> Result<Self, SmallError> {
        let token = data.unique_value()?;
        match token.value()?.parse::<f32>() {
            Ok(n) => Ok(n),
            Err(_) => Err(SmallError::FloatParse(token)),
        }
    }
}

impl Small for bool {
    fn from_data(data: Data) -> Result<Self, SmallError> {
        let token = data.unique_value()?;
        let s = token.value()?;
        if s == String::from("false") {
            Ok(false)
        } else if s == String::from("true") {
            Ok(true)
        } else {
            Err(SmallError::BoolParse(token))
        }
    }
}

impl<T> Small for Option<T> where T: Small {
    fn from_data(data: Data) -> Result<Self, SmallError> {
        if data.reduction.is_empty() {
            return Ok(None)
        } else {
            Ok(Some(T::from_data(data)?))
        }
    }
}

impl<T> Small for Vec<T> where T: Small {
    fn from_data(data: Data) -> Result<Self, SmallError> {
        let mut v: Vec<T> = Vec::new();
        for &slice in data.reduction.iter() {
            let dat = Data {
                tokens:    data.tokens,
                reduction: vec!(slice),
            };
            v.push(T::from_data(dat)?);
        };
        Ok(v)
    }
}