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
//! Module for handling all derivation related operations.
//!
//! Its goal is to emulate derivation on grammars.
//!
//! It defines a `Derivation` type which can be used to conveniently work with grammar and derive them in many ways.

use crate::grammar::Grammar;
use crate::production::Production;
use crate::symbol::{sentential_form, Symbol};
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fmt;

#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum DerivationError {
    /// Error for when the derivation tries to apply a production whose index is not in the valid ones for the grammar.
    ///
    /// # Examples
    /// If you have a grammar with 3 productions, then the indexes of those productions will be [0..2]. If you specify 3 or more as
    /// production index, you'll get this error.
    WrongProductionIndex(usize),
    /// Error for when the derivation tries to apply a production to the indexed symbol in the current sentential form
    /// but the latter doesn't have enough symbols to reach the indexed one.
    ///
    /// # Examples
    /// If you have a sentential form like this `A B C` (which has 3 symbols, so the indexes of those symbols in the sentential
    /// form are 0 for the `A`, 1 for the `B` and 2 for the `C`) and try to apply a production rule to an index >= 3,
    /// then you'll get this error.
    WrongIndex(Vec<Symbol>, usize),
    /// Error for when the derivation tries to apply a production on part of the sentential form, but the production can't be applied
    /// due to the left hand side not matching the part of the sentential form the production is being applied to.
    ///
    /// # Examples
    /// If you have a derivation step which target the production `A -> B` and the index 0 of the sentential form,
    /// which contains `C A B`, the left hand side of the production (`A`) doesn't match the sentential form starting from
    /// 0 (`C`), so the derivation step can't be applied and you'll get this error.
    ImpossibleStep(Production, Vec<Symbol>, DerivationStep),
    /// Error for when the derivation tries to apply a [leftmost_n](struct.Derivation.html#method.leftmost_n) or
    /// [rightmost_n](struct.Derivation.html#method.rightmost_n) derivation to a sentential form which doesn't have a non terminal symbol,
    /// so the derivation step can't be applied, because there's no sentential form index to derive from.
    ///
    /// # Examples
    /// If you have the derivation step which target the production `A -> B` and the current sentential form is `a` (it doesn't have any non
    /// terminal symbols), you'll get this error.
    NoNSymbol(Vec<Symbol>),
}

impl fmt::Display for DerivationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DerivationError::WrongProductionIndex(p_index) => write!(
                f,
                "Wrong production index: can't find production with index {}° in the grammar",
                p_index
            ),
            DerivationError::WrongIndex(sf, index) => write!(
                f,
                "Wrong step index: can't find index {}° of sentential form \"{:?}\"",
                index, sf
            ),
            DerivationError::ImpossibleStep(p, sf, step) => write!(
                f,
                "Impossible step: can't apply {}° production \"{}\" to {}° symbol of sentential form \"{:?}\"",
                step.p_index, p, step.index, sf
            ),
            DerivationError::NoNSymbol(sf) => write!(
                f,
                "Impossible step: can't find a non terminal symbol to start the derivation from, within the sentential form \"{:?}\"",
                sf
            ),
        }
    }
}

impl Error for DerivationError {}

/// A useful abstraction over derivation steps.
///
/// It contains two information:
/// - p_index, the production index, needed to retrieve the correct production from the grammar
/// - index, the index of the first symbol of the sentential form from which apply the derivation step
///
/// # Examples
/// If you have a grammar based on the productions:
/// - `A -> B C`
/// - `B -> b`
///
/// you can create a derivation on that grammar, based on the default sentential form which is `A`
/// (it matches the grammar start symbol initially), then apply a derivation step based on:
/// - p_index = 0, so the 0° (first) production rule of the grammar will be used (`A -> B C`)
/// - index = 0, so the 0° (first) symbol of the current sentential form (`A`) which is `A`
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct DerivationStep {
    pub p_index: usize,
    pub index: usize,
}

