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
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
//! # SML
//!
//! `SML` is a simple markup language. It is designed to convert human readable information into
//! Rust data-structures.
//!
//! # Data Format
//!
//! 1. Each line can either be just a key, for example
//! ```
//!     key:
//! ```
//! or it can be a key/value pair, for example
//! ```
//!     key: "value"
//! ```
//!
//! 2. Indentation has meaning and is 4 spaces. The first key on the first line determines the
//!    alignment of indentation.
//!
//! 3. All values must be double quoted.
//!
//! 4. Every key/value pair must be nested in a key. For example
//! ```
//!     hobbit: "Frodo"
//! ```
//! by itself is invalid. It can be written:
//! ```
//!     hobbit:
//!         name: "Frodo"
//! ```
//! Thinking in terms of Rust data-structures, a key without a value represents a `struct` or an
//! `enum` while a key/value pair represents a `struct` field or `enum` variant.
//!
//! 5. Separation of lines has meaning.
//!
//! 6. Keys may not include `:`.
//!
//! 7. Double quotes in values must be escaped using `\"`.
//!
//! 8. There can be an arbitary amount of whitespace and returns before the first key and after the
//!    last key.
//!
//! 9. Characters after the second double-quote in the value are ignored (so this space can be used
//!    for comments).
//!
//! # Example
//!
//! Create a data-structure from a small-formatted string,
//!
//! ```
//! use sml::{Small, FromSmall, SmallError};
//!
//! #[derive(Debug)]
//! struct Hobbit {
//!     name:    String,
//!     age:     u32,
//!     friends: Vec<Hobbit>,
//!     bicycle: Option<String>,
//! }
//! 
//! impl FromSmall for Hobbit {
//!     fn from_small(small: Small) -> Result<Self, SmallError> {
//!         Ok(Self {
//!             name:    String::sml(&small, "hobbit::name")?,
//!             age:     u32::sml(&small, "hobbit::age")?,
//!             friends: Vec::<Hobbit>::sml(&small, "hobbit::friends::hobbit")?,
//!             bicycle: Option::<String>::sml(&small, "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);
//! }
//! ```
//!
//! and create a small-formatted string from a data-structure,
//!
//! ```
//! use sml::{Small, ToSmall, SmallError};
//!
//! #[derive(Debug)]
//! struct Hobbit {
//!     name:    String,
//!     age:     u32,
//!     friends: Vec<Hobbit>,
//!     bicycle: Option<String>,
//! }
//! 
//! impl ToSmall for Hobbit {
//!     fn to_small(&self) -> Small {
//!         Small::key("hobbit")
//!             .append(self.name)
//!             .append(self.age)
//!             .append(self.friends)
//!             .append(self.bicycle);
//!     }
//! }
//!
//! println!("{}", frodo::<ToSmall>::to_string());
//!
//! // hobbit:
//! //     name:         "Frodo Baggins"
//! //     age:          "98"
//! //     friends:
//! //         hobbit:
//! //             name: "Bilbo Baggins"
//! //             age:  "176"
//! //         hobbit:
//! //             name: "Samwise Gamgee"
//! //             age:  "66"
//! ```

#![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;

