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
//! Module for handling all productions related operations.
//!
//! Its goal is to emulate a formal grammar production.
//!
//! It defines a `Production` type which can be used to conveniently work with productions in grammars,
//! and provide abstraction over normal collection of symbols, organized in a left and right hand side (form A -> B).
//!
//! It can be easily constructed from `&str`s or collections of [Symbol](../symbol/struct.Symbol.html)s.

use crate::symbol::{sentential_form, Symbol, SymbolError};
use crate::tokenizer;
use crate::tokenizer::TokenizerError;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::error::Error;
use std::fmt;

#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum ProductionError {
    /// Error returned for trying to create a Production with an empty / missing left hand side.
    /// Left hand side of productions should be an ordered collection of n >= 1 symbols.
    NoLhs,
    /// Error returned for trying to create a Production with an empty / missing right hand side.
    /// Right hand side of productions should be an ordered collection of n >= 1 symbols.
    NoRhs,
    /// Error returned for trying to create a Production with invalid symbols.
    /// To be expected when creating productions from raw string inputs.
    SymbolError(SymbolError),
    /// Error returned for trying to create a Production with a bad formatted raw input string.
    /// Properly formatted productions as strings are described in the
    /// [Production](struct.Production.html) documentation.
    FormatError(TokenizerError),
}

impl fmt::Display for ProductionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProductionError::NoLhs => write!(f, "ProductionError: no lhs in production"),
            ProductionError::NoRhs => write!(f, "ProductionError: no rhs in production"),
            ProductionError::SymbolError(e) => {
                write!(f, "ProductionError: symbol error encountered = {}", e)
            }
            ProductionError::FormatError(e) => write!(
                f,
                "ProductionError: bad formatted string encountered, error = {}",
                e
            ),
        }
    }
}

impl Error for ProductionError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            ProductionError::SymbolError(e) => Some(e),
            ProductionError::FormatError(e) => Some(e),
            _ => None,
        }
    }
}

impl std::convert::From<TokenizerError> for ProductionError {
    fn from(e: TokenizerError) -> Self {
        ProductionError::FormatError(e)
    }
}

/// A predicate for checking if production match some expected characteristics.
///
/// You can test a predicate on a Production by using the [test]: #method.test method.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ProductionPredicate {
    /// It checks if the left hand side of the production equals the given ordered collection of symbols.
    LhsEquals(Vec<Symbol>),
    /// It checks if the right hand side of the production equals the given ordered collection of symbols.
    RhsEquals(Vec<Symbol>),
    /// It checks if the right hand side length (symbols count) of the production equals the given number.
    RhsLengthEquals(usize),
    /// It checks if the right hand side of the production ends with the given ordered collection of symbols.
    RhsIsSuffixOf(Vec<Symbol>),
}

impl ProductionPredicate {
    /// Test if a production match the predicate
    ///
    /// # Examples
    /// ```rust
    /// use liblet::production::{ProductionPredicate, production};
    /// use liblet::symbol::symbol;
    ///
    /// // create a new production "A -> B C"
    /// let p = production("A", "B C");
    /// let rhs = vec![symbol("B"), symbol("C")];
    ///
    /// assert!(ProductionPredicate::RhsEquals(rhs).test(&p));
    /// ```
    pub fn test(&self, p: &Production) -> bool {
        match self {
            ProductionPredicate::LhsEquals(symbols) => p.lhs() == *symbols,
            ProductionPredicate::RhsEquals(symbols) => p.rhs() == *symbols,
            ProductionPredicate::RhsLengthEquals(length) => p.rhs().len() == *length,
            ProductionPredicate::RhsIsSuffixOf(symbols) => p.rhs().ends_with(&symbols),
        }
    }
}