impl fmt::Display for DerivationStep {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.p_index, self.index)
    }
}

/// The main type of this module.
///
/// It allows derivations on a specified grammar. Every derivation step modify the current derivation state.
/// A derivation can be created from scratch with the initial sentential form based on the grammar start symbol or a
/// custom sentential form can be used to initialize the derivation from there (in the latter case, no previous steps are automatically
/// calculated, so the history can't be reproduced using the derivation).
///
/// At any time, you can query the sentential form and the applied steps of the derivation.
///
/// For more information about derivation steps, check out their [documentation](struct.DerivationStep.html).
///
/// # Notice
/// A derivation needs to borrow a grammar, in order for it to work even if the grammar is then left. So if the original grammar is then modified,
/// it doesn't affect the derivation of the original one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Derivation {
    g: Grammar,
    steps: Vec<DerivationStep>,
    sentential_forms: Vec<Vec<Symbol>>,
}

impl fmt::Display for Derivation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.sentential_forms
                .iter()
                .map(|x: &Vec<Symbol>| { sentential_form(x.clone()) })
                .collect::<Vec<String>>()
                .join(" -> ")
        )
    }
}

impl Derivation {
    /// Return a new derivation based on the given grammar.
    /// The initial sentential form is supposed to be the start symbol of the grammar.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// assert_eq!(d.sentential_form(), vec![symbol("A")]);
    /// ```
    pub fn new(g: Grammar) -> Derivation {
        let from = vec![g.s()];
        Derivation::new_from(g, from)
    }

    /// Return a new derivation based on the given grammar.
    /// The initial sentential form is the collection of symbols passed as input, ordered as it's passed.
    ///
    /// # Notice
    /// It allows you to create derivation based on sentential forms with any symbols, even the ones not in the grammar.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new_from(g, vec![symbol("Custom")]);
    ///
    /// assert_eq!(d.sentential_form(), vec![symbol("Custom")]);
    /// ```
    pub fn new_from<I>(g: Grammar, sentential_form: I) -> Derivation
    where
        I: IntoIterator<Item = Symbol>,
    {
        Derivation {
            g: g,
            steps: Vec::new(),
            sentential_forms: vec![sentential_form.into_iter().collect()],
        }
    }

    /// Return the steps done from the derivation until now.
    ///
    /// Return an empy collection if no steps have been done.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// assert!(d.steps().is_empty());
    /// ```
    pub fn steps(&self) -> Vec<DerivationStep> {
        self.steps.clone()
    }

    /// Return the current sentential form of the derivation, that is, the sentential form obtained
    /// by applying the derivation steps on the initial sentential form of the derivation.
    ///
    /// Return the initial sentential form if no steps have been done.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// assert_eq!(d.sentential_form(), vec![symbol("A")]);
    /// ```
    pub fn sentential_form(&self) -> Vec<Symbol> {
        if let Some(last) = self.sentential_forms.last() {
            last.clone()
        } else {
            unreachable!()
        }
    }

