aboutsummaryrefslogtreecommitdiff
path: root/chain/src/atom/default.rs
blob: 1870aa1f68f41a5d10c118ba37aa9b28dc2bc495 (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
//! This file provides a default implementation of the
//! [`Atom`][super::Atom] trait.

use super::*;
use grammar::{Grammar, GrammarLabel, GrammarLabelType};
use graph::{error::Error as GraphError, Graph, LabelExtGraph, LabelGraph};
use nfa::{
    default::{nfa::DefaultNFA, regex::DefaultRegex},
    error::Error as NFAError,
    LabelType, NfaLabel,
};

use graph_macro::Graph;

use core::fmt::Display;
use std::{
    collections::{hash_set::Iter, BTreeMap as Map, HashMap, HashSet},
    iter::Copied,
};

use crate::item::default::DefaultForest;
use forest::ForestLabel;

/// A virtual node represents the derivative of a non-terminal symbol
/// `s` with respect to a terminal symbol `t`.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
struct VirtualNode {
    s: usize,
    t: usize,
}

impl Display for VirtualNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "VN[{}]^({})", self.s, self.t)
    }
}

impl VirtualNode {
    fn new(s: usize, t: usize) -> Self {
        Self { s, t }
    }
}

type VirtualMap = Map<VirtualNode, usize>;

/// A virtual trace stores the rule positions that are responsible for
/// an edge from the virtual node \[nt\]^s to `target`.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
struct VirtualTrace {
    nt: usize,
    t: usize,
    target: usize,
}

impl Display for VirtualTrace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "VT[{}]^({}) -> {}", self.nt, self.t, self.target)
    }
}

impl VirtualTrace {
    fn new(nt: usize, t: usize, target: usize) -> Self {
        Self { nt, t, target }
    }
}

type VirtualTraceMap = Map<VirtualTrace, HashSet<usize>>;

type VirtualFrag = DefaultForest<ForestLabel<GrammarLabel>>;

type VirtualFragMap = Map<VirtualNode, Map<usize, VirtualFrag>>;

/// The type of atomic languages.
#[derive(Debug, Clone, Default, Graph)]
pub struct DefaultAtom {
    grammar: Grammar,
    #[graph]
    nfa: DefaultNFA<LabelType<TNT>>,
    accepting_vec: Vec<bool>,
    // NOTE: This is mostly for printing and debugging
    regexp: Vec<DefaultRegex<TNT>>,
    virtual_nodes: VirtualMap,
    virtual_traces: VirtualTraceMap,
    virtual_frags: VirtualFragMap,
    // /// `left_corners[x][y]` is true if and only if the non-terminal
    // /// `y` is in the reflexive-transitive closure of left corners of
    // /// the non-terminal `x`: `y` can start a derivation from `x`,
    // /// after only nullable symbols.
    // left_corners: Vec<Vec<bool>>,
    /// `left_corners[x][y]` is true if and only if the non-terminal
    /// `y` is in the reflexive-transitive closure of left corners of
    /// the non-terminal `x`: `y` can start a derivation from `x`,
    /// after only nullable symbols.
    left_corners: Vec<Vec<bool>>,
    /// `acc_by_nt[x][node]` is true if and only if `node` reaches the
    /// end of the non-terminal `x` by nullable edges.
    acc_by_nt: Vec<Vec<bool>>,
}

impl DefaultAtom {
    /// Return the string description of a rule position.
    pub fn rule_pos_string(&self, pos: usize) -> Result<String, Box<dyn std::error::Error>> {
        if pos == self.grammar.total() {
            return Ok("End of rules".to_owned());
        }

        let rule_num = self.grammar.get_rule_num(pos)?;

        assert!(rule_num < self.grammar.non_num());

        let display_tnt = |tnt| {
            format!(
                " {} ",
                self.name_of_tnt(match tnt {
                    TNT::Non(_) => tnt,
                    TNT::Ter(t) => self.unpack_tnt(t).unwrap(),
                })
                .unwrap_or_else(|e| format!("{e}"))
            )
        };

        Ok(self.regexp.get(rule_num).unwrap().to_string_with_dot(
            display_tnt,
            if rule_num == 0 {
                pos
            } else {
                pos - self.grammar.nth_accumulator(rule_num)?
            },
        )?)
    }