impl fmt::Display for ProductionPredicate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProductionPredicate::LhsEquals(symbols) => write!(
                f,
                "ProductionPredicate: lhs == {}",
                sentential_form(symbols.clone())
            ),
            ProductionPredicate::RhsEquals(symbols) => write!(
                f,
                "ProductionPredicate: rhs == {}",
                sentential_form(symbols.clone())
            ),
            ProductionPredicate::RhsIsSuffixOf(symbols) => write!(
                f,
                "ProductionPredicate: rhs suffix == {}",
                sentential_form(symbols.clone())
            ),
            ProductionPredicate::RhsLengthEquals(length) => {
                write!(f, "ProductionPredicate: rhs length == {}", length)
            }
        }
    }
}

/// The main type of this module.
///
/// It allows to abstract over grammar productions, having a defined left and right and side,
/// which are ordered collections of symbols.
///
/// A production can be created easily from strings, following these rules:
/// - string can contain any number of whitespace
/// - multiple productions are divided by '\n' char
/// - string must have a sequence of symbol to the left of a "->"
/// - string must have a sequence of alternatives to the right of a "->"
/// - string can have only one "->" per production (per line)
/// - a sequence of symbol is a sequence of symbols divided by some whitespace
/// - a sequence of alternative is one ore more sequence of symbols divided by the "|" char
/// - string can't contain anything else
///
/// # Examples
/// `A -> B` leads to a production from the symbol `A` to the symbol `B`
///
/// `A -> B | C` leads to two productions, one for each alternative (`A` -> `B` and `A` -> `C`)
///
/// `A -> B\nA -> C` leads to the same result of the above one, defining the two productions separately
///
/// `A -> ` will results in an error, because there's no right hand side for the production
#[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Production {
    lhs: Vec<Symbol>,
    rhs: Vec<Symbol>,
}

impl fmt::Display for Production {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for lhs in self.lhs() {
            write!(f, "{} ", lhs)?;
        }
        write!(f, "->")?;
        for rhs in self.rhs() {
            write!(f, " {}", rhs)?;
        }

        Ok(())
    }
}

impl std::convert::TryFrom<&str> for Production {
    type Error = ProductionError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let p = Production::from_string(value)?;
        let mut p_iter = p.iter();
        if let Some(p) = p_iter.next() {
            if p_iter.next().is_none() {
                Ok(p.clone())
            } else {
                Err(ProductionError::FormatError(
                    TokenizerError::ProductionMultiple(value.to_string()),
                ))
            }
        } else {
            Err(ProductionError::FormatError(
                TokenizerError::ProductionEmpty(value.to_string()),
            ))
        }
    }
}

impl Production {
    /// Creates a new Production based on the left and right hand side given as collections of symbols.
    ///
    /// # Errors
    /// It can return an error if either the left or right hand side is empty.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::production::Production;
    /// use liblet::symbol::symbol;
    ///
    /// // create left and right hand side for production "A -> B C"
    /// let lhs = vec![symbol("A")];
    /// let rhs = vec![symbol("B"), symbol("C")];
    ///
    /// // create a new production based on the previously defined left and right hand side
    /// let production = Production::new(lhs, rhs);
    ///
    /// assert!(production.is_ok());
    /// ```
    pub fn new<I>(lhs: I, rhs: I) -> Result<Production, ProductionError>
    where
        I: IntoIterator<Item = Symbol>,
    {
        let lhs: Vec<Symbol> = lhs.into_iter().collect();
        let rhs: Vec<Symbol> = rhs.into_iter().collect();

        if lhs.is_empty() {
            return Err(ProductionError::NoLhs);
        }
        if rhs.is_empty() {
            return Err(ProductionError::NoRhs);
        }

        Ok(Production { lhs: lhs, rhs: rhs })
    }