    /// Apply the given step (production index and sentential form index) to the derivation.
    /// Return the modified derivation for writing things like `d.step(0,0).step(1,2)` etc.
    ///
    /// Return the initial sentential form if no steps have been done.
    ///
    /// # Errors
    /// For more info about the errors returned, check the [DerivationError](enum.DerivationError.html) documentation.
    /// - [WrongProductionIndex](enum.DerivationError.html#variant.WrongProductionIndex) error if the production index targets a nonexistent grammar production
    /// - [WrongIndex](enum.DerivationError.html#variant.WrongIndex) error if the index target an impossible index of the current derivation sentential form
    /// - [ImpossibleStep](enum.DerivationError.html#variant.ImpossibleStep) error if the step to be applied can't be applied to the current derivation sentential form
    /// (but the steps indexes were correct)
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// assert_eq!(d.sentential_form(), vec![symbol("A")]);
    /// ```
    pub fn step(mut self, p_index: usize, index: usize) -> Result<Derivation, DerivationError> {
        let step = DerivationStep { p_index, index };
        let p: Production = self
            .g
            .p()
            .get(p_index)
            .ok_or(DerivationError::WrongProductionIndex(p_index))?
            .clone();
        let mut sf: Vec<Symbol> = self.sentential_form();
        if sf.len() <= step.index {
            return Err(DerivationError::WrongIndex(sf, step.index));
        }
        let mut lhs: Vec<Symbol> = sf.split_off(step.index);

        if lhs.starts_with(&p.lhs()) {
            let mut rhs = p.rhs().into_iter().filter(|s| !s.is_epsilon()).collect();
            let mut remaining = lhs.split_off(p.lhs().len());
            sf.append(&mut rhs);
            sf.append(&mut remaining);
            self.steps.push(step);
            self.sentential_forms.push(sf);
        } else {
            return Err(DerivationError::ImpossibleStep(
                p.clone(),
                self.sentential_form(),
                step,
            ));
        }

        Ok(self)
    }

    /// Apply the given ordered collection of steps.
    ///
    /// It works just like the [step](#method.step) method, but it receives a collection of steps instead of a single one.
    /// For clarity reason, a colleciton of formal [DerivationStep](struct.DerivationStep.html)s is required here.
    ///
    /// # Errors
    /// Return an error if any of the given steps return an error when applied.
    /// For more info about the errors returned, check the [DerivationError](enum.DerivationError.html) documentation.
    /// - [WrongProductionIndex](enum.DerivationError.html#variant.WrongProductionIndex) error if the production index target a nonexistent grammar production
    /// - [WrongIndex](enum.DerivationError.html#variant.WrongIndex) error if the index target an impossible index of the current derivation sentential form
    /// - [ImpossibleStep](enum.DerivationError.html#variant.ImpossibleStep) error if the step to be applied can't be applied to the current derivation sentential form
    /// (but the steps indexes were correct)
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// assert_eq!(d.sentential_form(), vec![symbol("A")]);
    /// ```
    pub fn step_from_iter<I>(self, steps: I) -> Result<Derivation, DerivationError>
    where
        I: IntoIterator<Item = DerivationStep>,
    {
        let mut d = self;
        for step in steps {
            d = d.step(step.p_index, step.index)?;
        }

        Ok(d)
    }

    /// Apply a step on the leftmost symbol of the current sentential form, using the production
    /// specified as input with the production index.
    ///
    /// It works just like the [step](#method.step) method, using the index of
    /// the first non terminal symbol within the current sentential form as the sentential form symbol index.
    ///
    /// # Errors
    /// Return an error according to the [step](#method.step) method.
    ///
    /// Moreover, it can return a [NoNSymbol](enum.DerivationError.html#variant.NoNSymbol) error if there are no non terminal symbols in the current
    /// sentential form
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// assert!(d.leftmost(0).is_ok()); // applied "A -> a" on "A"
    /// ```
    pub fn leftmost(self, p_index: usize) -> Result<Derivation, DerivationError> {
        let sf = self.sentential_form();
        for (index, symbol) in sf.iter().enumerate() {
            if symbol.is_non_terminal() {
                return self.step(p_index, index);
            }
        }

        Err(DerivationError::NoNSymbol(sf))
    }

    /// Repeated [leftmost](#method.leftmost) for each production index in an ordered collection of productions passed as input
    pub fn leftmost_from_iter<I>(self, p_indexes: I) -> Result<Derivation, DerivationError>
    where
        I: IntoIterator<Item = usize>,
    {
        let mut d = self;
        for p_index in p_indexes {
            d = d.leftmost(p_index)?;
        }

        Ok(d)
    }