    /// Print nullable nodes.
    pub fn print_nullables(&self) {
        print!("printing nullables for the atom: ");

        for nullable in self
            .accepting_vec
            .iter()
            .enumerate()
            .filter_map(|(index, pred)| (*pred).then_some(index))
        {
            print!("{nullable}, ");
        }

        println!();
    }

    /// Print virtual nodes.
    pub fn print_virtual(&self) {
        println!("printing virtual nodes of the atom:");

        for (vn, node) in self.virtual_nodes.iter() {
            println!("[{}]^{{({})}}: {}", vn.s, vn.t, node);
        }

        println!();
    }

    /// Print the underlying NFA.
    pub fn print_nfa<S: AsRef<str>>(&self, filename: S) -> Result<(), std::io::Error> {
        self.nfa.print_viz(filename.as_ref())?;

        self.print_nullables();

        self.print_virtual();

        Ok(())
    }
}

impl Display for DefaultAtom {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let grammar = &self.grammar;

        let error_to_string = |err| format!("{err}");
        let tnt_to_string = |tnt, deco| {
            grammar
                .name_of_tnt(tnt)
                .map(|name| format!("{deco}({name})"))
                .unwrap_or_else(error_to_string)
        };

        let display_tnt = |tnt| match tnt {
            TNT::Ter(t) => format!(
                "({})",
                grammar
                    .unpack_tnt(t)
                    .map(|tnt| tnt_to_string(tnt, ""))
                    .unwrap_or_else(error_to_string)
            ),
            TNT::Non(_) => tnt_to_string(tnt, "H"),
        };

        writeln!(f, "regular expressions:")?;

        let mut accumulators = Vec::with_capacity(self.regexp.len() + 1);
        accumulators.push(0usize);

        for regex in self.regexp.iter() {
            writeln!(f, "accumulator: {}", accumulators.last().unwrap())?;

            accumulators.push(regex.nodes_len() * 2 + accumulators.last().unwrap());

            let string = regex.to_string_with(display_tnt)?;

            writeln!(f, "{string}")?;
        }

        writeln!(f, "total = {}", accumulators.last().unwrap())?;

        writeln!(f, "virtual nodes:")?;

        for (virtual_node, index) in self.virtual_nodes.iter() {
            writeln!(f, "{virtual_node}: {index}")?;
        }

        Ok(())
    }
}

// Some boiler-plate delegation implementations for Graph and
// LabelGraph, in order to implement Nfa.

impl LabelGraph<LabelType<TNT>> for DefaultAtom {
    type Iter<'b>
        = <DefaultNFA<LabelType<TNT>> as LabelGraph<LabelType<TNT>>>::Iter<'b>
    where
        Self: 'b;

    type TupleIter<'b>
        = <DefaultNFA<LabelType<TNT>> as LabelGraph<LabelType<TNT>>>::TupleIter<'b>
    where
        Self: 'b,
        DOption<TNT>: 'b;

    type LabelIter<'b>
        = <DefaultNFA<LabelType<TNT>> as LabelGraph<LabelType<TNT>>>::LabelIter<'b>
    where
        Self: 'b,
        DOption<TNT>: 'b;

    type EdgeLabelIter<'a>
        = <DefaultNFA<LabelType<TNT>> as LabelGraph<LabelType<TNT>>>::EdgeLabelIter<'a>
    where
        Self: 'a,
        DOption<TNT>: 'a;

    #[inline]
    fn vertex_label(&self, node_id: usize) -> Result<Option<LabelType<TNT>>, GraphError> {
        self.nfa.vertex_label(node_id)
    }