    /// Creates a new Production based on the left and right hand side given as collections of `&str`.
    ///
    /// # Errors
    /// It can return an error if the strings are not convertible to [Symbol](../symbol/struct.Symbol.html)s.
    /// Otherwise, it acts like [new](#method.new).
    ///
    /// # Examples
    /// ```rust
    /// use liblet::production::Production;
    /// use liblet::symbol::symbol;
    ///
    /// // create left and right hand side for production "A -> B C"
    /// let lhs = vec!["A"];
    /// let rhs = vec!["B", "C"];
    ///
    /// // create a new production based on the previously defined left and right hand side
    /// let production = Production::new_from_string(lhs, rhs);
    ///
    /// assert!(production.is_ok());
    /// ```
    pub fn new_from_string<'a, I>(lhs: I, rhs: I) -> Result<Production, ProductionError>
    where
        I: IntoIterator<Item = &'a str>,
    {
        let lhs = lhs.into_iter().try_fold(Vec::new(), |mut acc, s| {
            let s = Symbol::new(s)?;
            acc.push(s);
            Ok(acc)
        });
        let rhs = rhs.into_iter().try_fold(Vec::new(), |mut acc, s| {
            let s = Symbol::new(s)?;
            acc.push(s);
            Ok(acc)
        });

        match (lhs, rhs) {
            (Ok(lhs), Ok(rhs)) => Production::new(lhs, rhs),
            (Err(e), _) => Err(ProductionError::SymbolError(e)),
            (_, Err(e)) => Err(ProductionError::SymbolError(e)),
        }
    }

    /// Return the ordered collection of symbol representing the left hand side of the production.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::production::{Production,production};
    /// use liblet::symbol::symbol;
    ///
    /// // create a production representing "A -> B C"
    /// let p = production("A", "B C");
    ///
    /// assert_eq!(p.lhs(), vec![symbol("A")]);
    /// ```
    pub fn lhs(&self) -> Vec<Symbol> {
        self.lhs.clone()
    }

    /// Return the ordered collection of symbol representing the right hand side of the production.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::production::{Production,production};
    /// use liblet::symbol::symbol;
    ///
    /// // create a production representing "A -> B C"
    /// let p = production("A", "B C");
    ///
    /// assert_eq!(p.rhs(), vec![symbol("B"), symbol("C")]);
    /// ```
    pub fn rhs(&self) -> Vec<Symbol> {
        self.rhs.clone()
    }

    /// Return a set containing all the different symbols which appears on the left
    /// and right hand side of the production.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::production::{Production,production};
    /// use liblet::symbol::{Symbol,symbol};
    /// use std::collections::HashSet;
    ///
    /// // create a production representing "A -> B C"
    /// let p = production("A", "B C");
    /// let symbols: HashSet<Symbol> = vec![symbol("A"), symbol("B"), symbol("C")].into_iter().collect();
    ///
    /// assert_eq!(p.symbols(), symbols);
    /// ```
    pub fn symbols(&self) -> HashSet<Symbol> {
        let mut symbols: Vec<Symbol> = self.lhs();
        symbols.append(&mut self.rhs());
        symbols.into_iter().collect()
    }