    /// Apply a step on the rightmost symbol of the current sentential form, using the production
    /// specified as input with the production index.
    ///
    /// It works just like the [step](#method.step) method, using as the index of the sentential
    /// form symbol to derive from the index of rightmost non terminal symbol within the sentential form
    ///
    /// # Errors
    /// Return an error according to the [step](#method.step) method.
    ///
    /// Moreover, it can return a [NoNSymbol](enum.DerivationError.html#variant.NoNSymbol) error if there are no non terminal symbols in the current
    /// sentential form.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// assert!(d.rightmost(0).is_ok()); // applied "A -> a" on "A"
    /// ```
    pub fn rightmost(self, p_index: usize) -> Result<Derivation, DerivationError> {
        let sf = self.sentential_form();
        let len = sf.len();
        for (index, symbol) in sf.iter().rev().enumerate() {
            if symbol.is_non_terminal() {
                return self.step(p_index, (len - 1) - index);
            }
        }

        Err(DerivationError::NoNSymbol(sf))
    }

    /// Repeated [rightmost](#method.rightmost) for each production index in an ordered collection of productions passed as input
    pub fn rightmost_from_iter<I>(self, p_indexes: I) -> Result<Derivation, DerivationError>
    where
        I: IntoIterator<Item = usize>,
    {
        let mut d = self;
        for p_index in p_indexes {
            d = d.rightmost(p_index)?;
        }

        Ok(d)
    }

    /// Check if a given step is appliable to the current sentential form.
    ///
    /// Return `true` if the given step is appliable, `false` otherwise.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// // check if step "A -> a" on "A" is appliable
    /// assert!(d.is_possible_step(0,0));
    /// ```
    pub fn is_possible_step(self, p_index: usize, index: usize) -> bool {
        Derivation::new_from(self.g.clone(), self.sentential_form())
            .step(p_index, index)
            .is_ok()
    }

    /// Return a collection of steps, representing the possible steps from the current derivation state,
    /// based on trying to derive using the production whose production index is given as argument
    /// with each possible sentential form symbol index.
    ///
    /// Can return an empty collection if no steps are possible.
    ///
    /// # Errors
    /// Return a [WrongProductionIndex](enum.DerivationError.html#variant.WrongProductionIndex) error if the production
    /// index targets a nonexistent grammar production
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// // get all possible steps for applying "A -> a"
    /// // on the current sentential form (which is only 1),
    /// // the step (0,0)
    /// let possible_steps = d.possible_steps_by_prod(0)?;
    /// assert_eq!(possible_steps.len(), 1);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn possible_steps_by_prod(
        self,
        p_index: usize,
    ) -> Result<Vec<DerivationStep>, DerivationError> {
        let sf = self.sentential_form();
        let sf_len = self.sentential_form().len();
        let lhs: Vec<Symbol> = self
            .g
            .p()
            .get(p_index)
            .ok_or(DerivationError::WrongProductionIndex(p_index))?
            .lhs();
        let mut steps: Vec<DerivationStep> = Vec::new();

        for i in 0..sf_len {
            if sf[i..sf_len] == lhs[0..lhs.len()] {
                steps.push(DerivationStep {
                    p_index: p_index,
                    index: i,
                });
            }
        }

        Ok(steps)
    }

    /// Return a collection of steps, representing the possible steps from the current derivation state,
    /// based on trying to derive using the sentential form symbol index given as argument
    /// with each possible production of the grammar.
    ///
    /// Can return an empty collection if no steps are possible.
    ///
    /// # Errors
    /// Return a [WrongIndex](enum.DerivationError.html#variant.WrongIndex) error if the sentential form symbol
    /// index is not in range of the sentential form symbol indexes.
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::derivation::Derivation;
    /// use liblet::grammar::grammar;
    /// use liblet::symbol::symbol;
    ///
    /// let g = grammar("A -> a");
    /// let d = Derivation::new(g);
    ///
    /// // get all possible steps starting from the 0°
    /// // symbol of the sentential form ("A"), which is
    /// // only 1, the step (0,0)
    /// let possible_steps = d.possible_steps_by_index(0)?;
    /// assert_eq!(possible_steps.len(), 1);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn possible_steps_by_index(
        self,
        index: usize,
    ) -> Result<Vec<DerivationStep>, DerivationError> {
        let sf = self.sentential_form();
        let sf_len = self.sentential_form().len();
        let mut steps: Vec<DerivationStep> = Vec::new();

        if sf_len <= index {
            return Err(DerivationError::WrongIndex(sf, index));
        }

        for (i, p) in self.g.p().iter().enumerate() {
            let lhs = p.lhs();
            if sf[index..sf_len] == lhs[0..lhs.len()] {
                steps.push(DerivationStep {
                    p_index: i,
                    index: index,
                });
            }
        }

        Ok(steps)
    }
}