mod test;

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 {
    ///
    /// Failed to convert a `String` to a boolean. The two values that are accepted are `"true"`
    /// and `"false"`. Holds the `Token` that failed to parse.
    ///
    BoolParse(Token),

    ///
    /// Expected a key but could not find it. Holds the `Token` that failed to parse and the
    /// position in the line of the following colon.
    ///
    EmptyKey(Token, usize), 

    ///
    /// Indentation should be aligned by 4 to the top key. `usize` refers to the indent of the top
    /// key in the original string.
    ///
    Indent(Token, usize),

    ///
    /// The input string is empty.
    ///
    Empty,

    ///
    /// Could not parse the string as a float. Holds the `Token` that failed to parse.
    ///
    FloatParse(Token),

    ///
    /// Expected a unique key or key/value pair but could not find it.
    ///
    PathIsEmpty,

    /// 
    /// Expected key/value pair but found a key only. Holds the `Token` that failed to parse.
    ///
    IsKey(Token),

    /// 
    /// Expected a key but found a key/value pair.
    ///
    IsValue(String),

    ///
    /// Failed to parse a key path.
    ///
    KeyParse(String),

    ///
    /// Could not parse the string as an integer. Holds the `Token` that failed to parse.
    ///
    IntegerParse(Token),

    ///
    /// Expected a colon after the key. Holds the `Token` that failed to parse and the position
    /// where a colon was expected.
    ///
    NoColon(Token, usize),

    ///
    /// Values should start with a double quotemark. Holds the `Token` that failed to parse and a
    /// `usize` of the expected position of the quote.
    ///
    NoQuoteAfterKey(Token, usize),

    ///
    /// Values should end with a double quotemark. Holds the `Token` that failed to parse and a
    /// `usize` of the expected position of the second quote.
    ///
    NoSecondQuote(Token, usize),

    ///
    /// Keys and Values should be separated by at least one space. Holds the `Token` that failed to
    /// parse.
    ///
    NoSpaceAfterKey(Token),

    ///
    /// Expected one key but found many. Holds a `usize` of the number of keys.
    ///
    NotUnique(usize),

    ///
    /// Keys should not contain double quotemarks. Holds the `Token` that failed to parse and a
    /// `usize` of the position of the double quote.
    ///
    QuotemarkInKey(Token, usize),  // usize refers to position of quote.
}

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::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::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)
            },
        }
    }
}

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)
    }
}

/// The `Token` struct contains implementation details of a parsed line of the input `String`. Its
/// not really part of the API, but gets passed around by `SmallError` and as such is public.
#[derive(Clone, Debug)]
pub struct Token {
    text:      String,         // A line from the original input string.
    line:      usize,          // The line number in original input string.
    start_key: Option<usize>,  // Index to start of key, if it could be parsed.
    end_key:   Option<usize>,  // Index to end of key (including ':') if it could be parsed.
    start_val: Option<usize>,  // Index to start of value (including ") if it could be parsed.
    end_val:   Option<usize>,  // Index to end of value (including ") if it could be parsed.
}

// Parser State
enum PS {
    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)
    }
}

/// `Small` is an internal representation of the original input string, or part of the
/// original string.
#[derive(Clone, Debug)]
pub struct Small<'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> Small<'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<Small<'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(Small {
            tokens:     self.tokens,
            reduction:  reduction, 
        })
    }

    fn reduce(&self, s: &str) -> Result<Small, 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)
    }

    // fn key_value<T>(key: &str, value: T) -> Result<Self, SmallError>
    //     where T: ToSmall {

    //     let value = value.to_string();

    //     let text = &format!("{}: \"{}\"", key, value);

    //     let tokens = vec!(Token::from_str(text, 0, 0))?;

    //     let () = tokens;

    //     Ok(Small {
    //         tokens:     &tokens,
    //         reduction:  vec!(&tokens.0[..]),
    //     })
    // }
}

impl<'a> Display for Small<'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> Small<'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 `FromSmall` trait can be constructed from a small-formatted
/// string.
///
pub trait FromSmall {

    /// The `from_small()` function describes how to create a data-structure from the internal
    /// components of the input `String`. It maps a selection from the original input `String` to
    /// `Self`. For example,
    ///
    /// ```
    /// use small::{Small, FromSmall, SmallError};
    /// 
    /// #[derive(Debug)]
    /// struct Hobbit {
    ///     name:    String,
    ///     age:     u32,
    ///     friends: Vec<Hobbit>,
    ///     bicycle: Option<String>,
    /// }
    /// 
    /// impl FromSmall for Hobbit {
    ///     fn from_small(small: Small) -> Result<Self, SmallError> {
    ///         Ok(Self {
    ///             name:    String::sml(&small, "hobbit::name")?,
    ///             age:     u32::sml(&small, "hobbit::age")?,
    ///             friends: Vec::<Hobbit>::sml(&small, "hobbit::friends::hobbit")?,
    ///             bicycle: Option::<String>::sml(&small, "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_small(small: Small) -> Result<Self, SmallError>
        where Self: std::marker::Sized;