    /// Create a collection of productions from a raw input string.
    ///
    /// # Errors
    /// Can return an error if the raw string can't be parsed to obtain actual productions both due to wrong
    /// string formatting (LHS -> RHS | ...)(see [from_string](../symbol/struct.Symbol.html) method from symbols
    /// for more info about string formatting symbols) and due to production creation error (see production [constructor](#method.new) for more info).
    ///
    /// In the case an empty or whitespace only string is given, it just returns an empty collection of productions.
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::production::Production;
    ///
    /// let result = Production::from_string("
    ///     A -> B C
    ///     B -> b
    /// ")?;
    ///
    /// assert_eq!(result.len(), 2);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn from_string(string: &str) -> Result<Vec<Production>, ProductionError> {
        tokenizer::productions_from_string(string)?
            .iter()
            .try_fold(Vec::new(), |mut acc, p| {
                let p = Production::new_from_string::<Vec<&str>>(
                    p.0.iter().map(String::as_str).collect(),
                    p.1.iter().map(String::as_str).collect(),
                )?;
                acc.push(p);
                Ok(acc)
            })
    }

    /// Create a collection of productions from a collection of raw input string.
    /// Same as [from_string](#method.from_string) but accepts an `IntoIterator`.
    ///
    /// # Errors
    /// Can return an error if any of the raw strings can't be parsed to obtain actual productions both due to wrong
    /// string formatting (LHS -> RHS | ...)(see [from_string](../symbol/struct.Symbol.html) method from symbols
    /// for more info about string formatting symbols) and due to production creation error (see production [constructor](#method.new) for more info).
    ///
    /// In the case empty or whitespace only strings are given, it just returns an empty collection of productions.
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::production::Production;
    ///
    /// let result = Production::from_iter(vec![
    ///     "A -> B C",
    ///     "B -> b"
    /// ])?;
    ///
    /// assert_eq!(result.len(), 2);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn from_iter<'a, I>(strings: I) -> Result<Vec<Production>, ProductionError>
    where
        I: IntoIterator<Item = &'a str>,
    {
        let mut p: Vec<Production> = Vec::new();

        for string in strings {
            p.append(&mut Production::from_string(string)?)
        }

        Ok(p)
    }

    /// Return a boxed `FnMut` which accepts a production and test the given predicate on it, returning a `bool`ean value.
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::production::{Production,ProductionPredicate};
    /// use liblet::symbol::symbol;
    ///
    /// let p = Production::from_string("
    ///     A -> B C
    ///     B -> b
    /// ")?;
    /// let closure = Production::such_that(ProductionPredicate::RhsEquals(vec![symbol("b")]));
    /// let expected = Production::new(vec![symbol("B")], vec![symbol("b")])?;
    /// let mut result = p.iter().filter(closure);
    ///
    /// assert_eq!(result.next(), Some(&expected));
    /// assert_eq!(result.next(), None);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn such_that(predicate: ProductionPredicate) -> Box<dyn FnMut(&&Production) -> bool> {
        Box::new(move |p| predicate.test(&p))
    }
}

/// Convenience function for creating a production from a pair of raw strings
/// (left hand side and right hand side).
///
/// It returns the production directly,
/// as opposed to the `Result` returned from the production [constructor](struct.Production.html#method.new).
///
/// # Panics
/// Panics if some error occurred during production creation (see production [consructor](struct.Production.html#method.new) for further details)
///
/// # Examples
/// ```rust
/// use liblet::production::production;
/// use liblet::symbol::symbol;
///
/// let p = production("A", "B C");
///
/// assert_eq!(p.lhs(), vec![symbol("A")]);
/// assert_eq!(p.rhs(), vec![symbol("B"),symbol("C")]);
/// ```
pub fn production(lhs: &str, rhs: &str) -> Production {
    Production::new(
        Symbol::from_string(lhs).unwrap(),
        Symbol::from_string(rhs).unwrap(),
    )
    .unwrap()
}

/// Convenience function for creating a collection of productions from a raw string.
///
/// It returns the productions directly,
/// as opposed to the `Result` returned from the production [from_string](struct.Production.html#method.from_string) method.
///
/// # Panics
/// Panics if some error occurred during productions creation (see production [from_string](struct.Production.html#method.from_string) method for further details)
///
/// # Examples
/// ```rust
/// use liblet::production::productions;
///
/// let p = productions("
///     A -> B C
///     B -> b
/// ");
///
/// assert_eq!(p.len(), 2);
/// ```
pub fn productions(string: &str) -> Vec<Production> {
    Production::from_string(string).unwrap()
}

