summaryrefslogtreecommitdiff
path: root/chain/src/item/default/splone.rs
blob: 09fca0b89d099b2b0feb1fe2b56eef2c8f5219ce (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
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
//! This module implements a function for "closing" and "splitting" a
//! node in a forest, and hence the name.

use super::*;
use grammar::TNT;

fn get_nt_label(label: GrammarLabel) -> Option<usize> {
    match label.label() {
        GrammarLabelType::TNT(TNT::Non(nt)) => Some(nt),
        _ => None,
    }
}

fn get_rule_label(label: GrammarLabel) -> Option<usize> {
    match label.label() {
        GrammarLabelType::Rule(rule) => Some(rule),
        _ => None,
    }
}

/// Existing or non-existing label.
#[derive(Debug, Copy, Clone)]
enum Eon {
    Ex(usize),
    Nex(ForestLabel<GrammarLabel>),
}

impl DefaultForest<ForestLabel<GrammarLabel>> {
    /// Either "open split" or "closed split".
    ///
    /// An open split is an attempt to set the end of the node to
    /// `None`, and a closed split is an attempt to set the end to a
    /// specific position.
    ///
    /// Also this function preserves `edge_index + 1` many children
    /// when splitting or cloning.
    ///
    /// To be more precise, this function performs the following
    /// actions:
    ///
    /// 1. Make sure it is labelled by a nonterminal.
    ///
    /// 2. Check the status of the node.  If it is packed, return an
    /// error.
    ///
    /// 3. Make a new label according to the given `end`.  See the
    /// function
    /// [`create_new_label`][DefaultForest::<ForestLabel<GrammarLabel>>::create_new_label]
    /// for the process of making new labels.
    ///
    /// 4. If the new label is equal to the old label, and if
    /// `edge_index + 1` is equal to the degree of the node, then do
    /// nothing.
    ///
    /// 5. If the new label is equal to the old label but
    /// `edge_index+1` is not equal to the degree of the node, then
    /// clone the node while preserving `edge_index + 1` many
    /// children.
    ///
    /// 6. If the new label is not equal to the old label, then split
    /// the node. See the function
    /// [`split_node`][DefaultForest::<ForestLabel<GrammarLabel>>::split_node]
    /// for details.
    ///
    /// # `completingp`
    ///
    /// When we are completing the forest at the end, we do not wish
    /// to keep the nodes at the end, so we pass a flag to inform the
    /// function of this intention.
    ///
    /// # Return
    ///
    /// The function returns the new, splitted or cloned node, or the
    /// old node, if nothing is performed.
    ///
    /// # Name
    ///
    /// The name is a mixture of *split* and *clone*.
    ///
    /// # NOTE
    ///
    /// We want to "do the same thing" to each parent of the node,
    /// that should be checked to be labelled by a rule position.
    ///
    /// That is to say, if we replace the label of the node, we also
    /// replace the label of the "rule parent".  If we split the node,
    /// the rule parents are also splitted in a parallel manner with
    /// the splitted node.
    ///
    /// Also, when we refer to the parents of the node in the
    /// descriptions of procedures below, we actually refer to the
    /// parents of the rule parents, which should again be checked to
    /// be labelled by non-terminals.
    pub(crate) fn splone(
        &mut self,
        node: usize,
        end: Option<usize>,
        edge_index: usize,
        completingp: bool,
    ) -> Result<usize, Error> {
        let node_label = self.vertex_label(node)?.ok_or(Error::NodeNoLabel(node))?;

        assert!(get_nt_label(node_label.label()).is_some());

        if node_label.is_packed() {
            self.print_viz("dbg forest.gv").unwrap();
            dbg!(self.vertex_label(node)?, end);
            return Err(Error::SplitPack(node));
        }

        let node_end = node_label.label().end();
        let node_degree = self.degree(node)?;

        // We can check the end to know whether the new label is equal
        // to the old label.
        if node_end == end {
            if node_degree <= edge_index + 1 {
                return Ok(node);
            }

            let cloned = self.clone_node(node, edge_index + 1, false)?;

            return Ok(cloned);
        }

        let new_label = self.create_new_label(node, end, edge_index, None)?;

        let new_label = match new_label {
            Eon::Nex(label) => label,
            Eon::Ex(existing) => {
                return Ok(existing);
            }
        };

        if node_end.is_some()
            || edge_index + 1 < node_degree
            || node_label.clone_index().is_some()
            || new_label.clone_index().is_some()
        {
            return self.split_node(new_label, node, edge_index, completingp);
        }

        self.replace_label(node, new_label)?;

        Ok(node)
    }

    /// Split or clone, and then plant.
    ///
    /// # Splone
    ///
    /// This function is similar to
    /// [`splone`][DefaultForest::<ForestLabel<GrammarLabel>>::splone],
    /// but this is specialized for planting a fragment under the
    /// newly sploned node.  See the above-mentionned function for
    /// details on how to splone.
    ///
    /// # Parameter `planted`
    ///
    /// The function to plant a fragment takes a parameter `planted`,
    /// which indicates whether or not the fragment had already been
    /// planted before.  This is used to avoid re-inserting fragments
    /// into the forest.  One can just add an edge and be done.
    ///
    /// # Special treatment
    ///
    /// This function is aimed at solving a specific problem that the
    /// function
    /// [`splone`][DefaultForest::<ForestLabel<GrammarLabel>>::splone]
    /// faces: duplication of nodes after planting a fragment under
    /// the newly sploned node.  That is, if we splone a node and then
    /// immediately plant a fragment under it, then that new node will
    /// become a different node from the original sploned node, so if
    /// we splone another node that ends up creating the same sploned
    /// node, and if we plant the same fragment under it, we will end
    /// up creating duplicated cloned nodes, which later mess up the
    /// forests.
    ///
    /// So this function first checks if the would-be-sploned node
    /// with the fragment planted already exists; if so, then just
    /// return that node, otherwise we perform the usual sploning and
    /// plant the fragment after the splone.
    ///
    /// # Special values of two parameters to `splone`
    ///
    /// Since we want to plant a fragment under the splone, the
    /// parameter `end` to the splone function is set to `None`
    /// automatically.
    ///
    /// Moreover, the parameter `completingp` is for completing the
    /// forest at the end, while we are definitely not at the end if
    /// we are going to plant a fragment after sploning, so that
    /// parameter is automatically set to `false` as well.
    pub(crate) fn splant(
        &mut self,
        node: usize,
        edge_index: usize,
        fragment: &DefaultForest<ForestLabel<GrammarLabel>>,
        planted: bool,
    ) -> Result<usize, Error> {
        let node_label = self.vertex_label(node)?.ok_or(Error::NodeNoLabel(node))?;

        assert!(get_nt_label(node_label.label()).is_some());

        if node_label.is_packed() {
            self.print_viz("dbg forest.gv").unwrap();
            dbg!(self.vertex_label(node)?);
            return Err(Error::SplitPack(node));
        }

        let node_end = node_label.label().end();

        // We can check the end to know whether the new label is equal
        // to the old label.
        if node_end.is_none() {
            if let Some(node_to_plant) = self.find_node_to_plant(fragment, node, edge_index)? {
                self.plant(node_to_plant, fragment, planted)?;

                return Ok(node_to_plant);
            } else {
                return Ok(node);
            }
        }

        let new_label = self.create_new_label(node, None, edge_index, Some((fragment, planted)))?;

        let new_label = match new_label {
            Eon::Nex(label) => label,
            Eon::Ex(existing) => {
                return Ok(existing);
            }
        };

        let splitted = self.split_node(new_label, node, edge_index, false)?;

        self.plant(splitted, fragment, planted)?;

        Ok(splitted)
    }

    /// Replace the label of a node by a new label.
    ///
    /// This also handles the labels of parents of the node.
    fn replace_label(
        &mut self,
        node: usize,
        new_label: ForestLabel<GrammarLabel>,
    ) -> Result<(), Error> {
        let end = new_label.label().end();

        let mut builder = PLGBuilderMut::from_graph_mut(&mut self.graph);

        builder.set_label(node, new_label)?;

        let parents: Vec<_> = builder
            .parents_of(node)?
            .map(|parent| parent.node())
            .collect();

        for parent in parents {
            let mut parent_label = builder
                .vertex_label(parent)?
                .ok_or(Error::NodeNoLabel(parent))?
                .label();

            if get_rule_label(parent_label).is_none() {
                self.print_viz("dbg forest.gv").unwrap();
                panic!("assumption fails");
            }

            assert_eq!(builder.degree(parent)?, 1);

            if let Some(pos) = end {
                parent_label.set_end(pos);
            } else {
                parent_label.open_end();
            }

            let parent_label = ForestLabel::from(parent_label);

            builder.set_label(parent, parent_label)?;
        }

        Ok(())
    }

    /// Procedure to split the node:
    ///
    /// 1. Create a new node with the new label.
    ///
    /// 2. Preserve the old children as specified by `edge_index + 1`.
    ///
    /// 3. For each parent, clone the parent.  Replace the original
    /// child of the parent, which pointed to the old node, by this
    /// new node.  Other children are inherited from the old parent.
    ///
    /// # Return
    ///
    /// The function returns the new node index.
    fn split_node(
        &mut self,
        new_label: ForestLabel<GrammarLabel>,
        mut node: usize,
        edge_index: usize,
        completingp: bool,
    ) -> Result<usize, Error> {
        let end = new_label.label().end();

        let mut builder = PLGBuilderMut::from_graph_mut(&mut self.graph);

        let new_node = builder.add_vertex(new_label);

        let new_packed = if new_label.clone_index().is_some() {
            let packed = builder
                .query_label(ForestLabel::new(new_label.label(), ForestLabelType::Packed))
                .unwrap();

            builder.add_edge(packed, new_node, new_label)?;

            Some(packed)
        } else {
            None
        };

        let preserve_children: Vec<_> = builder.children_of(node)?.take(edge_index + 1).collect();

        for child in preserve_children {
            builder.add_edge(new_node, child, new_label)?;
        }

        let parents: Vec<_> = {
            if let Some(label) = self.vertex_label(node)? {
                if label.clone_index().is_some() {
                    let mut parents = self.parents_of(node)?;
                    assert_eq!(parents.len(), 1);
                    node = parents.next().unwrap().node();
                }
            }

            let parents: Vec<_> = self.parents_of(node)?.collect();

            let mut result: Vec<(Parent, usize)> = Vec::with_capacity(
                parents
                    .iter()
                    .map(|parent| {
                        self.parents_of(parent.node())
                            .map(|iter| iter.len())
                            .unwrap_or(0)
                    })
                    .sum(),
            );

            for parent in parents {
                let mut parent_label = self
                    .vertex_label(parent.node())?
                    .ok_or_else(|| Error::NodeNoLabel(parent.node()))?
                    .label();

                assert!(get_rule_label(parent_label).is_some());

                if self.degree(parent.node())? != 1 {
                    dbg!(parent);
                    self.print_viz("dbg forest.gv").unwrap();

                    panic!("assumption fails");
                }

                if let Some(pos) = end {
                    parent_label.set_end(pos);
                } else {
                    parent_label.open_end();
                }

                let parent_label = ForestLabel::from(parent_label);

                let mut builder = PLGBuilderMut::from_graph_mut(&mut self.graph);

                let new_parent = builder.add_vertex(parent_label);

                if let Some(packed) = new_packed {
                    builder.add_edge(new_parent, packed, new_label)?;
                } else {
                    builder.add_edge(new_parent, new_node, new_label)?;
                }

                result.extend(
                    self.parents_of(parent.node())?
                        .map(|parent_parent| (parent_parent, new_parent)),
                );
            }

            result
        };

        for (parent, new_child) in parents {
            if !completingp {
                if self.has_same_children_until(
                    parent.node(),
                    parent.node(),
                    parent.edge(),
                    new_child,
                )? {
                    continue;
                }

                // we don't add a child to parent.edge() here.
                let cloned = self.clone_node(parent.node(), parent.edge(), false)?;

                let mut builder = PLGBuilderMut::from_graph_mut(&mut self.graph);

                builder.add_edge(cloned, new_child, new_label)?;
            } else {
                if self.has_same_children_except(
                    parent.node(),
                    parent.node(),
                    parent.edge(),
                    new_child,
                )? {
                    continue;
                }

                // we don't add a child to parent.edge() here.
                let cloned = self.clone_node(parent.node(), parent.edge(), false)?;

                let mut builder = PLGBuilderMut::from_graph_mut(&mut self.graph);

                builder.add_edge(cloned, new_child, new_label)?;

                let children_to_add: Vec<_> = builder
                    .children_of(parent.node())?
                    .skip(parent.edge() + 1)
                    .collect();

                for child in children_to_add {
                    builder.add_edge(cloned, child, new_label)?;
                }
            }
        }

        Ok(new_node)
    }

    /// Procedure for the new label:
    ///
    /// 1. Copy the old label.
    ///
    /// 2. Set the end to `pos`.
    ///
    /// 3. Pack the label.
    ///
    /// 4. Check if this label already exists.  If so, clone the label and
    /// return it.
    ///
    /// 5. Else set the label to be a plain label.
    ///
    /// 6. Check if this plain label already exists.  If so, clone the
    /// existing label, and return the clone of the cloned label.
    ///
    /// 7. Else return the plain label.
    ///
    /// # Fragment planting
    ///
    /// If the parameter `fragment` contains a fragment, that means we
    /// also check if an existing label is what we want by checking
    /// whether it has the same children except for the last one,
    /// whereas its last child contains the fragment as a prefix.
    ///
    /// Also, if an existing label is found to have exactly the same
    /// children, then for the sake of consistency, we plant the
    /// fragment under that existing node.
    fn create_new_label(
        &mut self,
        node: usize,
        end: Option<usize>,
        edge_index: usize,
        fragment: Option<(&DefaultForest<ForestLabel<GrammarLabel>>, bool)>,
    ) -> Result<Eon, Error> {
        let mut copied_label = self
            .vertex_label(node)?
            .ok_or(Error::NodeNoLabel(node))?
            .label();

        if let Some(pos) = end {
            copied_label.set_end(pos);
        } else {
            copied_label.open_end();
        }

        let label = ForestLabel::new(copied_label, ForestLabelType::Packed);

        if let Some(packed) = self.query_label(label) {
            for child in self.children_of(packed)? {
                let child_degree = self.degree(child)?;

                if self.has_same_children(child, node, child_degree, edge_index + 1)? {
                    if let Some((fragment, planted)) = fragment {
                        self.plant(child, fragment, planted)?;
                    }

                    return Ok(Eon::Ex(child));
                }

                if let Some((fragment, _planted)) = fragment {
                    let modified_degree = std::cmp::max(child_degree, 1) - 1;

                    // dbg!(node, end, edge_index, modified_degree);

                    // dbg!(child, child_degree);

                    // dbg!(&fragment);

                    if self.has_same_children(child, node, modified_degree, edge_index + 1)?
                        && child_degree != 0
                    {
                        let last_child = self.nth_child(child, child_degree - 1)?;

                        if self.is_prefix(last_child, fragment)? {
                            return Ok(Eon::Ex(child));
                        }
                    }
                }
            }

            let mut packed_children = self.children_of(packed)?;

            let first_child = packed_children.next().unwrap();

            let clone_index = self.clone_node(first_child, 0, true)?;

            let cloned_label = ForestLabel::new(copied_label, ForestLabelType::Cloned(clone_index));

            Ok(Eon::Nex(cloned_label))
        } else {
            let plain_label = ForestLabel::new(copied_label, ForestLabelType::Plain);

            if let Some(existing) = self.query_label(plain_label) {
                let existing_degree = self.degree(existing)?;

                if self.has_same_children(existing, node, existing_degree, edge_index + 1)? {
                    if let Some((fragment, planted)) = fragment {
                        self.plant(existing, fragment, planted)?;
                    }

                    return Ok(Eon::Ex(existing));
                }

                if let Some((fragment, _planted)) = fragment {
                    let modified_degree = std::cmp::max(existing_degree, 1) - 1;

                    if existing_degree != 0
                        && self.has_same_children(
                            existing,
                            node,
                            modified_degree,
                            edge_index + 1,
                        )?
                    {
                        let last_child = self.nth_child(existing, existing_degree - 1)?;

                        if self.is_prefix(last_child, fragment)? {
                            return Ok(Eon::Ex(existing));
                        }
                    }
                }

                let clone_index = self.clone_node(existing, 0, true)?;

                Ok(Eon::Nex(ForestLabel::new(
                    copied_label,
                    ForestLabelType::Cloned(clone_index),
                )))
            } else {
                Ok(Eon::Nex(plain_label))
            }
        }
    }

    /// Determine if the `fragment` should be planted anew.  If so, return
    /// a node to plant.
    ///
    /// Precisely speaking, if `node` has the fragment planted at the
    /// position `edge_index` + 1, then there is no need to plant.  If
    /// not, but if `edge_index` + 1 is equal to the degree of `node`,
    /// then we can directly plant under `node`.
    ///
    /// Moreover, if `node` is cloned, then do the same check for each of
    /// its clones.
    ///
    /// # Assumption
    ///
    /// This function assumes the node is open-ended.
    fn find_node_to_plant(
        &mut self,
        fragment: &DefaultForest<ForestLabel<GrammarLabel>>,
        node: usize,
        edge_index: usize,
    ) -> Result<Option<usize>, Error> {
        let mut node = node;

        let node_label = self.vertex_label(node)?.ok_or(Error::NodeNoLabel(node))?;

        if node_label.is_packed() {
            dbg!("split pack: {node}");

            return Err(Error::SplitPack(node));
        }

        if node_label.clone_index().is_some() {
            let mut parents = self.parents_of(node)?;

            #[cfg(debug_assertions)]
            assert_eq!(parents.len(), 1, "Assumption fails");

            let packed = parents.next().unwrap().node();

            for clone in self.children_of(packed)? {
                let degree = self.degree(clone)?;

                if degree == 0 {
                    return Ok(Some(clone));
                }

                if degree >= edge_index + 2 {
                    let index_child = self.nth_child(clone, edge_index + 1)?;

                    if self.is_prefix(index_child, fragment.borrow())? {
                        return Ok(None);
                    }
                }

                if degree == edge_index + 1 {
                    return Ok(Some(clone));
                }
            }

            node = self.clone_node(node, edge_index + 1, false)?;

            return Ok(Some(node));
        }

        let degree = self.degree(node)?;

        if degree == 0 {
            return Ok(Some(node));
        }

        if degree >= edge_index + 2 {
            let index_child = self.nth_child(node, edge_index + 1)?;

            if self.is_prefix(index_child, fragment.borrow())? {
                return Ok(None);
            }
        }

        if degree == edge_index + 1 {
            return Ok(Some(node));
        }

        node = self.clone_node(node, edge_index + 1, false)?;

        Ok(Some(node))
    }

    /// Compare if two nodes have the same children in the same order.
    fn has_same_children(
        &self,
        nodea: usize,
        nodeb: usize,
        edge_num_a: usize,
        edge_num_b: usize,
    ) -> Result<bool, Error> {
        let children_a = self.children_of(nodea)?.take(edge_num_a);
        let children_b = self.children_of(nodeb)?.take(edge_num_b);

        if children_a.len() != children_b.len() {
            return Ok(false);
        }

        for (childa, childb) in children_a.zip(children_b) {
            if childa != childb {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Detect if a node has a branch that has the same children as
    /// another node, until a given index, where it points to another
    /// given node.
    ///
    /// # Clones
    ///
    /// If `nodea` is a clone, it checks every clone to see if the
    /// condition is satisfied for some clone.
    fn has_same_children_until(
        &self,
        nodea: usize,
        nodeb: usize,
        edge_index: usize,
        alternative: usize,
    ) -> Result<bool, Error> {
        let labela = self.vertex_label(nodea)?.ok_or(Error::NodeNoLabel(nodea))?;
        let children_b = self.children_of(nodeb)?;

        if children_b.len() < edge_index + 1 {
            return Err(Error::IndexOutOfBounds(edge_index, children_b.len() - 1));
        }

        if labela.is_plain() {
            let children_a = self.children_of(nodea)?;

            if children_a.len() < edge_index + 1 {
                return Ok(false);
            }

            for (index, (childa, childb)) in
                children_a.zip(children_b).take(edge_index + 1).enumerate()
            {
                if index != edge_index {
                    if childa != childb {
                        return Ok(false);
                    }
                } else if childa != alternative {
                    return Ok(false);
                }
            }

            Ok(true)
        } else if labela.clone_index().is_some() {
            let mut parentsa = self.parents_of(nodea)?;

            assert_eq!(parentsa.len(), 1);

            let parenta = parentsa.next().unwrap().node();

            'branch_loop: for branch in self.children_of(parenta)? {
                let children_a = self.children_of(branch)?;
                let children_b = children_b.clone();

                if children_a.len() < edge_index + 1 {
                    continue 'branch_loop;
                }

                for (index, (childa, childb)) in
                    children_a.zip(children_b).take(edge_index + 1).enumerate()
                {
                    if index != edge_index {
                        if childa != childb {
                            continue 'branch_loop;
                        }
                    } else if childa != alternative {
                        continue 'branch_loop;
                    }
                }

                return Ok(true);
            }

            Ok(false)
        } else {
            // a packed node; this should not happen
            unreachable!("should not examine children of a packed node")
        }
    }

    /// Detect if a node has a branch that has the same children as
    /// another node, except for a given index, where it points to another
    /// given node.
    ///
    /// # Clones
    ///
    /// If `nodea` is a clone, it checks every clone to see if the
    /// condition is satisfied for some clone.
    fn has_same_children_except(
        &self,
        nodea: usize,
        nodeb: usize,
        edge_index: usize,
        alternative: usize,
    ) -> Result<bool, Error> {
        let labela = self.vertex_label(nodea)?.ok_or(Error::NodeNoLabel(nodea))?;
        let children_b = self.children_of(nodeb)?;

        if children_b.len() < edge_index + 1 {
            return Err(Error::IndexOutOfBounds(edge_index, children_b.len() - 1));
        }

        if labela.is_plain() {
            let children_a = self.children_of(nodea)?;

            if children_a.len() != children_b.len() {
                return Ok(false);
            }

            for (index, (childa, childb)) in
                children_a.zip(children_b).take(edge_index + 1).enumerate()
            {
                if index != edge_index {
                    if childa != childb {
                        return Ok(false);
                    }
                } else if childa != alternative {
                    return Ok(false);
                }
            }

            Ok(true)
        } else if labela.clone_index().is_some() {
            let mut parentsa = self.parents_of(nodea)?;

            assert_eq!(parentsa.len(), 1);

            let parenta = parentsa.next().unwrap().node();

            'branch_loop: for branch in self.children_of(parenta)? {
                let children_a = self.children_of(branch)?;
                let children_b = children_b.clone();

                if children_a.len() < children_b.len() {
                    continue 'branch_loop;
                }

                for (index, (childa, childb)) in
                    children_a.zip(children_b).take(edge_index + 1).enumerate()
                {
                    if index != edge_index {
                        if childa != childb {
                            continue 'branch_loop;
                        }
                    } else if childa != alternative {
                        continue 'branch_loop;
                    }
                }

                return Ok(true);
            }

            Ok(false)
        } else {
            // a packed node; this should not happen
            unreachable!("should not examine children of a packed node")
        }
    }
}

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

    use grammar::TNT::*;

    fn create_test_forest(
    ) -> Result<DefaultForest<ForestLabel<GrammarLabel>>, Box<dyn std::error::Error>> {
        let mut forest = leaf!(GrammarLabel::new(Non(0), 0), GrammarLabel);

        forest.plant(
            0,
            leaf!(GrammarLabel::new_closed(6, 0, 1), GrammarLabel),
            false,
        )?;
        forest.plant(
            1,
            leaf!(GrammarLabel::new_closed(Ter(0), 0, 1), GrammarLabel),
            false,
        )?;

        forest.plant(0, leaf!(GrammarLabel::new(7, 1), GrammarLabel), false)?;
        forest.plant(3, leaf!(GrammarLabel::new(Non(0), 1), GrammarLabel), false)?;

        forest.plant(4, leaf!(GrammarLabel::new(3, 1), GrammarLabel), false)?;
        forest.plant(5, leaf!(GrammarLabel::new(Non(1), 1), GrammarLabel), false)?;

        forest.plant(
            6,
            leaf!(GrammarLabel::new_closed(11, 1, 2), GrammarLabel),
            false,
        )?;
        forest.plant(
            7,
            leaf!(GrammarLabel::new_closed(Ter(2), 1, 2), GrammarLabel),
            false,
        )?;

        forest.plant(
            6,
            leaf!(GrammarLabel::new_closed(13, 2, 3), GrammarLabel),
            false,
        )?;
        forest.plant(
            9,
            leaf!(GrammarLabel::new_closed(Ter(2), 2, 3), GrammarLabel),
            false,
        )?;

        forest.print_viz("test forest.gv")?;

        Ok(forest)
    }

    fn splone_6_3_1() -> Result<DefaultForest<ForestLabel<GrammarLabel>>, Box<dyn std::error::Error>>
    {
        let mut forest = create_test_forest()?;

        let mut builder = PLGBuilderMut::from_graph_mut(&mut forest.graph);

        builder.set_label(
            5,
            ForestLabel::new(GrammarLabel::new_closed(3, 1, 3), ForestLabelType::Plain),
        )?;

        builder.set_label(
            6,
            ForestLabel::new(
                GrammarLabel::new_closed(Non(1), 1, 3),
                ForestLabelType::Plain,
            ),
        )?;

        Ok(forest)
    }

    fn splone_6_2_0() -> Result<DefaultForest<ForestLabel<GrammarLabel>>, Box<dyn std::error::Error>>
    {
        let mut forest = splone_6_3_1()?;

        let cloned = forest.clone_node(4, 0, false)?;

        forest.plant(
            cloned,
            leaf!(GrammarLabel::new_closed(3, 1, 2), GrammarLabel),
            false,
        )?;

        forest.plant(
            cloned + 1,
            leaf!(GrammarLabel::new_closed(Non(1), 1, 2), GrammarLabel),
            false,
        )?;

        let mut builder = PLGBuilderMut::from_graph_mut(&mut forest.graph);

        let dummy_label = ForestLabel::from(GrammarLabel::new(0, 0));

        builder.add_edge(cloned + 2, 7, dummy_label)?;

        Ok(forest)
    }

    fn splone_6_n_0() -> Result<DefaultForest<ForestLabel<GrammarLabel>>, Box<dyn std::error::Error>>
    {
        let mut forest = splone_6_2_0()?;

        let cloned = forest.clone_node(4, 0, false)?;

        forest.plant(cloned, leaf!(GrammarLabel::new(3, 1), GrammarLabel), false)?;

        forest.plant(
            cloned + 1,
            leaf!(GrammarLabel::new(Non(1), 1), GrammarLabel),
            false,
        )?;

        let mut builder = PLGBuilderMut::from_graph_mut(&mut forest.graph);

        let dummy_label = ForestLabel::from(GrammarLabel::new(0, 0));

        builder.add_edge(cloned + 2, 7, dummy_label)?;

        Ok(forest)
    }

    fn splone_4_3_0() -> Result<DefaultForest<ForestLabel<GrammarLabel>>, Box<dyn std::error::Error>>
    {
        let mut forest = splone_6_n_0()?;

        let cloned = forest.clone_node(0, 0, false)?;

        forest.plant(
            cloned,
            leaf!(GrammarLabel::new_closed(6, 0, 1), GrammarLabel),
            true,
        )?;

        forest.plant(
            cloned,
            leaf!(GrammarLabel::new_closed(7, 1, 3), GrammarLabel),
            false,
        )?;

        forest.plant(
            cloned + 1,
            leaf!(GrammarLabel::new_closed(Non(0), 1, 3), GrammarLabel),
            false,
        )?;

        let mut builder = PLGBuilderMut::from_graph_mut(&mut forest.graph);

        let dummy_label = ForestLabel::from(GrammarLabel::new(0, 0));

        builder.add_edge(cloned + 2, 5, dummy_label)?;

        Ok(forest)
    }

    fn splone_17_3_0_15_3_0(
    ) -> Result<DefaultForest<ForestLabel<GrammarLabel>>, Box<dyn std::error::Error>> {
        let mut forest = splone_4_3_0()?;

        let to_clone = forest
            .query_label(ForestLabel::from(GrammarLabel::new_closed(Non(1), 1, 3)))
            .unwrap();

        let cloned = forest.clone_node(to_clone, 0, false)?;

        let mut builder = PLGBuilderMut::from_graph_mut(&mut forest.graph);

        let dummy_label = ForestLabel::from(GrammarLabel::new(0, 0));

        let child = builder
            .query_label(ForestLabel::from(GrammarLabel::new_closed(11, 1, 2)))
            .unwrap();

        builder.add_edge(cloned, child, dummy_label)?;

        let to_clone = forest
            .query_label(ForestLabel::from(GrammarLabel::new_closed(Non(0), 1, 3)))
            .unwrap();

        let cloned = forest.clone_node(to_clone, 0, false)?;

        let mut builder = PLGBuilderMut::from_graph_mut(&mut forest.graph);

        let child = builder
            .query_label(ForestLabel::from(GrammarLabel::new(3, 1)))
            .unwrap();

        builder.add_edge(cloned, child, dummy_label)?;

        Ok(forest)
    }

    #[test]
    fn test() -> Result<(), Box<dyn std::error::Error>> {
        let mut test_forest = create_test_forest()?;

        test_forest.splone(6, Some(3), 1, false)?;

        let answer = splone_6_3_1()?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 6 3 1.gv")?;
            panic!("splone(6, Some(3), 1) produced wrong forest");
        }

        test_forest.splone(6, Some(3), 1, false)?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 6 3 1.gv")?;
            panic!("repeated splone(6, Some(3), 1) produced wrong forest");
        }

        test_forest.splone(6, Some(2), 0, false)?;

        let answer = splone_6_2_0()?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 6 2 0.gv")?;
            panic!("splone(6, Some(2), 0) produced wrong forest");
        }

        test_forest.splone(6, Some(2), 0, false)?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 6 2 0.gv")?;
            panic!("repeated splone(6, Some(2), 0) produced wrong forest");
        }

        test_forest.splone(6, None, 0, false)?;

        let answer = splone_6_n_0()?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 6 None 0.gv")?;
            panic!("splone(6, None, 0) produced wrong forest");
        }

        test_forest.splone(14, None, 0, false)?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 6 None 0.gv")?;
            panic!("repeated splone(6, None, 0) produced wrong forest");
        }

        test_forest.splone(4, Some(3), 0, false)?;

        let answer = splone_4_3_0()?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 4 3 0.gv")?;
            panic!("splone(4, Some(3), 0) produced wrong forest");
        }

        test_forest.splone(4, Some(3), 0, false)?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 4 3 0.gv")?;
            panic!("repeated splone(4, Some(3), 0) produced wrong forest");
        }

        test_forest.splone(17, Some(3), 0, false)?;
        test_forest.splone(15, Some(3), 0, false)?;

        let answer = splone_17_3_0_15_3_0()?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 17 3 0 15 3 0.gv")?;
            panic!("splone(17, Some(3), 0) - splone(15, Some(3), 0) produced wrong forest");
        }

        test_forest.splone(17, Some(3), 0, false)?;
        test_forest.splone(15, Some(3), 0, false)?;

        if test_forest != answer {
            test_forest.print_viz("sploned forest.gv")?;
            answer.print_viz("splone 17 3 0 15 3 0.gv")?;
            panic!(
                "repeated splone(17, Some(3), 0) - splone(15, Some(3), 0) produced wrong forest"
            );
        }

        Ok(())
    }
}