    #[inline]
    fn edge_label(
        &self,
        source: usize,
        target: usize,
    ) -> Result<Self::EdgeLabelIter<'_>, GraphError> {
        self.nfa.edge_label(source, target)
    }

    #[inline]
    fn find_children_with_label(
        &self,
        node_id: usize,
        label: &LabelType<TNT>,
    ) -> Result<<Self as LabelGraph<LabelType<TNT>>>::Iter<'_>, GraphError> {
        self.nfa.find_children_with_label(node_id, label)
    }

    #[inline]
    fn tuples_of(&self, node_id: usize) -> Result<Self::TupleIter<'_>, GraphError> {
        self.nfa.tuples_of(node_id)
    }

    #[inline]
    fn labels_of(&self, node_id: usize) -> Result<Self::LabelIter<'_>, GraphError> {
        self.nfa.labels_of(node_id)
    }

    #[inline]
    fn has_edge_label(
        &self,
        node_id: usize,
        label: &LabelType<TNT>,
        target: usize,
    ) -> Result<bool, GraphError> {
        self.nfa.has_edge_label(node_id, label, target)
    }
}

impl LabelExtGraph<LabelType<TNT>> for DefaultAtom {
    #[inline]
    fn extend(
        &mut self,
        edges: impl IntoIterator<Item = (LabelType<TNT>, usize)>,
    ) -> Result<usize, GraphError> {
        self.nfa.extend(edges)
    }
}

impl Nfa<LabelType<TNT>> for DefaultAtom {
    type FromRegex<S: graph::GraphLabel + std::fmt::Display + Default> = ();

    #[inline]
    fn to_nfa(
        _regexps: &[impl nfa::Regex<nfa::default::regex::RegexType<LabelType<TNT>>>],
        _sub_pred: impl Fn(LabelType<TNT>) -> Result<nfa::SoC<LabelType<TNT>>, NFAError>,
        _default: Option<LabelType<TNT>>,
    ) -> Result<Self::FromRegex<DOption<DOption<TNT>>>, NFAError> {
        // NOTE: We cannot construct an atom from a set of regular
        // languages alone.  So it is appropriate to panic here, if
        // one tries to do so, for some reason.
        unimplemented!()
    }

    #[inline]
    fn remove_dead(&mut self, reserve: impl FnMut(usize) -> bool) -> Result<(), NFAError> {
        self.nfa.remove_dead(reserve)
    }

    #[inline]
    fn closure(
        &mut self,
        predicate: impl FnMut(LabelType<TNT>) -> bool,
        remove_after_p: bool,
        transform: impl FnMut(nfa::TwoEdges<LabelType<TNT>>) -> LabelType<TNT>,
        remove_predicate: impl FnMut(LabelType<TNT>) -> bool,
    ) -> Result<(), NFAError> {
        self.nfa
            .closure(predicate, remove_after_p, transform, remove_predicate)
    }
}

