summaryrefslogtreecommitdiff
path: root/grammar/src/lib.rs
blob: 4e544c9aa80bfe37ba9ee1c80e07c84856982d69 (plain)
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
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
#![warn(missing_docs)]
//! This file implements the extected behaviours of grammars.

// NOTE: We shall first start with a parser that works at the level of
// characters.  The purpose is to first experiment with the workings
// and the performance of the algorithms, before optimising by using
// regular expressions to classify inputs into tokens.  In other
// words, the current focus is not on the optimisations, whereas
// scanners are for optimisations only, so to speak.

// REVIEW: Separate contents into modules.

use nfa::{
    default::{
        nfa::DefaultNFA,
        regex::{DefaultRegex, ParseError, RegexType},
    },
    DOption, Nfa, Regex, SoC,
};

use graph::{adlist::ALGBuilder, builder::Builder, Graph};

use std::{collections::HashSet, fmt::Display};

/// The type of a terminal.
///
/// For the time being this is a wrapper around a string, but in the
/// future it may hold more information of scanners.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Terminal {
    // If we want to use scanners, per chance add them as a new field
    // here.
    name: String,
}

impl Terminal {
    /// Create a terminal with the given name.
    #[inline]
    pub fn new(name: String) -> Self {
        Self { name }
    }

    /// Return the name of the terminal.
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// The type of a non-terminal.
///
/// This is just a wrapper around a string.
#[derive(Debug, Clone)]
pub struct Nonterminal(String);

impl Nonterminal {
    /// Return the name of the nonterminal.
    ///
    /// Just to improve readability.
    #[inline]
    pub fn name(&self) -> &str {
        &self.0
    }
}

/// The type of a terminal or a non-terminal.
///
/// Only an index is stored here.  Actual data are stored in two other
/// arrays.
#[derive(Debug, Hash, Eq, PartialEq, Clone, Copy, Ord, PartialOrd)]
pub enum TNT {
    /// Terminal variant
    Ter(usize),
    /// Nonterminal variant
    Non(usize),
}

impl Display for TNT {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TNT::Ter(t) => write!(f, "T({t})"),
            TNT::Non(n) => write!(f, "N({n})"),
        }
    }
}

/// Errors related to grammar operations.
#[derive(Debug, Copy, Clone)]
#[non_exhaustive]
pub enum Error {
    /// The first component is the index, and the second the bound.
    IndexOutOfBounds(usize, usize),
    /// Fail to build the N-th regular expression, due to the
    /// ParseError.
    BuildFail(usize, ParseError),
    /// fail to build NFA
    NFAFail(nfa::error::Error),
}

impl From<nfa::error::Error> for Error {
    fn from(nfae: nfa::error::Error) -> Self {
        Self::NFAFail(nfae)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::IndexOutOfBounds(i, b) => write!(f, "index {i} out of bound {b}"),
            Error::BuildFail(n, pe) => write!(
                f,
                "Failed to build the {n}-th regular expression due to error: {pe}"
            ),
            Error::NFAFail(nfae) => write!(f, "failed to build NFA because of {nfae}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        if let Error::NFAFail(error) = self {
            Some(error)
        } else {
            None
        }
    }
}

/// A rule is a regular expression of terminals or non-terminals.
#[derive(Debug, Clone)]
pub struct Rule {
    regex: DefaultRegex<TNT>,
}

impl Rule {
    /// Return true if and only if the rule is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.regex.is_empty()
    }

    /// Return the length of the rule.
    #[inline]
    pub fn len(&self) -> usize {
        self.regex.len()
    }
}

/// The type of a grammar.
#[derive(Debug, Clone, Default)]
pub struct Grammar {
    /// A list of terminals.
    ter: Vec<Terminal>,
    /// A list of non-terminals.
    non: Vec<Nonterminal>,
    /// A list of rules.
    ///
    /// The length of the list must match that of the list of
    /// non-terminals.
    rules: Vec<Rule>,
    // The following two attributes are empty until we call
    // `compute_firsts` on the grammar.
    /// The list of sets of "first terminals".
    ///
    /// The length must match that of the list of non-terminals.
    firsts: Vec<HashSet<Option<usize>>>,
    /// The list of lists of nodes that are reachable after a nullable
    /// transition in the regular expression.
    ///
    /// The length must match that of the list of non-terminals.
    first_nodes: Vec<Vec<usize>>,
    // The following attribute is empty until we call `left_closure`
    // on the grammar.
    left_closure_branches: HashSet<usize>,
}