    /// Applies a keypath to `Small` and returns a `Vec` of `Small`s. For example applying
    /// `"hobbit::name"` to
    ///
    /// ```text
    ///         hobbit:
    ///             name:         "Frodo Baggins"
    ///             age:          "98"
    ///             friends:
    ///                 hobbit:
    ///                     name: "Bilbo Baggins"
    ///                     age:  "176"
    ///                 hobbit:
    ///                     name: "Samwise Gamgee"
    ///                     age:  "66""#;
    /// ```
    /// returns a `Vec` with one `Small` element,
    /// ```
    ///             name:         "Frodo Baggins"
    /// ```
    /// Applying `"hobbit::name::friends"` to the original string returns a `Vec` with two `Small`
    /// elements which represent
    /// ```text
    ///                 hobbit:
    ///                     name: "Bilbo Baggins"
    ///                     age:  "176"
    /// ```
    /// and
    /// ```text
    ///                 hobbit:
    ///                     name: "Samwise Gamgee"
    ///                     age:  "66""#;
    /// ```
    ///
    fn sml(small: &Small, key_path: &str) -> Result<Self, SmallError>
        where Self: std::marker::Sized {

        Ok(Self::from_small(small.reduce(key_path)?)?)
    }

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

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

    /// Converts a `String` into `Self`. This function is designed to give helpful error messages
    /// for debugging.
    /// 
    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 to_sml(small: &Small) -> String {
        small.to_string()
    }
}

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);
        };
    };
}

/// Converts a `Vec` of one `Small` element to a `String`.
impl FromSmall for String {
    fn from_small(small: Small) -> Result<Self, SmallError> {
        let token = small.unique_value()?;
        Ok(token.value()?)
    }
}

/// Converts a `Vec` with one `Small` element to a `u32`.
impl FromSmall for u32 {
    fn from_small(small: Small) -> Result<Self, SmallError> {
        let token = small.unique_value()?;
        match token.value()?.parse::<u32>() {
            Ok(n) => Ok(n),
            Err(_) => Err(SmallError::IntegerParse(token)),
        }
    }
}

/// Converts a `Vec` with one `Small` element to a `usize`.
impl FromSmall for usize {
    fn from_small(small: Small) -> Result<Self, SmallError> {
        let token = small.unique_value()?;
        match token.value()?.parse::<usize>() {
            Ok(n) => Ok(n),
            Err(_) => Err(SmallError::IntegerParse(token)),
        }
    }
}

/// Converts a `Vec` with one `Small` element to a `f32`.
impl FromSmall for f32 {
    fn from_small(small: Small) -> Result<Self, SmallError> {
        let token = small.unique_value()?;
        match token.value()?.parse::<f32>() {
            Ok(n) => Ok(n),
            Err(_) => Err(SmallError::FloatParse(token)),
        }
    }
}

/// Converts a `Vec` with one `Small` element to a `bool`.
impl FromSmall for bool {
    fn from_small(small: Small) -> Result<Self, SmallError> {
        let token = small.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))
        }
    }
}

/// Converts a `Vec` with either one or no `Small` elements to an `Option<T>`.
impl<T> FromSmall for Option<T> where T: FromSmall {
    fn from_small(small: Small) -> Result<Self, SmallError> {
        if small.reduction.is_empty() {
            return Ok(None)
        } else {
            Ok(Some(T::from_small(small)?))
        }
    }
}

/// Converts a `Vec` of `Small` elements to a `Vec<T>`.
impl<T> FromSmall for Vec<T> where T: FromSmall {
    fn from_small(small: Small) -> Result<Self, SmallError> {
        let mut v: Vec<T> = Vec::new();
        for &slice in small.reduction.iter() {
            let dat = Small {
                tokens:    small.tokens,
                reduction: vec!(slice),
            };
            v.push(T::from_small(dat)?);
        };
        Ok(v)
    }
}

pub trait ToSmall {
    fn to_small(&self) -> Result<Small, SmallError>;

    fn to_string(&self) -> String;
}