impl DefaultAtom {
    /// Construct an atomic language from a grammar.
    pub fn from_grammar(mut grammar: Grammar) -> Result<Self, GrammarError> {
        grammar.compute_firsts()?;

        let regexp = grammar.left_closure()?;

        let mut nfa = grammar.left_closure_to_nfa(&regexp)?;

        let accumulators: Vec<usize> = {
            let mut result = Vec::with_capacity(regexp.len() + 1);
            result.push(0);

            for regex in regexp.iter() {
                // Calling `unwrap` here is safe as `result` is always
                // non-empty.
                result.push(regex.nodes_len() * 2 + result.last().unwrap());
            }

            result
        };

        let accumulators_set: HashSet<usize> = accumulators.iter().copied().collect();

        let nullables: HashSet<usize> = (0..grammar.non_num())
            .filter(|n| matches!(grammar.is_nullable(*n), Ok(true)))
            .collect();

        // Now record accepting information.

        let nfa_len = nfa.nodes_len();

        let label_is_nullable = |label: NfaLabel<DOption<TNT>>| {
            if let Some(label) = *label.get_value() {
                matches!(label, TNT::Non(n) if nullables.contains(&n))
            } else {
                true
            }
        };

        let mut accepting_vec: Vec<bool> = std::iter::repeat(false).take(nfa_len).collect();

        for nfa_start in accumulators.iter().copied().take(regexp.len()) {
            *accepting_vec.get_mut(nfa_start + 1).unwrap() = true;
        }

        // The last is always accepting.
        *accepting_vec.get_mut(nfa_len - 1).unwrap() = true;

        let mut updated = true;

        while updated {
            updated = false;

            for node in nfa.nodes() {
                // skip those that do not need to be updated
                if *accepting_vec
                    .get(node)
                    .ok_or(GrammarError::IndexOutOfBounds(node, nfa_len))?
                {
                    continue;
                }

                'label_loop: for (label, target_iter) in nfa
                    .labels_of(node)
                    .map_err(|_| GrammarError::IndexOutOfBounds(node, nfa_len))?
                {
                    if label_is_nullable(*label) {
                        for target in target_iter {
                            if *accepting_vec
                                .get(target)
                                .ok_or(GrammarError::IndexOutOfBounds(target, nfa_len))?
                            {
                                // accepting_vec[node] must have been
                                // false, as we checked above
                                *accepting_vec.get_mut(node).unwrap() = true;
                                updated = true;

                                break 'label_loop;
                            }
                        }
                    }
                }
            }
        }

        // Perform nulling and remove_epsilon at the same time.
        // Acceptance is relative to the frame: a state may reach the
        // end of one non-terminal through nullable edges without
        // reaching the end of another.  So for every non-terminal `x`
        // compute the states that reach the end of `x` by nullable
        // edges, in the same way as `accepting_vec`.
        let acc_by_nt: Vec<Vec<bool>> = (0..grammar.non_num())
            .map(|x| -> Result<Vec<bool>, GrammarError> {
                let mut result: Vec<bool> = vec![false; nfa_len];

                *result.get_mut(accumulators[x] + 1).unwrap() = true;

                let mut updated = true;

                while updated {
                    updated = false;

                    for node in nfa.nodes() {
                        if result[node] {
                            continue;
                        }

                        'label_loop: for (label, target_iter) in nfa
                            .labels_of(node)
                            .map_err(|_| GrammarError::IndexOutOfBounds(node, nfa_len))?
                        {
                            if label_is_nullable(*label) {
                                for target in target_iter {
                                    if result[target] {
                                        result[node] = true;
                                        updated = true;

                                        break 'label_loop;
                                    }
                                }
                            }
                        }
                    }
                }

                Ok(result)
            })
            .collect::<Result<_, _>>()?;

        // Left corners must be computed before taking the null
        // closure, whose edges would hide the structure we are
        // following.
        let left_corners: Vec<Vec<bool>> = {
            let rule_positions = grammar.total() * 2;
            let nt_num = grammar.non_num();

            let mut result = vec![vec![false; nt_num]; nt_num];

            for x in 0..nt_num {
                let mut seen = vec![false; nfa_len];
                let mut stack = vec![*accumulators.get(x).unwrap()];

                result[x][x] = true;

                while let Some(node) = stack.pop() {
                    if std::mem::replace(&mut seen[node], true) {
                        continue;
                    }

                    if node < rule_positions {
                        result[x][grammar.get_rule_num(node / 2)?] = true;
                    }

                    // The edges out of the end of a rule lead to the
                    // rules which have that non-terminal as a left
                    // corner, not to the left corners of `x`.
                    if node % 2 == 1 && accumulators_set.contains(&(node - 1)) {
                        continue;
                    }

                    for (label, target_iter) in nfa
                        .labels_of(node)
                        .map_err(|_| GrammarError::IndexOutOfBounds(node, nfa_len))?
                    {
                        if let Some(TNT::Non(y)) = *label.get_value() {
                            result[x][y] = true;
                            stack.push(*accumulators.get(y).unwrap());
                        }

                        if label_is_nullable(*label) {
                            stack.extend(target_iter);
                        }
                    }
                }
            }

            result
        };

        nfa.closure(
            label_is_nullable,
            true,
            |two_edges| grammar.transform_label_null_epsilon(two_edges),
            |label| label.get_value().is_none(),
        )?;

        nfa.remove_dead(|node| accumulators_set.contains(&node))?;

        // Now add the virtual nodes.
        let mut virtual_nodes: VirtualMap = Default::default();

        // Record virtual traces.
        let mut virtual_traces: VirtualTraceMap = Default::default();

        // Record virtual fragments.
        let mut virtual_frags: VirtualFragMap = Default::default();

        let nt_num = grammar.non_num();

        assert!(nt_num <= accumulators.len());

        /// Convert an error telling us that an index is out of bounds.
        ///
        /// # Panics
        ///
        /// The function panics if the error is not of the expected
        /// kind.
        fn index_out_of_bounds_conversion(ge: GraphError) -> GrammarError {
            match ge {
                GraphError::IndexOutOfBounds(index, bound) => {
                    GrammarError::IndexOutOfBounds(index, bound)
                }
                // This is supposed to be unreachable, but we still
                // give it a valid value.
                _ => GrammarError::NFAFail(NFAError::Graph(ge)),
            }
        }

        for nt in 0..nt_num {
            // This is safe because of the above assertion.
            let nt_start = *accumulators.get(nt).unwrap();

            let children: std::collections::HashMap<_, _> = nfa
                .labels_of(nt_start)
                .map_err(index_out_of_bounds_conversion)?
                .map(|(label, target_iter)| (*label, target_iter))
                .collect();

            /// The tuples have the following meanings in order:
            ///
            /// - `LabelType` => the label for the edge
            ///
            /// - `usize` => the target of the edge
            ///
            /// - `Option<Vec<usize>>` => reduction information
            ///
            /// - `usize` => the rule position that caused this edge
            type TerminalsValue = (
                HashSet<(LabelType<TNT>, usize, Option<Vec<usize>>, usize)>,
                bool,
            );

            let mut terminals_map: HashMap<usize, TerminalsValue> = HashMap::new();

            for (label, children_iter) in children.into_iter() {
                if let Some(TNT::Ter(t)) = *label.get_value() {
                    let estimated_len = {
                        let mut result = 0;

                        for child in children_iter.clone() {
                            result += nfa.degree(child).map_err(index_out_of_bounds_conversion)?;
                        }

                        result
                    };

                    let virtual_trace = label.get_moved();

                    let mut accepting = false;

                    for child in children_iter {
                        // add a virtual fragment

                        let line: Vec<GrammarLabelType> = grammar
                            .query_expansion(nt_start, child)?
                            .iter()
                            .copied()
                            .flatten()
                            .flat_map(|(nt, rule)| [(*rule).into(), TNT::Non(*nt).into()])
                            .rev()
                            .chain(std::iter::once(TNT::Ter(t).into()))
                            .collect();

                        assert!(line.len() > 1);

                        // by our construction this must be a rule
                        let rule = line.get(line.len() - 2).unwrap().rule().unwrap();

                        use crate::default::Error as DError;

                        let frag = crate::item::genins::generate_fragment(line, 0).map_err(
                            |fe: DError| -> GrammarError {
                                match fe {
                                    DError::IndexOutOfBounds(index, bound) => {
                                        GrammarError::IndexOutOfBounds(index, bound)
                                    }
                                    DError::DuplicateNode(n) => GrammarError::NFAFail(
                                        NFAError::Graph(GraphError::DuplicatedNode(n)),
                                    ),
                                    DError::DuplicateEdge(source, target) => GrammarError::NFAFail(
                                        NFAError::Graph(GraphError::DuplicatedEdge(source, target)),
                                    ),
                                    DError::NodeNoLabel(n) => {
                                        panic!("node {n} has no label!")
                                    }
                                    DError::CannotReserve(_) => unreachable!(
                                        "generate_fragment should not signal this error"
                                    ),
                                    DError::CannotClone(_) => {
                                        unreachable!("we are not cloning")
                                    }
                                    DError::CannotPlant => {
                                        unreachable!("why can we not plant?")
                                    }
                                    DError::SplitPack(_) => {
                                        unreachable!("we not not splitting")
                                    }
                                    DError::InvalidClone(_) => {
                                        unreachable!("we are not cloning")
                                    }
                                    DError::CannotClose(_, _, _, _) => {
                                        unreachable!("we are not closing virtual nodes")
                                    }
                                    DError::Invalid => {
                                        panic!("a label is wrongly planted?")
                                    }
                                }
                            },
                        )?;

                        virtual_frags
                            .entry(VirtualNode::new(nt, t))
                            .or_default()
                            .insert(rule, frag);

                        // The virtual node accepts if some child
                        // reaches the end of `nt`.
                        accepting = accepting
                            || *acc_by_nt
                                .get(nt)
                                .and_then(|row| row.get(child))
                                .ok_or(GrammarError::IndexOutOfBounds(child, nfa_len))?;

                        if let Some((_, old_accepting)) = terminals_map.get_mut(&t) {
                            *old_accepting = *old_accepting || accepting;
                        } else {
                            terminals_map
                                .insert(t, (HashSet::with_capacity(estimated_len), accepting));
                        }

                        for (child_label, child_children_iter) in nfa
                            .labels_of(child)
                            .map_err(index_out_of_bounds_conversion)?
                        {
                            // We checked this is safe above.
                            let (set, _) = terminals_map.get_mut(&t).unwrap();

                            set.extend(child_children_iter.map(|target| {
                                (
                                    *child_label,
                                    target,
                                    grammar
                                        .query_reduction(child, target)
                                        .unwrap()
                                        .map(|slice| slice.to_vec()),
                                    virtual_trace,
                                )
                            }));
                        }
                    }
                }
            }

            for (t, (set, accepting)) in terminals_map.into_iter() {
                // update virtual traces

                for (_, target, _, pos) in set.iter() {
                    let trace = VirtualTrace::new(nt, t, *target);

                    virtual_traces.entry(trace).or_default().insert(*pos);
                }

                // add a virtual node

                let new_index = nfa
                    .extend(set.iter().map(|(label, target, _, _)| (*label, *target)))
                    .map_err(index_out_of_bounds_conversion)?;

                if accepting_vec.get(new_index).is_none() {
                    #[cfg(debug_assertions)]
                    assert_eq!(new_index, accepting_vec.len());

                    accepting_vec.push(accepting);
                }

                let virtual_node = VirtualNode::new(nt, t);

                virtual_nodes.insert(virtual_node, new_index);

                // update the reduction information
                for (_, target, info, _) in set {
                    if let Some(info) = info {
                        if !matches!(
                            grammar.query_reduction(new_index, target)?,
                            Some(original_reduction)
                                if original_reduction.len()
                                >= info.len())
                        {
                            grammar.set_reduction(new_index, target, info);
                        }
                    }
                }
            }
        }

        Ok(Self {
            grammar,
            nfa,
            regexp,
            virtual_nodes,
            accepting_vec,
            virtual_traces,
            virtual_frags,
            acc_by_nt,
            left_corners,
        })
    }