/// Convenience function for creating a derivation from a grammar.
///
/// # Examples
/// ```rust
/// use liblet::derivation::derivation;
/// use liblet::grammar::grammar;
/// use liblet::symbol::symbol;
///
/// let g = grammar("A -> a");
/// let d = derivation(g);
///
/// assert_eq!(d.sentential_form(), vec![symbol("A")]);
/// ```
pub fn derivation(g: Grammar) -> Derivation {
    Derivation::new(g)
}

/// Convenience function for creating a step from a production index and a
/// sentential form symbol index.
///
/// # Examples
/// ```rust
/// use liblet::derivation::step;
/// use liblet::symbol::symbol;
///
/// let s = step(0,0);
///
/// assert_eq!(s.p_index, 0);
/// assert_eq!(s.index, 0);
/// ```
pub fn step(p_index: usize, index: usize) -> DerivationStep {
    DerivationStep {
        p_index: p_index,
        index: index,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::grammar::grammar;
    use crate::production::production;
    use crate::symbol::symbol;
    use std::fmt::Write;

    // struct.Derivation

    #[test]
    fn new() {
        let g = grammar("S -> A | B");
        let d = Derivation::new(g.clone());

        assert_eq!(d.g, g);
        assert_eq!(d.steps(), Vec::new());
        assert_eq!(d.sentential_form(), vec![symbol("S")]);
    }

    #[test]
    fn new_from() {
        let g = grammar("S -> A | B\nA -> a");
        let d = Derivation::new_from(g.clone(), vec![symbol("A")]);

        assert_eq!(d.g, g);
        assert_eq!(d.steps(), Vec::new());
        assert_eq!(d.sentential_form(), vec![symbol("A")]);
    }

    #[test]
    fn derivation() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());

        assert_eq!(d.g, g);
        assert_eq!(d.steps(), Vec::new());
        assert_eq!(d.sentential_form(), vec![symbol("S")]);
    }

    #[test]
    fn sentential_form_before_steps() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());

        assert_eq!(d.sentential_form(), vec![symbol("S")]);
    }

    #[test]
    fn step() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());
        let step = DerivationStep {
            p_index: 0,
            index: 0,
        };
        let result = d.step(step.p_index, step.index);
        assert!(
            result.is_ok(),
            "Step on derivation should not return an error"
        );
        let d = result.unwrap();

        assert_eq!(d.steps(), vec![step]);
        assert_eq!(d.sentential_form(), vec![symbol("A")]);
        assert_eq!(d.sentential_forms.len(), 2);
        assert_eq!(d.sentential_forms[0], vec![symbol("S")]);
        assert_eq!(d.sentential_forms[1], vec![symbol("A")]);
    }

    #[test]
    fn step_epsilon() {
        let g = grammar("S -> A | ε");
        let d = super::derivation(g.clone());
        let step = DerivationStep {
            p_index: 1,
            index: 0,
        };
        let result = d.step(step.p_index, step.index);
        assert!(
            result.is_ok(),
            "Step on derivation should not return an error"
        );
        let d = result.unwrap();

        assert_eq!(d.steps(), vec![step]);
        assert_eq!(d.sentential_form(), vec![]);
        assert_eq!(d.sentential_forms.len(), 2);
        assert_eq!(d.sentential_forms[0], vec![symbol("S")]);
        assert_eq!(d.sentential_forms[1], vec![]);
    }

    #[test]
    fn step_wrong_production_index() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());
        let step = DerivationStep {
            p_index: 2,
            index: 0,
        };

        let result = d.step(step.p_index, step.index);
        assert!(result.is_err(), "Step on derivation should return an error");
        let e = result.unwrap_err();
        assert_eq!(
            e,
            DerivationError::WrongProductionIndex(step.p_index),
            "Step on derivation returned the wrong error"
        );
    }

    #[test]
    fn step_wrong_index() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());
        let sentential_form = vec![symbol("S")];
        let step = DerivationStep {
            p_index: 0,
            index: 1,
        };
        let result = d.step(step.p_index, step.index);
        assert!(result.is_err(), "Step on derivation should return an error");
        let e = result.unwrap_err();
        assert_eq!(
            e,
            DerivationError::WrongIndex(sentential_form, step.index),
            "Step on derivation returned the wrong error"
        );
    }

    #[test]
    fn step_impossible_step() {
        let g = grammar("S -> A | B\nA -> a");
        let d = super::derivation(g.clone());
        let sentential_form = vec![symbol("S")];
        let production = production("A", "a");
        let step = DerivationStep {
            p_index: 2,
            index: 0,
        };
        let result = d.step(step.p_index, step.index);
        assert!(result.is_err(), "Step on derivation should return an error");
        let e = result.unwrap_err();
        assert_eq!(
            e,
            DerivationError::ImpossibleStep(production, sentential_form, step),
            "Step on derivation returned the wrong error"
        );
    }

    #[test]
    fn step_from_iter() {
        let g = grammar("S -> A | B\nA -> a");
        let d = super::derivation(g.clone());
        let steps: Vec<DerivationStep> = vec![
            DerivationStep {
                p_index: 0,
                index: 0,
            },
            DerivationStep {
                p_index: 2,
                index: 0,
            },
        ];
        let result = d.step_from_iter(steps.clone());
        assert!(result.is_ok(), "Step from iter should not return an error");
        let d = result.unwrap();
        assert_eq!(d.steps(), steps);
        assert_eq!(d.sentential_form(), vec![symbol("a")]);
        assert_eq!(d.sentential_forms.len(), 3);
        assert_eq!(d.sentential_forms[0], vec![symbol("S")]);
        assert_eq!(d.sentential_forms[1], vec![symbol("A")]);
        assert_eq!(d.sentential_forms[2], vec![symbol("a")]);
    }

    #[test]
    fn leftmost() {
        let g = grammar("S -> A B | B C\nA -> a");
        let mut d = super::derivation(g.clone());
        let p_index = 2;
        let steps = vec![
            DerivationStep {
                p_index: 0,
                index: 0,
            },
            DerivationStep {
                p_index: p_index,
                index: 0,
            },
        ];
        d = d.step(0, 0).unwrap();
        let result = d.leftmost(p_index);
        assert!(
            result.is_ok(),
            "Leftmost derivation should not return an error"
        );
        let d = result.unwrap();
        assert_eq!(d.steps(), steps);
        assert_eq!(d.sentential_form(), vec![symbol("a"), symbol("B")]);
        assert_eq!(d.sentential_forms.len(), 3);
        assert_eq!(d.sentential_forms[0], vec![symbol("S")]);
        assert_eq!(d.sentential_forms[1], vec![symbol("A"), symbol("B")]);
        assert_eq!(d.sentential_forms[2], vec![symbol("a"), symbol("B")]);
    }

    #[test]
    fn leftmost_no_n_symbol() {
        let g = grammar("S -> a b | B C\nA -> a");
        let mut d = super::derivation(g);
        let p_index = 2;
        d = d.step(0, 0).unwrap();

        let result = d.leftmost(p_index);
        assert!(
            result.is_err(),
            "Leftmost derivation should return an error"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            DerivationError::NoNSymbol(vec![symbol("a"), symbol("b")]),
            "Leftmost derivation returned error is wrong"
        );
    }

    #[test]
    fn leftmost_from_iter() {
        let g = grammar("S -> A B | B C\nA -> B\n B -> b");
        let d = super::derivation(g.clone());
        let steps = vec![
            DerivationStep {
                p_index: 0,
                index: 0,
            },
            DerivationStep {
                p_index: 2,
                index: 0,
            },
            DerivationStep {
                p_index: 3,
                index: 0,
            },
        ];
        let result = d.leftmost_from_iter(steps.clone().iter().map(|x: &DerivationStep| x.p_index));
        assert!(
            result.is_ok(),
            "Leftmost steps on derivation should not return an error"
        );
        let d = result.unwrap();
        assert_eq!(d.steps(), steps);
        assert_eq!(d.sentential_form(), vec![symbol("b"), symbol("B")]);
        assert_eq!(d.sentential_forms.len(), 4);
        assert_eq!(d.sentential_forms[0], vec![symbol("S")]);
        assert_eq!(d.sentential_forms[1], vec![symbol("A"), symbol("B")]);
        assert_eq!(d.sentential_forms[2], vec![symbol("B"), symbol("B")]);
        assert_eq!(d.sentential_forms[3], vec![symbol("b"), symbol("B")]);
    }

    #[test]
    fn rightmost() {
        let g = grammar("S -> A B | B\nB -> b");
        let mut d = super::derivation(g.clone());
        let p_index = 2;
        let steps = vec![
            DerivationStep {
                p_index: 0,
                index: 0,
            },
            DerivationStep {
                p_index: p_index,
                index: 1,
            },
        ];
        d = d.step(0, 0).unwrap();

        let result = d.rightmost(p_index);
        assert!(
            result.is_ok(),
            "Rightmost step on derivation should not return an error"
        );
        let d = result.unwrap();
        assert_eq!(d.steps(), steps);
        assert_eq!(d.sentential_form(), vec![symbol("A"), symbol("b")]);
        assert_eq!(d.sentential_forms.len(), 3);
        assert_eq!(d.sentential_forms[0], vec![symbol("S")]);
        assert_eq!(d.sentential_forms[1], vec![symbol("A"), symbol("B")]);
        assert_eq!(d.sentential_forms[2], vec![symbol("A"), symbol("b")]);
    }

    #[test]
    fn rightmost_no_n_symbol() {
        let g = grammar("S -> a b | B C\nA -> a");
        let mut d = super::derivation(g);
        let p_index = 2;
        d = d.step(0, 0).unwrap();

        let result = d.rightmost(p_index);
        assert!(
            result.is_err(),
            "Rightmost derivation should return an error"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            DerivationError::NoNSymbol(vec![symbol("a"), symbol("b")]),
            "Rightmost derivation returned error is wrong"
        );
    }

    #[test]
    fn rightmost_from_iter() {
        let g = grammar("S -> A B | B\nB -> A\nA -> a");
        let d = super::derivation(g.clone());
        let steps = vec![
            DerivationStep {
                p_index: 0,
                index: 0,
            },
            DerivationStep {
                p_index: 2,
                index: 1,
            },
            DerivationStep {
                p_index: 3,
                index: 1,
            },
        ];

        let result =
            d.rightmost_from_iter(steps.clone().iter().map(|x: &DerivationStep| x.p_index));
        assert!(
            result.is_ok(),
            "Rightmost steps on derivation should not return an error"
        );
        let d = result.unwrap();
        assert_eq!(d.steps(), steps);
        assert_eq!(d.sentential_form(), vec![symbol("A"), symbol("a")]);
        assert_eq!(d.sentential_forms.len(), 4);
        assert_eq!(d.sentential_forms[0], vec![symbol("S")]);
        assert_eq!(d.sentential_forms[1], vec![symbol("A"), symbol("B")]);
        assert_eq!(d.sentential_forms[2], vec![symbol("A"), symbol("A")]);
        assert_eq!(d.sentential_forms[3], vec![symbol("A"), symbol("a")]);
    }

    #[test]
    fn is_possible_step_true() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());
        assert!(
            d.is_possible_step(0, 0),
            "Step on derivation should be possible"
        );
    }

    #[test]
    fn is_possible_step_false() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());
        assert!(
            !d.is_possible_step(0, 1),
            "Step on derivation should not be possible"
        );
    }

    #[test]
    fn possible_steps_by_prod() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());
        assert_eq!(
            d.possible_steps_by_prod(1).unwrap(),
            vec![super::step(1, 0)]
        );
    }

    #[test]
    fn possible_steps_by_index() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());
        assert_eq!(
            d.possible_steps_by_index(0).unwrap(),
            vec![super::step(0, 0), super::step(1, 0)]
        );
    }

    #[test]
    fn possible_steps_by_index_wrong_index() {
        let g = grammar("S -> A | B");
        let d = super::derivation(g.clone());
        let result = d.possible_steps_by_index(2);
        assert!(
            result.is_err(),
            "Possible steps by index from input test should return an error"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            DerivationError::WrongIndex(vec![symbol("S")], 2),
            "Possible steps by index from input test returned the wrong error"
        );
    }

    #[test]
    fn derivation_display() {
        let mut buf = String::new();
        let d = Derivation::new(grammar("A -> a b")).step(0, 0).unwrap();

        let result = write!(buf, "{}", d);
        assert!(result.is_ok());
        assert_eq!(buf, "A -> a b")
    }

    // enum.DerivationError

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

        let result = write!(buf, "{}", DerivationError::WrongProductionIndex(p_index));
        assert!(result.is_ok());
        assert_eq!(
            buf,
            format!(
                "Wrong production index: can't find production with index {}° in the grammar",
                p_index
            )
        )
    }

    #[test]
    fn derivation_error_display_wrong_index() {
        let mut buf = String::new();
        let index = 0;
        let sf = vec![symbol("A")];

        let result = write!(buf, "{}", DerivationError::WrongIndex(sf.clone(), index));
        assert!(result.is_ok());
        assert_eq!(
            buf,
            format!(
                "Wrong step index: can't find index {}° of sentential form \"{:?}\"",
                index, sf
            )
        )
    }

    #[test]
    fn derivation_error_display_impossible_step() {
        let mut buf = String::new();
        let p = production("A", "B");
        let step = super::step(0, 0);
        let sf = vec![symbol("A")];

        let result = write!(
            buf,
            "{}",
            DerivationError::ImpossibleStep(p.clone(), sf.clone(), step)
        );
        assert!(result.is_ok());
        assert_eq!(
            buf,
            format!(
                "Impossible step: can't apply {}° production \"{}\" to {}° symbol of sentential form \"{:?}\"",
                step.p_index, p, step.index, sf
            )
        )
    }

    #[test]
    fn derivation_error_display_no_n_symbol() {
        let mut buf = String::new();
        let sf = vec![symbol("A")];

        let result = write!(buf, "{}", DerivationError::NoNSymbol(sf.clone()));
        assert!(result.is_ok());
        assert_eq!(
            buf,
            format!(
                "Impossible step: can't find a non terminal symbol to start the derivation from, within the sentential form \"{:?}\"",
                sf
            )
        )
    }

    // struct.DerivationStep

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

        let result = write!(buf, "{}", super::step(1, 0));
        assert!(result.is_ok());
        assert_eq!(buf, "(1, 0)")
    }
}