/// A private type to aid the recursive looping of rergular
/// expressions.
#[derive(Copy, Clone)]
enum StackElement {
    Seen(usize),
    Unseen(usize),
}

impl StackElement {
    fn index(self) -> usize {
        match self {
            Self::Seen(index) => index,
            Self::Unseen(index) => index,
        }
    }

    fn is_seen(self) -> bool {
        matches!(self, Self::Seen(_))
    }
}

impl Grammar {
    /// Construct a grammar from a vector of terminals, a vector of
    /// non-terminals, and a vector of rules for the non-temrinals.
    ///
    /// # Panic
    ///
    /// If the length of `non` is not equal to that of `rules`, then
    /// the function panics.
    pub fn new(ter: Vec<Terminal>, non: Vec<Nonterminal>, rules: Vec<Rule>) -> Self {
        assert_eq!(non.len(), rules.len());

        // One more room is reserved for the `None` value.
        let firsts = std::iter::repeat_with(|| HashSet::with_capacity(ter.len() + 1))
            .take(non.len())
            .collect();

        let first_nodes = rules
            .iter()
            .map(|rule| Vec::with_capacity(rule.len()))
            .collect();

        let left_closure_branches = HashSet::default();

        Self {
            ter,
            non,
            rules,
            firsts,
            first_nodes,
            left_closure_branches,
        }
    }

    /// Return the name of a terminal or a non-terminal.
    pub fn name_of_tnt(&self, tnt: TNT) -> Result<String, Error> {
        match tnt {
            TNT::Ter(t) => Ok(format!(
                "T{}",
                self.ter
                    .get(t)
                    .ok_or(Error::IndexOutOfBounds(t, self.ter.len()))?
                    .name()
            )),
            TNT::Non(n) => Ok(format!(
                "N{}",
                self.non
                    .get(n)
                    .ok_or(Error::IndexOutOfBounds(n, self.non.len()))?
                    .name()
            )),
        }
    }