    /// Generate a vector of virtual fragments for a non-terminal and
    /// a terminal.
    ///
    /// # RULE
    ///
    /// If one passes `Some(rule)` as the paramter, then this returns
    /// only those fragments that begin with the specified rule.
    ///
    /// On the other hand, if one passes `None`, then this returns
    /// only those fragments that can end the non-terminal expansion.
    ///
    /// # Guarantee
    ///
    /// It is guaranteed that the 1-th node of each fragment is a rule
    /// number.
    pub(crate) fn generate_virtual_frags(
        &self,
        nt: usize,
        t: usize,
        rule: Option<usize>,
    ) -> Option<Vec<&VirtualFrag>> {
        let vn = VirtualNode::new(nt, t);

        if let Some(rule) = rule {
            self.virtual_frags
                .get(&vn)
                .and_then(|map| map.get(&rule))
                .map(|f| vec![f])
        } else {
            let result: Vec<&VirtualFrag> = self
                .virtual_frags
                .get(&vn)
                .iter()
                .copied()
                .flatten()
                .filter_map(|(rule, frag)| {
                    self.is_accepting(rule * 2 + 1)
                        .unwrap_or(false)
                        .then_some(frag)
                })
                .collect();

            if result.is_empty() {
                None
            } else {
                Some(result)
            }
        }
    }
}