/// Convenience function for creating visual representation of
/// a collection of productions, ordered.
///
/// # Examples
/// ```rust
/// use liblet::production::{production_table, productions};
///
/// let p = productions("
///     A -> B C
///     B -> b
/// ");
/// let result = production_table(p);
///
/// assert_eq!(result, "0: A -> B C\n1: B -> b");
/// ```
pub fn production_table<I>(productions: I) -> String
where
    I: IntoIterator<Item = Production>,
{
    productions
        .into_iter()
        .enumerate()
        .map(|(i, p)| format!("{}: {}", i, p))
        .collect::<Vec<String>>()
        .join("\n")
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::symbol::symbol;
    use std::convert::TryFrom;
    use std::fmt::Write;

    // struct.Production

    #[test]
    fn from_string() {
        let p_check = vec![
            Production {
                lhs: vec![symbol("S")],
                rhs: vec![symbol("A"), symbol("B")],
            },
            Production {
                lhs: vec![symbol("A")],
                rhs: vec![symbol("a")],
            },
            Production {
                lhs: vec![symbol("A")],
                rhs: vec![symbol("B")],
            },
            Production {
                lhs: vec![symbol("B")],
                rhs: vec![symbol("b")],
            },
        ];

        assert_eq!(
            Production::from_string("S -> A B\nA -> a | B\nB -> b").unwrap(),
            p_check,
            "Parsed production rules are not those expected"
        );
    }

    #[test]
    fn from_string_error() {
        let error = TokenizerError::ProductionNoRhs("S".to_string());
        let result = Production::from_string("S ->\n -> a | B\nB -> b");

        assert!(
            result.is_err(),
            "Production from string on test input should return error"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            ProductionError::FormatError(error),
            "Creation of productions from test input returned the wrong error"
        );
    }

    #[test]
    fn from_iter() {
        let p_check = vec![
            Production {
                lhs: vec![symbol("S")],
                rhs: vec![symbol("A"), symbol("B")],
            },
            Production {
                lhs: vec![symbol("A")],
                rhs: vec![symbol("a")],
            },
            Production {
                lhs: vec![symbol("B")],
                rhs: vec![symbol("a")],
            },
            Production {
                lhs: vec![symbol("B")],
                rhs: vec![symbol("b")],
            },
        ];

        assert_eq!(
            super::productions("S -> A B\nA -> a\nB -> a | b"),
            p_check,
            "Created production rules are not those expected"
        );
    }

    #[test]
    fn such_that() {
        let filter = Production::such_that(ProductionPredicate::LhsEquals(vec![symbol("T")]));
        let productions = Production::from_string("S -> A | B\nA -> a\nT -> t\nB -> B").unwrap();

        let productions_iter = productions.clone();
        let mut filtered = productions_iter.iter().filter(filter);

        assert_eq!(
            filtered.next(),
            productions.get(3),
            "Filtered productions on test input should return the T -> t production"
        );
        assert_eq!(
            filtered.next(),
            None,
            "Filtered productions on test input should return no more productions"
        );
    }

    #[test]
    fn new() {
        let p_check = Production {
            lhs: vec![symbol("S")],
            rhs: vec![symbol("A"), symbol("B")],
        };

        assert_eq!(
            Production::new(p_check.lhs(), p_check.rhs()).unwrap(),
            p_check,
            "Created production rule is not the one expected"
        );
    }

    #[test]
    fn new_empty_side_lhs() {
        let iter = vec![symbol("S")];

        let result = Production::new(vec![], iter);
        assert!(
            result.is_err(),
            "Creation of production rule should return an error"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            ProductionError::NoLhs,
            "Creation of production rule returned the wrong error"
        );
    }

    #[test]
    fn new_empty_side_rhs() {
        let iter = vec![symbol("S")];

        let result = Production::new(iter, vec![]);
        assert!(
            result.is_err(),
            "Creation of production rule should return an error"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            ProductionError::NoRhs,
            "Creation of production rule returned the wrong error"
        );
    }

    #[test]
    fn new_from_string() {
        let p_check = Production {
            lhs: vec![symbol("S")],
            rhs: vec![symbol("A"), symbol("B")],
        };

        assert_eq!(
            Production::new_from_string(vec!["S"], vec!["A", "B"]).unwrap(),
            p_check,
            "Created production rule is not the one expected"
        );
    }

    #[test]
    fn new_from_string_error_lhs() {
        let error = SymbolError::InvalidSymbol("\n".to_string());
        let result = Production::new_from_string(vec!["\n"], vec!["A", "B"]);

        assert!(
            result.is_err(),
            "Created production rule should return error"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            ProductionError::SymbolError(error),
            "Creation of production rule returned the wrong error"
        );
    }

    #[test]
    fn new_from_string_error_rhs() {
        let error = SymbolError::InvalidSymbol("\n".to_string());
        let result = Production::new_from_string(vec!["S"], vec!["\n"]);

        assert!(
            result.is_err(),
            "Created production rule should return error"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            ProductionError::SymbolError(error),
            "Creation of production rule returned the wrong error"
        );
    }

    #[test]
    fn production_display() {
        let mut buf = String::new();
        let p = super::production("A", "B C");

        let result = write!(buf, "{}", p);
        assert!(result.is_ok());
        assert_eq!(buf, "A -> B C")
    }

    #[test]
    fn production_try_from() {
        let result = Production::try_from("A -> B");
        assert!(result.is_ok());
    }

    #[test]
    fn production_try_from_multiple() {
        let string = "A -> B\nA -> C";
        let result = Production::try_from(string);
        assert!(result.is_err());
        let e = result.unwrap_err();
        assert_eq!(
            e,
            ProductionError::FormatError(TokenizerError::ProductionMultiple(string.to_string()))
        );
    }

    #[test]
    fn production_try_from_error() {
        let string = "A -> B -> C";
        let result = Production::try_from(string);
        assert!(result.is_err());
        let e = result.unwrap_err();
        assert_eq!(
            e,
            ProductionError::FormatError(TokenizerError::ProductionMultipleOneLine(0))
        );
    }

    #[test]
    fn production_try_from_no_productions() {
        let result = Production::try_from("");
        assert!(result.is_err());
        let e = result.unwrap_err();
        assert_eq!(
            e,
            ProductionError::FormatError(TokenizerError::ProductionEmpty("".to_string()))
        );
    }

    // enum.ProductionError

    #[test]
    fn production_error_display_no_lhs() {
        let mut buf = String::new();

        let result = write!(buf, "{}", ProductionError::NoLhs);
        assert!(result.is_ok());
        assert_eq!(buf, "ProductionError: no lhs in production")
    }

    #[test]
    fn production_error_display_no_rhs() {
        let mut buf = String::new();

        let result = write!(buf, "{}", ProductionError::NoRhs);
        assert!(result.is_ok());
        assert_eq!(buf, "ProductionError: no rhs in production")
    }

    #[test]
    fn production_error_display_symbol_error() {
        let mut buf = String::new();
        let error = SymbolError::EmptySymbol;

        let result = write!(buf, "{}", ProductionError::SymbolError(error.clone()));
        assert!(result.is_ok());
        assert_eq!(
            buf,
            format!("ProductionError: symbol error encountered = {}", error)
        )
    }

    #[test]
    fn production_error_display_format_error() {
        let mut buf = String::new();
        let error = TokenizerError::ProductionNoLhs;

        let result = write!(buf, "{}", ProductionError::FormatError(error.clone()));
        assert!(result.is_ok());
        assert_eq!(
            buf,
            format!(
                "ProductionError: bad formatted string encountered, error = {}",
                error
            )
        )
    }

    #[test]
    fn production_error_source() {
        assert!(
            ProductionError::FormatError(TokenizerError::ProductionNoLhs)
                .source()
                .is_some()
        );
        assert!(ProductionError::SymbolError(SymbolError::EmptySymbol)
            .source()
            .is_some());
    }

    #[test]
    fn production_error_source_none() {
        assert!(ProductionError::NoLhs.source().is_none());
        assert!(ProductionError::NoRhs.source().is_none());
    }

    // enum.ProductionPredicate

    #[test]
    fn predicate_lhs_equals() {
        let predicate = ProductionPredicate::LhsEquals(vec![symbol("T")]);

        assert!(
            predicate.test(&Production {
                lhs: vec![symbol("T")],
                rhs: vec![]
            }),
            "Predicate should return true"
        );
        assert!(
            !predicate.test(&Production {
                lhs: vec![symbol("F")],
                rhs: vec![]
            }),
            "Predicate should return false"
        );
    }

    #[test]
    fn predicate_rhs_equals() {
        let predicate = ProductionPredicate::RhsEquals(vec![symbol("T")]);

        assert!(
            predicate.test(&Production {
                lhs: vec![],
                rhs: vec![symbol("T")]
            }),
            "Predicate should return true"
        );
        assert!(
            !predicate.test(&Production {
                lhs: vec![],
                rhs: vec![symbol("F")]
            }),
            "Predicate should return false"
        );
    }

    #[test]
    fn predicate_rhs_length_equals() {
        let predicate = ProductionPredicate::RhsLengthEquals(2);

        assert!(
            predicate.test(&Production {
                lhs: vec![],
                rhs: vec![symbol("T1"), symbol("T2")]
            }),
            "Predicate should return true"
        );
        assert!(
            !predicate.test(&Production {
                lhs: vec![],
                rhs: vec![symbol("F")]
            }),
            "Predicate should return false"
        );
    }

    #[test]
    fn predicate_rhs_is_suffix_of() {
        let predicate = ProductionPredicate::RhsIsSuffixOf(vec![symbol("T2"), symbol("T3")]);

        assert!(
            predicate.test(&Production {
                lhs: vec![],
                rhs: vec![symbol("T1"), symbol("T2"), symbol("T3")]
            }),
            "Predicate should return true"
        );
        assert!(
            !predicate.test(&Production {
                lhs: vec![],
                rhs: vec![symbol("F")]
            }),
            "Predicate should return false"
        );
    }

    #[test]
    fn production_predicate_display_lhs_equals() {
        let mut buf = String::new();

        let result = write!(
            buf,
            "{}",
            ProductionPredicate::LhsEquals(vec![symbol("A"), symbol("B")])
        );
        assert!(result.is_ok());
        assert_eq!(buf, format!("ProductionPredicate: lhs == {}", "A B"))
    }

    #[test]
    fn production_predicate_display_rhs_equals() {
        let mut buf = String::new();

        let result = write!(
            buf,
            "{}",
            ProductionPredicate::RhsEquals(vec![symbol("A"), symbol("B")])
        );
        assert!(result.is_ok());
        assert_eq!(buf, format!("ProductionPredicate: rhs == {}", "A B"))
    }

    #[test]
    fn production_predicate_display_rhs_is_suffix_of() {
        let mut buf = String::new();

        let result = write!(
            buf,
            "{}",
            ProductionPredicate::RhsIsSuffixOf(vec![symbol("A"), symbol("B")])
        );
        assert!(result.is_ok());
        assert_eq!(buf, format!("ProductionPredicate: rhs suffix == {}", "A B"))
    }

    #[test]
    fn production_predicate_display_rhs_length_equals() {
        let mut buf = String::new();

        let result = write!(buf, "{}", ProductionPredicate::RhsLengthEquals(2));
        assert!(result.is_ok());
        assert_eq!(buf, format!("ProductionPredicate: rhs length == {}", 2))
    }

    // mod.production

    #[test]
    fn production() {
        let p_check = Production {
            lhs: vec![symbol("S")],
            rhs: vec![symbol("A"), symbol("B")],
        };

        assert_eq!(
            super::production("S", "A B"),
            p_check,
            "Created production rule is not the one expected"
        );
    }

    #[test]
    fn productions() {
        let p_check = vec![
            Production {
                lhs: vec![symbol("S")],
                rhs: vec![symbol("A"), symbol("B")],
            },
            Production {
                lhs: vec![symbol("A")],
                rhs: vec![symbol("a")],
            },
        ];

        assert_eq!(
            super::productions("S -> A B\nA -> a"),
            p_check,
            "Created production rules are not those expected"
        );
    }

    #[test]
    fn production_table() {
        let p = super::productions(
            "
            A -> B C
            B -> b
        ",
        );
        let result = super::production_table(p);

        assert_eq!(result, "0: A -> B C\n1: B -> b");
    }
}