    /// Return true if and only if there are no non-terminals in the
    /// grammar.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.non.is_empty()
    }

    /// Return the total length of all rules.
    #[inline]
    pub fn total(&self) -> usize {
        self.rules.iter().map(Rule::len).sum()
    }

    /// Return the number of terminals.
    #[inline]
    pub fn ter_num(&self) -> usize {
        self.ter.len()
    }

    /// Return the number of non-terminals.
    #[inline]
    pub fn non_num(&self) -> usize {
        self.non.len()
    }

    /// Convert a non-terminal `N` to `N + TER_NUM`, so that we use a
    /// single number to represent terminals and non-terminals.
    ///
    /// # Bounds
    ///
    /// If a terminal index is greater than or equal to the number of
    /// terminals, then this signals an error; mutatis mutandis for
    /// non-terminals.
    ///
    /// # Related
    ///
    /// The inverse function is [`unpack_tnt`][Grammar::unpack_tnt].
    #[inline]
    pub fn pack_tnt(&self, tnt: TNT) -> Result<usize, Error> {
        let ter_num = self.ter.len();
        let non_num = self.non.len();

        match tnt {
            TNT::Ter(t) => {
                if t >= ter_num {
                    Err(Error::IndexOutOfBounds(t, ter_num))
                } else {
                    Ok(t)
                }
            }
            TNT::Non(n) => {
                if n >= non_num {
                    Err(Error::IndexOutOfBounds(n, non_num))
                } else {
                    Ok(n + ter_num)
                }
            }
        }
    }

    /// Convert a single number to either a terminal or a
    /// non-terminal.
    ///
    /// # Bounds
    ///
    /// If the number is greater than or equal to the sum of the
    /// numbers of terminals and of non-terminals, then this signals
    /// an error.
    ///
    /// # Related
    ///
    /// This is the inverse of [`pack_tnt`][Grammar::pack_tnt].
    ///
    /// # Errors
    ///
    /// This function is supposed to return only one type of errors,
    /// namely, the IndexOutOfBounds error that results from a bounds
    /// check.  Breaking this is breaking the guarantee of this
    /// function, and is considered a bug.  This behaviour can and
    /// should be tested.  But I have not found a convenient test
    /// method for testing various grammars.
    #[inline]
    pub fn unpack_tnt(&self, flat: usize) -> Result<TNT, Error> {
        let ter_num = self.ter.len();
        let non_num = self.non.len();

        if flat < ter_num {
            Ok(TNT::Ter(flat))
        } else if flat < ter_num + non_num {
            Ok(TNT::Non(flat - ter_num))
        } else {
            Err(Error::IndexOutOfBounds(flat, ter_num + non_num))
        }
    }

    /// Return true if and only if the non-terminal is nullable.
    #[inline]
    pub fn is_nullable(&self, non_terminal: usize) -> Result<bool, Error> {
        Ok(self
            .firsts
            .get(non_terminal)
            .ok_or(Error::IndexOutOfBounds(non_terminal, self.non.len()))?
            .contains(&None))
    }

    /// For a NON_TERMINAL, return an iterator that goes over the
    /// nodes that are reachable from the non-terminal through an
    /// empty transition of the nondeterministic finite automaton.
    #[inline]
    pub fn first_nodes_of(&self, non_terminal: usize) -> Result<std::slice::Iter<usize>, Error> {
        Ok(self
            .first_nodes
            .get(non_terminal)
            .ok_or(Error::IndexOutOfBounds(non_terminal, self.non.len()))?
            .iter())
    }

    /// Return a hash set that contains all nodes in the set of
    /// left-closure regular languages that are added because of the
    /// left-linear expansion.
    pub fn left_closure_branches(&self) -> &HashSet<usize> {
        &self.left_closure_branches
    }

    /// Compute the set of terminals that can appear as the first
    /// terminal in some left-linear derivation of a non-terminal, for
    /// every non-terminal.
    ///
    /// This is an algorithm that computes the transitive closure,
    /// which is a common approach for this task.  But perhaps there
    /// are more efficient approaches?
    ///
    /// Also the function computes the set of "reachable nodes" in the
    /// process, and records the information in the `first_nodes`
    /// attribute.
    pub fn compute_firsts(&mut self) -> Result<(), Error> {
        let mut updated = true;

        let non_len = self.non_num();

        use StackElement::{Seen, Unseen};

        while updated {
            updated = false;

            for (n, regex) in self.rules.iter().map(|rule| &rule.regex).enumerate() {
                let root = if let Some(root) = regex.root() {
                    root
                } else {
                    if !self.is_nullable(n)? {
                        updated = true;

                        self.firsts.get_mut(n).unwrap().insert(None);

                        // The default construction of a grammar
                        // reserves some space for each vector, so
                        // explicitly setting this can reduce some
                        // minor memory overhead.
                        let pointer = self.first_nodes.get_mut(n).unwrap();

                        pointer.clear();
                        pointer.shrink_to_fit();
                    }

                    continue;
                };

                let regex_len = regex.len();

                let mut stack: Vec<StackElement> = Vec::with_capacity(regex_len);

                stack.push(Unseen(root));

                let mut children_sets_stack: Vec<HashSet<Option<usize>>> =
                    Vec::with_capacity(regex_len);

                let mut children_nodes_stack: Vec<HashSet<usize>> = Vec::with_capacity(regex_len);

                while let Some(top) = stack.pop() {
                    let top_index = top.index();
                    let is_seen = top.is_seen();

                    match regex
                        .vertex_label(top_index)
                        .map_err(|_| Error::IndexOutOfBounds(top_index, regex_len))?
                    {
                        RegexType::Kleene => {
                            if !is_seen {
                                stack.push(Seen(top_index));

                                for child in regex.children_of(top_index).unwrap() {
                                    stack.push(Unseen(child));
                                }
                            } else {
                                let degree = regex.degree(top_index).unwrap();
                                let children_stack_len = children_sets_stack.len();
                                let children_nodes_len = children_nodes_stack.len();

                                assert!(
                                    children_stack_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                assert!(
                                    children_nodes_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                let mut this_set = HashSet::new();

                                this_set.insert(None);

                                let mut this_nodes = HashSet::new();

                                this_nodes.insert(top_index);

                                if degree == 0 {
                                    children_sets_stack.push(this_set);
                                    children_nodes_stack.push(this_nodes);

                                    continue;
                                }

                                let mut stop = false;

                                for (child_set, child_nodes) in children_sets_stack
                                    .drain((children_stack_len - degree)..)
                                    .zip(
                                        children_nodes_stack.drain((children_nodes_len - degree)..),
                                    )
                                {
                                    if stop {
                                        break;
                                    }

                                    if !child_set.contains(&None) {
                                        stop = true;
                                    }

                                    this_set.extend(child_set);
                                    this_nodes.extend(child_nodes);
                                }

                                children_sets_stack.push(this_set);
                                children_nodes_stack.push(this_nodes);
                            }
                        }
                        RegexType::Plus => {
                            if !is_seen {
                                stack.push(Seen(top_index));

                                for child in regex.children_of(top_index).unwrap() {
                                    stack.push(Unseen(child));
                                }
                            } else {
                                let degree = regex.degree(top_index).unwrap();
                                let children_stack_len = children_sets_stack.len();
                                let children_nodes_len = children_nodes_stack.len();

                                assert!(
                                    children_stack_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                assert!(
                                    children_nodes_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                let mut this_set = HashSet::new();

                                let mut this_nodes = HashSet::new();

                                this_nodes.insert(top_index);

                                if degree == 0 {
                                    this_set.insert(None);

                                    children_sets_stack.push(this_set);
                                    children_nodes_stack.push(this_nodes);

                                    continue;
                                }

                                let mut stop = false;

                                for (child_set, child_nodes) in children_sets_stack
                                    .drain((children_stack_len - degree)..)
                                    .zip(
                                        children_nodes_stack.drain((children_nodes_len - degree)..),
                                    )
                                {
                                    if stop {
                                        break;
                                    }

                                    if !child_set.contains(&None) {
                                        stop = true;
                                    }

                                    this_set.extend(child_set);
                                    this_nodes.extend(child_nodes);
                                }

                                if stop {
                                    this_set.remove(&None);
                                }

                                children_sets_stack.push(this_set);
                                children_nodes_stack.push(this_nodes);
                            }
                        }
                        RegexType::Optional => {
                            if !is_seen {
                                stack.push(Seen(top_index));

                                for child in regex.children_of(top_index).unwrap() {
                                    stack.push(Unseen(child));
                                }
                            } else {
                                let degree = regex.degree(top_index).unwrap();
                                let children_stack_len = children_sets_stack.len();
                                let children_nodes_len = children_nodes_stack.len();

                                assert!(
                                    children_stack_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                assert!(
                                    children_nodes_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                let mut this_set = HashSet::new();

                                this_set.insert(None);

                                let mut this_nodes = HashSet::new();

                                this_nodes.insert(top_index);

                                if degree == 0 {
                                    children_sets_stack.push(this_set);
                                    children_nodes_stack.push(this_nodes);

                                    continue;
                                }

                                let mut stop = false;

                                for (child_set, child_nodes) in children_sets_stack
                                    .drain((children_stack_len - degree)..)
                                    .zip(
                                        children_nodes_stack.drain((children_nodes_len - degree)..),
                                    )
                                {
                                    if stop {
                                        break;
                                    }

                                    if !child_set.contains(&None) {
                                        stop = true;
                                    }

                                    this_set.extend(child_set.iter().copied());
                                    this_nodes.extend(child_nodes.iter().copied());
                                }

                                children_sets_stack.push(this_set);
                                children_nodes_stack.push(this_nodes);
                            }
                        }
                        RegexType::Or => {
                            if !is_seen {
                                stack.push(Seen(top_index));

                                for child in regex.children_of(top_index).unwrap() {
                                    stack.push(Unseen(child));
                                }
                            } else {
                                let degree = regex.degree(top_index).unwrap();
                                let children_stack_len = children_sets_stack.len();
                                let children_nodes_len = children_nodes_stack.len();

                                assert!(
                                    children_stack_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                assert!(
                                    children_nodes_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                let mut this_set = HashSet::new();

                                let mut this_nodes = HashSet::new();

                                this_nodes.insert(top_index);

                                if degree == 0 {
                                    this_set.insert(None);

                                    children_sets_stack.push(this_set);
                                    children_nodes_stack.push(this_nodes);

                                    continue;
                                }

                                for (child_set, child_nodes) in children_sets_stack
                                    .drain((children_stack_len - degree)..)
                                    .zip(
                                        children_nodes_stack.drain((children_nodes_len - degree)..),
                                    )
                                {
                                    this_set.extend(child_set.iter().copied());
                                    this_nodes.extend(child_nodes.iter().copied());
                                }

                                children_sets_stack.push(this_set);
                                children_nodes_stack.push(this_nodes);
                            }
                        }
                        RegexType::Paren => {
                            // Only for printing purposes
                            let mut this_set = HashSet::new();

                            this_set.insert(None);

                            children_sets_stack.push(this_set);

                            let mut this_nodes = HashSet::new();

                            this_nodes.insert(top_index);

                            children_nodes_stack.push(this_nodes);
                        }
                        RegexType::Empty => {
                            if !is_seen {
                                stack.push(Seen(top_index));

                                for child in regex.children_of(top_index).unwrap().rev() {
                                    stack.push(Unseen(child));
                                }
                            } else {
                                let degree = regex.degree(top_index).unwrap();
                                let children_stack_len = children_sets_stack.len();
                                let children_nodes_len = children_nodes_stack.len();

                                assert!(
                                    children_stack_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                assert!(
                                    children_nodes_len >= degree,
                                    "not enough stack elements for {top_index}"
                                );

                                let mut this_set = HashSet::new();

                                let mut this_nodes = HashSet::new();

                                this_nodes.insert(top_index);

                                if degree == 0 {
                                    this_set.insert(None);

                                    children_sets_stack.push(this_set);
                                    children_nodes_stack.push(this_nodes);

                                    continue;
                                }

                                let mut stop = false;

                                for (child_set, child_nodes) in children_sets_stack
                                    .drain((children_stack_len - degree)..)
                                    .zip(
                                        children_nodes_stack.drain((children_nodes_len - degree)..),
                                    )
                                {
                                    if stop {
                                        break;
                                    }

                                    if !child_set.contains(&None) {
                                        stop = true;
                                    }

                                    this_set.extend(child_set.iter().copied());
                                    this_nodes.extend(child_nodes.iter().copied());
                                }

                                if stop {
                                    this_set.remove(&None);
                                }

                                children_sets_stack.push(this_set);
                                children_nodes_stack.push(this_nodes);
                            }
                        }
                        RegexType::Lit(tnt) => {
                            match tnt {
                                TNT::Ter(t) => {
                                    let mut this_set = HashSet::with_capacity(1);

                                    this_set.insert(Some(t));

                                    children_sets_stack.push(this_set);
                                }
                                TNT::Non(non) => {
                                    let this_set = self
                                        .firsts
                                        .get(non)
                                        .ok_or(Error::IndexOutOfBounds(non, non_len))?
                                        .clone();

                                    children_sets_stack.push(this_set);
                                }
                            }

                            let mut this_nodes = HashSet::with_capacity(1);
                            this_nodes.insert(top_index);

                            children_nodes_stack.push(this_nodes);
                        }
                    }
                }

                assert_eq!(
                    children_sets_stack.len(),
                    1,
                    "Too many elements left at the end"
                );

                assert_eq!(
                    children_nodes_stack.len(),
                    1,
                    "Too many elements left at the end"
                );

                for first in children_sets_stack.pop().unwrap().into_iter() {
                    if !self.firsts.get(n).unwrap().contains(&first) {
                        updated = true;

                        self.firsts.get_mut(n).unwrap().insert(first);
                    }
                }

                *self.first_nodes.get_mut(n).unwrap() =
                    children_nodes_stack.pop().unwrap().into_iter().collect();
            }
        }

        Ok(())
    }

    /// Return the regular language of the left-linear closures of
    /// non-terminals in the grammar.
    ///
    /// The resulting vector is guaranteed to be of the same length as
    /// the number of non-terminals.
    ///
    /// The resulting regular language is not "self-contained".  That
    /// is to say, its terminals indices are packed indices and are
    /// meaningless without the interpretation of the grammar.  They
    /// should be converted to a nondeterministic finite automaton and
    /// then to its null closure later on.
    pub fn left_closure(&self) -> Result<Vec<DefaultRegex<TNT>>, Error> {
        let non_len = self.non_num();

        let mut result = Vec::with_capacity(non_len);

        for (n, rule) in self.rules.iter().enumerate() {
            let regex = &rule.regex;

            let regex_root = if let Some(root) = regex.root() {
                root
            } else {
                result.push(Default::default());

                continue;
            };

            let regex_len = regex.len();

            /// A convenient macro to retrieve the children from the
            /// original regular expression with error propagation.
            macro_rules! children {
                ($n:expr) => {
                    regex
                        .children_of($n)
                        .map_err(|_| Error::IndexOutOfBounds($n, regex_len))?
                };
            }

            /// A convenient macro to retrieve the label from the
            /// original regular expression with error propagation.
            macro_rules! label {
                ($n:expr) => {
                    regex
                        .vertex_label($n)
                        .map_err(|_| Error::IndexOutOfBounds($n, regex_len))?
                };
            }

            let parents = regex.parents_array().map_err(|e| match e {
                nfa::error::Error::UnknownNode(n) => Error::IndexOutOfBounds(n, regex_len),
                nfa::error::Error::Cycle => Error::BuildFail(n, ParseError::Cycle),
                _ => unreachable!(),
            })?;

            use RegexType::*;
            use TNT::*;

            let mut local_result: Vec<RegexType<TNT>> = Vec::with_capacity(regex_len * 2);
            let mut builder = ALGBuilder::default();

            /// Perform a depth-first copy
            macro_rules! df_copy {
                ($parent:expr, $index:expr) => {
                    match label!($index) {
                        Kleene | Plus | Optional | Or | Paren | Empty => {
                            let mut stack = vec![($parent, $index)];

                            while let Some((top_parent, top_index)) = stack.pop() {
                                let label = label!(top_index);
                                let label = match label {
                                    Lit(top_tnt) => Lit(Ter(self.pack_tnt(top_tnt).unwrap())),
                                    _ => label,
                                };

                                local_result.push(label);

                                let new = builder.add_vertex();

                                builder.add_edge(top_parent, new, ()).unwrap();

                                stack.extend(children!(top_index).map(|child| (new, child)));
                            }
                        }
                        Lit(remain_tnt) => {
                            local_result.push(Lit(Ter(self.pack_tnt(remain_tnt).unwrap())));
                            let new = builder.add_vertex();
                            builder.add_edge($parent, new, ()).unwrap();
                        }
                    }
                };
            }

            local_result.push(Or);
            builder.add_vertex();

            local_result.push(Lit(Ter(self.pack_tnt(Non(n)).unwrap())));
            let non_lit_index = builder.add_vertex();

            builder.add_edge(0, non_lit_index, ()).unwrap();

            // If this non-terminal is nullable, add an empty variant.
            if self.is_nullable(n)? {
                local_result.push(Empty);
                let empty_index = builder.add_vertex();
                builder.add_edge(0, empty_index, ()).unwrap();
            }

            for first_node in self.first_nodes_of(n)?.copied() {
                assert!(first_node < parents.len());

                let tnt = match label!(first_node) {
                    Lit(tnt) => Lit(tnt),
                    _ => continue,
                };

                let mut parents_chain = {
                    let mut result = Vec::new();
                    let mut stack = Vec::with_capacity(parents.len());

                    stack.push(first_node);

                    while let Some(top) = stack.pop() {
                        assert!(top < parents.len());
                        if let Some(parent) = parents.get(top).copied().unwrap() {
                            result.push(parent);
                            stack.push(parent.0);
                        }
                    }

                    result.reverse();

                    result
                };

                if parents_chain.is_empty() {
                    local_result.push(tnt);
                    let lit_index = builder.add_vertex();
                    builder.add_edge(0, lit_index, ()).unwrap();

                    continue;
                }

                assert_eq!(parents_chain.first().unwrap().0, regex_root);

                // A different, "more local", root.
                let mut local_root: usize;

                // Handle the direct parent
                let (parent_node, parent_edge_index) = parents_chain.pop().unwrap();

                match label!(parent_node) {
                    Kleene | Plus => {
                        // TODO: If parent_edge_index is 0, make a
                        // Plus node instead.
                        local_result.extend([Empty, tnt]);

                        local_root = builder.add_vertex();
                        let lit_index = builder.add_vertex();
                        builder.add_edge(local_root, lit_index, ()).unwrap();

                        let iterator = children!(parent_node);

                        for index in iterator.clone().skip(parent_edge_index + 1) {
                            df_copy!(local_root, index);
                        }

                        local_result.push(Kleene);
                        let new_parent = builder.add_vertex();
                        builder.add_edge(local_root, new_parent, ()).unwrap();

                        for index in iterator {
                            df_copy!(new_parent, index);
                        }
                    }

                    Or => {
                        local_result.push(tnt);
                        local_root = builder.add_vertex();
                    }
                    Optional | Empty => {
                        // If this path is taken, it should not be
                        // optional.
                        local_result.extend([Empty, tnt]);
                        local_root = builder.add_vertex();
                        let lit_index = builder.add_vertex();
                        builder.add_edge(local_root, lit_index, ()).unwrap();

                        for index in children!(parent_node).skip(parent_edge_index + 1) {
                            df_copy!(local_root, index);
                        }
                    }
                    Paren | Lit(_) => unreachable!(),
                }

                // Handle successive parents

                for (node, edge_index) in parents_chain.into_iter() {
                    let node_type = label!(node);

                    match node_type {
                        Kleene | Plus => {
                            // TODO: If edge_index is 0, then just
                            // make this a Plus node.

                            local_result.push(Empty);
                            let new_index = builder.add_vertex();
                            builder.add_edge(new_index, local_root, ()).unwrap();

                            local_root = new_index;

                            let iterator = children!(node);

                            for index in iterator.clone().skip(edge_index + 1) {
                                df_copy!(local_root, index);
                            }

                            local_result.push(Kleene);
                            let new_parent = builder.add_vertex();
                            builder.add_edge(local_root, new_parent, ()).unwrap();

                            for index in iterator {
                                df_copy!(new_parent, index);
                            }
                        }
                        RegexType::Or => {}
                        RegexType::Optional | RegexType::Empty => {
                            local_result.push(Empty);
                            let new_index = builder.add_vertex();
                            builder.add_edge(new_index, local_root, ()).unwrap();
                            local_root = new_index;

                            for index in children!(node).skip(edge_index + 1) {
                                df_copy!(local_root, index);
                            }
                        }
                        RegexType::Paren | RegexType::Lit(_) => unreachable!(),
                    }
                }

                builder.add_edge(0, local_root, ()).unwrap();
            }

            local_result.shrink_to_fit();

            let graph = builder.build();

            assert_eq!(graph.nodes_len(), local_result.len());

            result.push(
                DefaultRegex::new(graph, local_result)
                    .map_err(|_| Error::BuildFail(n, ParseError::Cycle))?,
            );
        }

        assert_eq!(result.len(), non_len);

        Ok(result)
    }

    /// Convert the regular language of left-linear closures to its
    /// equivalent nondeterministic finite automaton.
    ///
    /// In the generation of the left-linear closure, the terminals
    /// and non-terminals are packed into an unsigned integer.  We
    /// unpack them in converting to nondeterministic finite
    /// automaton.
    ///
    /// The resulting nondeterministic finite automaton should be
    /// transformed to its null-closure for use in our algorithm.
    pub fn left_closure_to_nfa(
        &self,
        closure: &[DefaultRegex<TNT>],
    ) -> Result<DefaultNFA<DOption<TNT>>, Error> {
        let label_transform = |tnt| match tnt {
            TNT::Ter(t) => {
                let new_tnt = self.unpack_tnt(t).map_err(|e| match e {
                    Error::IndexOutOfBounds(index, bound) => {
                        graph::error::Error::IndexOutOfBounds(index, bound)
                    }
                    _ => unreachable!(),
                })?;

                Ok(SoC::Carry(new_tnt))
            }
            TNT::Non(n) => Ok(SoC::Sub(n)),
        };

        let nfa = DefaultNFA::to_nfa(closure, label_transform, Some(TNT::Non(0)))?;

        Ok(nfa)
    }
}

impl Display for Grammar {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        assert_eq!(self.non.len(), self.rules.len());

        for (nt, rule) in self.non.iter().zip(self.rules.iter()) {
            write!(f, "{}: ", nt.name())?;

            writeln!(
                f,
                "{}",
                rule.regex.to_string_with(|tnt| format!(
                    "({})",
                    self.name_of_tnt(tnt)
                        .unwrap_or_else(|_| format!("Unknown {tnt:?}"))
                ))?
            )?;
        }

        Ok(())
    }
}

// A helper module that provides some grammars for testing.
#[cfg(feature = "test-helper")]
pub mod test_grammar_helper;

#[cfg(test)]
mod tests;