/// A convenient getter for the map of virtual nodes.
fn query(map: &VirtualMap, nt: usize, t: usize) -> Option<usize> {
    map.get(&VirtualNode::new(nt, t)).copied()
}

impl std::ops::Deref for DefaultAtom {
    type Target = Grammar;

    fn deref(&self) -> &Self::Target {
        &self.grammar
    }
}

impl Atom for DefaultAtom {
    fn atom(&self, nt: usize, t: usize) -> Result<Option<usize>, GrammarError> {
        if nt >= self.grammar.non_num() {
            return Err(GrammarError::IndexOutOfBounds(nt, self.grammar.non_num()));
        }

        if t >= self.grammar.ter_num() {
            return Err(GrammarError::IndexOutOfBounds(t, self.grammar.ter_num()));
        }

        Ok(query(&self.virtual_nodes, nt, t))
    }

    fn empty(&self) -> usize {
        self.grammar.total() << 1
    }

    fn is_accepting(&self, node_id: usize) -> Result<bool, GrammarError> {
        self.accepting_vec
            .get(node_id)
            .copied()
            .ok_or(GrammarError::IndexOutOfBounds(
                node_id,
                self.accepting_vec.len(),
            ))
    }

    type Iter<'a>
        = Copied<Iter<'a, usize>>
    where
        Self: 'a;

    fn trace(&self, nt: usize, t: usize, target: usize) -> Option<<Self as Atom>::Iter<'_>> {
        let trace = VirtualTrace::new(nt, t, target);

        self.virtual_traces
            .get(&trace)
            .map(|set| set.iter().copied())
    }

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

    fn is_accepting_in(&self, frame_nt: usize, node_id: usize) -> Result<bool, GrammarError> {
        if node_id < self.grammar.total() * 2 {
            self.acc_by_nt
                .get(frame_nt)
                .and_then(|row| row.get(node_id))
                .copied()
                .ok_or(GrammarError::IndexOutOfBounds(
                    node_id,
                    self.accepting_vec.len(),
                ))
        } else {
            self.is_accepting(node_id)
        }
    }

    fn allowed_in_frame(&self, frame_nt: usize, node_id: usize) -> bool {
        if node_id >= self.grammar.total() * 2 {
            return true;
        }

        match self.grammar.get_rule_num(node_id / 2) {
            Ok(owner) => self
                .left_corners
                .get(frame_nt)
                .and_then(|row| row.get(owner))
                .copied()
                .unwrap_or(true),
            _ => true,
        }
    }
}

#[cfg(test)]
mod test_default_atom {
    use super::*;

    #[test]
    fn test_from_grammar() -> Result<(), Box<dyn std::error::Error>> {
        use grammar::Grammar;

        let grammar_str = std::fs::read_to_string(
            "/Users/durand/Desktop/Centre/A propos de programmes/Rust/rep/grammar/abnf grammars/test.abnf",
        )
            .unwrap();

        let grammar: Grammar = grammar_str.parse()?;

        println!("grammar");
        println!("{grammar}");

        let atom = DefaultAtom::from_grammar(grammar)?;

        atom.print_nullables();

        atom.print_virtual();

        for virtual_node in 166..=173 {
            assert_eq!(
                atom.is_accepting(virtual_node)?,
                [169, 170, 172].contains(&virtual_node)
            );
        }

        Ok(())
    }
}