-
Notifications
You must be signed in to change notification settings - Fork 19
/
dag.rs
2152 lines (1982 loc) · 79.7 KB
/
dag.rs
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
//! Code for an editable, undoable forest of syntax trees.
use crate::arena::Arena;
use crate::ast;
use crate::ast::{Ast, AstClass};
use crate::core::{Direction, Path, Side};
use std::{collections::HashMap, hash::Hash};
/// The two possible locations where an edit could cause nodes to be replaced
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum EditLocation {
/// The edit caused the cursor to be replaced
Cursor = 0,
/// The edit caused the parent to be replaced
Parent = 1,
}
impl EditLocation {
/// How many steps above the cursor was the edit made
#[inline]
fn steps_above_cursor(self) -> usize {
self as usize
}
}
/// An enum that's returned when any of the 'edit' methods in [`Dag`] are successful.
#[allow(missing_docs)]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum EditSuccess<C: AstClass> {
Undo,
Redo,
Move(usize, Direction),
Replace(C),
InsertChild(C),
InsertNextToCursor { side: Side, class: C },
Delete { name: String },
}
impl<C: AstClass> EditSuccess<C> {
/// Writes an info message of a successful action using `info!`
fn log_message(self) {
match self {
EditSuccess::Undo => log::info!("Undoing one change"),
EditSuccess::Redo => log::info!("Redoing one change"),
EditSuccess::Move(n, Direction::Up) => log::info!("Moving {} levels up the tree", n),
EditSuccess::Move(n, Direction::Down) => {
log::info!("Moving {} levels down the tree", n)
}
EditSuccess::Move(n, Direction::Prev) => {
log::info!("Moving to {}th previous sibling", n)
}
EditSuccess::Move(n, Direction::Next) => log::info!("Moving to {}th next sibling", n),
EditSuccess::Replace(class) => {
log::info!("Replacing with '{}'/{}", class.to_char(), class.name())
}
EditSuccess::InsertChild(class) => {
log::info!(
"Inserting '{}'/{} as new child",
class.to_char(),
class.name()
)
}
EditSuccess::InsertNextToCursor { side, class } => log::info!(
"Inserting '{}'/{} {} the cursor",
class.to_char(),
class.name(),
side.relational_word()
),
EditSuccess::Delete { name } => log::info!("Deleting {}", name),
}
}
}
/// An error that represents an error in any of the 'edit' methods in [`Dag`].
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum EditErr<C: AstClass> {
/* MOVEMENT ERRORS */
/// Trying to move to a sibling of the root
MoveToSiblingOfRoot,
/* EDITING ERRORS */
/// Trying to undo the earliest change
NoChangesToUndo,
/// Trying to redo the latest change
NoChangesToRedo,
/// The user typed a char that doesn't correspond to any node
CharNotANode(char),
/// Trying to insert a node that cannot be root node
CannotBeRoot(C),
/// Trying to insert a node that cannot be a child of the cursor
CannotBeChild {
/// The class representing the disallowed child type
class: C,
/// The [`display_name`](Ast::display_name) of the parent node
parent_name: String,
},
/// Trying to replace many children
ReplaceError {
/// Current node index
current_child_index: usize,
/// Last node index
last_child_index: usize,
/// Node count
node_count: usize,
},
/// There were no nodes to insert
NoNodesToInsert,
/// An error was generated by the Ast code when trying to insert a node
InsertError(ast::InsertError),
/// An error was generated by the Ast code when trying to delete a node
DeleteError(ast::DeleteError),
/// Trying to add a sibling to the root
AddSiblingToRoot,
/// Trying to delete the root
DeletingRoot,
}
impl<C: AstClass> EditErr<C> {
/// Writes an warning message of the encountered error using either `warn!` or `error!`,
/// depending on the severity of the error
fn log_message(self) {
match self {
EditErr::MoveToSiblingOfRoot => log::warn!("Can't move to a sibling of the root."),
EditErr::NoChangesToUndo => log::warn!("No changes to undo."),
EditErr::NoChangesToRedo => log::warn!("No changes to redo."),
EditErr::NoNodesToInsert => log::warn!("No nodes to insert."),
EditErr::InsertError(e) => log::warn!("{}", e),
EditErr::DeleteError(e) => log::warn!("{}", e),
EditErr::CharNotANode(c) => log::warn!("'{}' doesn't correspond to any node type.", c),
EditErr::CannotBeRoot(c) => {
log::warn!("'{}' cannot be root", c.name())
}
EditErr::CannotBeChild { class, parent_name } => {
log::warn!("'{}' cannot be a child of {}", class.name(), parent_name)
}
EditErr::ReplaceError {
current_child_index,
last_child_index,
node_count,
} => {
log::warn!(
"Current child index: {}, Last child index {}, to be replaced node count {}",
current_child_index,
last_child_index,
node_count,
)
}
EditErr::AddSiblingToRoot => log::warn!("Can't add siblings to the root."),
EditErr::DeletingRoot => log::warn!("Can't delete the root."),
}
}
}
impl<C: AstClass> From<ast::InsertError> for EditErr<C> {
fn from(e: ast::InsertError) -> EditErr<C> {
EditErr::InsertError(e)
}
}
impl<C: AstClass> From<ast::DeleteError> for EditErr<C> {
fn from(e: ast::DeleteError) -> EditErr<C> {
EditErr::DeleteError(e)
}
}
/// An alias for [`Result`] that is the return type of all of [`Dag`]'s edit methods.
pub type EditResult<C> = Result<EditSuccess<C>, EditErr<C>>;
/// A trait-extension that provides a convenient way convert [`EditResult`]s into log messages.
pub trait LogMessage {
/// Log the current result's message to the appropriate log channel.
fn log_message(self);
}
impl<C: AstClass> LogMessage for EditResult<C> {
/// Consumes this `EditResult` and logs an appropriate summary report (using `info!` for
/// [`EditSuccess`]es and `warn!` or `error!` for [`EditErr`]s).
fn log_message(self) {
match self {
Ok(ok) => ok.log_message(),
Err(err) => err.log_message(),
}
}
}
/// A specification of things which can be inserted into a syntax tree
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Insertable {
/// Insert the node given by a certain [`char`] some number of times
CountedNode(usize, char),
}
impl std::fmt::Display for Insertable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Insertable::CountedNode(count, c) => write!(f, "{}{}", count, c),
}
}
}
/// A representation of a single edit, along with the cursor locations around it
struct Snapshot<'arena, Node: Ast<'arena>> {
cursor_before: Path,
root: &'arena Node,
cursor_after: Path,
}
impl<'arena, Node: Ast<'arena>> Snapshot<'arena, Node> {
fn new(cursor_before: Path, root: &'arena Node, cursor_after: Path) -> Self {
Snapshot {
cursor_before,
root,
cursor_after,
}
}
}
/// A datastructure that stores the history of a tree as a Dag (Directed Acyclic Graph) of
/// **immutable** nodes.
///
/// This means that every node that has ever been created exists somewhere in the Dag, and when
/// changes are made, every ancestor of that node is cloned until the root is reached and that
/// root becomes the new 'current' root. This is very similar to the way Git handles commits -
/// each node is like a file/directory and each root is a commit.
///
/// Therefore, moving back through the history is as simple as reading a different root node from
/// the `roots` vector, and following its descendants through the Dag of nodes.
pub struct Dag<'arena, Node: Ast<'arena>> {
/// The arena in which all the `Node`s will be stored
arena: &'arena Arena<Node>,
/// A [`Vec`] containing a reference to the root node at every edit in the undo history. This
/// is required to always have length at least one.
root_history: Vec<Snapshot<'arena, Node>>,
/// An index into [`root_history`](Dag::root_history) of the current edit. This is required to
/// be in `0..root_history.len()`.
history_index: usize,
current_cursor_path: Path,
cursor_location_history: HashMap<usize, usize>,
}
impl<'arena, Node: Ast<'arena>> Dag<'arena, Node> {
/// Builds a new `Dag`, given the tree it should contain
pub fn new(arena: &'arena Arena<Node>, root: &'arena Node, cursor_path: Path) -> Self {
Dag {
arena,
root_history: vec![Snapshot::new(
cursor_path.clone(),
root,
cursor_path.clone(),
)],
history_index: 0,
current_cursor_path: cursor_path,
cursor_location_history: HashMap::new(),
}
}
/* NAVIGATION METHODS */
/// Returns a reference to the node that is currently the root of the AST.
pub fn root(&self) -> &'arena Node {
// This indexing shouldn't panic because we require that `self.history_index` is a valid
// index into `self.root_history`, and `self.root_history` has at least one element
self.root_history[self.history_index].root
}
/// Returns the cursor node and its direct parent (if such a parent exists)
pub fn cursor_and_parent(&self) -> (&'arena Node, Option<&'arena Node>) {
self.current_cursor_path.cursor_and_parent(self.root())
}
/// Returns a reference to the node that is currently under the cursor.
pub fn cursor(&self) -> &'arena Node {
self.current_cursor_path.cursor(self.root())
}
/// Move the cursor a given `distance` in a given [`Direction`] across the tree.
pub fn move_cursor(
&mut self,
distance: usize,
direction: Direction,
) -> EditResult<Node::Class> {
let (mut current_cursor, cursor_parent) = self.cursor_and_parent();
let successful_distance = match direction {
Direction::Down => {
let mut successful_distance = 0usize;
while !current_cursor.children().is_empty() && successful_distance < distance {
// use current_cursor's memory address as key in hashmap,
// look up the previous cursor location in hashmap
// if key is not in hashmap, return None, and use 0 as index
let current_node_id = current_cursor as *const Node as usize;
let index = *self
.cursor_location_history
.get(¤t_node_id)
.unwrap_or(&0);
self.current_cursor_path.push(index);
current_cursor = current_cursor.children()[index];
successful_distance += 1;
}
successful_distance
}
Direction::Up => {
let mut successful_distance = 0usize;
while !self.current_cursor_path.is_root() && successful_distance < distance {
let (_, parent) = self.cursor_and_parent();
// this block of code will run when the current cursor is not on root, so unwrap is ok
let parent_node_id = parent.unwrap() as *const Node as usize;
// insert or update the parent_node_id and current_cursor_index in hashmap
self.cursor_location_history
.insert(parent_node_id, self.current_cursor_path.pop().unwrap());
successful_distance += 1;
}
successful_distance
}
Direction::Prev => {
let index = self
.current_cursor_path
.last_mut()
.ok_or(EditErr::MoveToSiblingOfRoot)?;
let last_index = *index;
*index = last_index.saturating_sub(distance);
// Return the distance that we actually moved
last_index - *index
}
Direction::Next => {
let index = self
.current_cursor_path
.last_mut()
.ok_or(EditErr::MoveToSiblingOfRoot)?;
let last_index = *index;
// We can unwrap here, because the only way for a node to not have a parent is
// if it's the root. And if the cursor is at the root, then the ? in the last line
// would have caught the error. The subtraction also cannot overflow because the
// parent of the cursor must have at least the cursor as a child.
let max_index = cursor_parent.unwrap().children().len() - 1;
*index = (*index + distance).min(max_index);
// Return the distance we travelled
*index - last_index
}
};
Ok(EditSuccess::Move(successful_distance, direction))
}
/* HISTORY METHODS */
/// Move one step back in the tree history
pub fn undo(&mut self, steps: usize) -> EditResult<Node::Class> {
log::trace!("Performing undo.");
// Early return if there are no changes to undo
if self.history_index == 0 {
return Err(EditErr::NoChangesToUndo);
}
// Move the history index back by one to perform the undo
self.history_index = self.history_index.saturating_sub(steps);
// Follow the behaviour of other text editors and update the location of the cursor
// with its location in the snapshot we are going forward to
self.current_cursor_path
.clone_from(&self.root_history[self.history_index + 1].cursor_before);
log::debug!("Setting cursor path to {:?}", self.current_cursor_path);
Ok(EditSuccess::Undo)
}
/// Move one step forward in the tree history
pub fn redo(&mut self, steps: usize) -> EditResult<Node::Class> {
log::trace!("Performing redo.");
// Early return if there are no changes to redo
if self.history_index >= self.root_history.len() - 1 {
return Err(EditErr::NoChangesToRedo);
}
// Move the history index forward by one to perform the redo
self.history_index = (self.history_index + steps).min(self.root_history.len() - 1);
// Follow the behaviour of other text editors and update the location of the cursor
// with its location in the snapshot we are going back to
self.current_cursor_path
.clone_from(&self.root_history[self.history_index].cursor_after);
log::debug!("Setting cursor path to {:?}", self.current_cursor_path);
Ok(EditSuccess::Redo)
}
/* EDITING METHODS */
fn perform_edit(
&mut self,
mut edit_func: impl FnMut(
// The `Dag` being edited
&mut Self,
// The parent and the cursor's child index (or `None` if the cursor is at the root)
Option<(&'arena Node, usize)>,
// A reference to the node under the cursor
&'arena Node,
) -> Result<
(Node, EditLocation, EditSuccess<Node::Class>),
EditErr<Node::Class>,
>,
) -> EditResult<Node::Class> {
// Generate a vec of pointers to the nodes that we will have to clone. We have to store
// this as a vec because the iterator that produces them (cursor_path::NodeIter) can only
// yield values from the root downwards, whereas we need the nodes in the opposite order.
let nodes_to_clone: Vec<&Node> = self.current_cursor_path.node_iter(self.root()).collect();
let old_cursor_path: Path = self.current_cursor_path.clone();
// Unwrap is safe because `nodes_to_clone` must always contain at least the root
let mut reverse_node_iter = nodes_to_clone.iter().copied().rev();
let cursor = reverse_node_iter.next().unwrap();
// Unwrapping in the closure is safe, because if the cursor does have a parent, then the
// cursor_path must have at least one element
let parent_and_index = reverse_node_iter
.next()
.map(|node| (node, old_cursor_path.last().unwrap()));
/* PERFORM THE EDIT */
let (new_node, edit_location, success) = edit_func(self, parent_and_index, cursor)?;
let steps_above_cursor = edit_location.steps_above_cursor();
/* CLONE ALL THE PARENT NODES TO GET A NEW ROOT */
// Because AST nodes are immutable, we make changes to nodes by entirely cloning the path
// down to the node under the cursor. We do this starting at the node under the cursor and
// work our way up parent by parent until we reach the root of the tree. At that point,
// this node becomes the root of the new tree.
let mut node = self.arena.alloc(new_node);
// Iterate backwards over the child indices and the nodes, whilst cloning the tree and
// replacing the correct child reference to point to the newly created node.
for (n, child_index) in nodes_to_clone
.iter()
.rev()
.skip(1)
.zip(old_cursor_path.iter().rev())
.skip(steps_above_cursor)
{
let mut cloned_node = (*n).clone();
cloned_node.replace_child(*child_index, node);
node = self.arena.alloc(cloned_node);
}
/* UPDATE THE HISTORY */
// Remove future trees from the history vector so that the currently 'checked-out' tree is
// the most recent tree in the history.
while self.history_index < self.root_history.len() - 1 {
// TODO: Deallocate the tree so that we don't get a 'memory leak'
self.root_history.pop();
}
// At this point, `node` contains a reference to the root of the new tree, so we just add
// this to the history, along with the cursor path.
log::debug!("current_cursor_path {:?}", self.current_cursor_path);
self.root_history.push(Snapshot::new(
old_cursor_path.clone(),
node,
self.current_cursor_path.clone(),
));
// Move the history index on by one so that we are pointing at the latest change
self.history_index = self.root_history.len() - 1;
/* RETURN SUCCESS */
Ok(success)
}
/// Replaces the current cursor with a node represented by `c`
pub fn replace_cursor(
&mut self,
prefix_count: usize,
insertable: Insertable,
) -> EditResult<Node::Class> {
let (node_count, class) = match insertable {
Insertable::CountedNode(count, c) => (
count,
Node::Class::from_char(c).ok_or(EditErr::CharNotANode(c))?,
),
};
// If `count` is 0, then the replacement is exactly equivalent to deleting the cursor.
//
// Ideally, replacement should just be implemented as deletion followed by insertion (which
// would fix at least one existing bug with replacement in JSON objects), but that is not
// possible in the current architecture because nodes like Json::Field cannot have their
// children deleted.
if node_count == 0 {
self.delete_cursor(prefix_count)?;
return Ok(EditSuccess::Replace(class));
}
// check if on the root
// get current node's parent
if prefix_count != 1 {
if let (_, Some(parent)) = self.cursor_and_parent() {
// Do boundary check
let max_index = parent.children().len() - 1;
// we can unwrap current_cursor_path can't be empty
let current_child_index = self.current_cursor_path.last().unwrap();
if current_child_index + prefix_count > max_index {
return Err(EditErr::ReplaceError {
current_child_index,
last_child_index: max_index,
node_count: prefix_count,
});
}
};
}
self.perform_edit(
|this: &mut Self,
_parent_and_index: Option<(&'arena Node, usize)>,
cursor: &'arena Node| {
// Early return if the `class` can't go in the cursor's location
match _parent_and_index {
Some((parent, _cursor_index)) => {
let mut cloned_parent = parent.clone();
// We can unwrap here, because we know that the cursor is not at the
// root and therefore there is at least one segment of the Path.
let next_cursor_index = this.current_cursor_path.last_mut().unwrap();
// Loop over the prefix count, so that the correct number of nodes get
// replaced
for _ in 0..prefix_count {
// Each time a node gets replaced, replace it with the nodes specified
// by the Insertable
for j in 0..node_count {
let insert_index = *next_cursor_index + j;
// Check that the new node would be valid in the insert location,
// and return if so
if !cloned_parent.is_valid_child(insert_index, class) {
return Err(EditErr::CannotBeChild {
class,
parent_name: parent.display_name(),
});
}
let new_node = this.arena.alloc(Node::from_class(class));
// Because of the short-circuit deletion rule, we know that there
// must be at least one node to insert. Therefore, we can use the
// first of these to replace the cursor and treat the rest as
// insertions.
if j == 0 {
cloned_parent.replace_child(insert_index, new_node);
} else {
cloned_parent.insert_child(
new_node,
this.arena,
insert_index,
)?;
}
}
// Move the cursor to **one past** the last node. This is so that the
// next loop iteration starts replacing the next node, and this effect
// is corrected by subtracting one after the loop.
*next_cursor_index += node_count;
}
// This will not underflow unless node_count == 0, in which case the
// delete short-circuit would stop this code executing
*next_cursor_index -= 1;
Ok((
cloned_parent,
EditLocation::Parent,
EditSuccess::Replace(class),
))
}
None => {
match (prefix_count * node_count, cursor.is_valid_root(class)) {
// This path is unreachable because its condition would trigger the
// short-circuiting call to delete
(0, _) => unreachable!(),
// If we're replacing the root with exactly 1 invalid node, then that's
// not OK
(1, false) => Err(EditErr::CannotBeRoot(class)),
// If we're replacing the root with exactly 1 valid node then it's OK
// and we do the replacement
(1, true) => Ok((
Node::from_class(class),
EditLocation::Cursor,
EditSuccess::Replace(class),
)),
// If we're replacing the root with more than 1 node, then this is
// equivalent to adding siblings to the root
_ => Err(EditErr::AddSiblingToRoot),
}
}
}
},
)
}
/// Updates the internal state so that the tree now contains `new_node` inserted as the last
/// child of the selected node. Also moves the cursor so that the new node is selected.
pub fn insert_child(
&mut self,
prefix_count: usize,
insertable: Insertable,
) -> EditResult<Node::Class> {
let (node_count, class) = match insertable {
Insertable::CountedNode(count, c) => (
count,
Node::Class::from_char(c).ok_or(EditErr::CharNotANode(c))?,
),
};
let count = prefix_count * node_count;
// If the count is 0, do nothing and exit
if count == 0 {
return Err(EditErr::NoNodesToInsert);
}
self.perform_edit(
|this: &mut Self,
_parent_and_index: Option<(&'arena Node, usize)>,
cursor: &'arena Node| {
log::debug!("Inserting '{}' as a new child.", class.to_char());
// Clone the node that currently is the cursor, and add the new nodes to the end of
// the child list
let mut cloned_cursor = cursor.clone();
// Add `count` children to the cursor
for _ in 0..count {
// Validate the tree at every step
if !cursor.is_valid_child(cursor.children().len(), class) {
log::debug!("New node could not be a valid child of the cursor");
// Short circuit if `c` couldn't be a valid child of the cursor
return Err(EditErr::CannotBeChild {
class,
parent_name: cursor.display_name(),
});
}
// Add the new child to the children of the cloned cursor
cloned_cursor.insert_child(
this.arena.alloc(Node::from_class(class)),
this.arena,
cloned_cursor.children().len(),
)?;
}
// Move the cursor to the last added child
this.current_cursor_path
.push(cloned_cursor.children().len() - 1);
// Return success
Ok((
cloned_cursor,
EditLocation::Cursor,
EditSuccess::InsertChild(class),
))
},
)
}
/// Updates the internal state so that the tree now contains `new_node` inserted as the first
/// child of the selected node. Also moves the cursor so that the new node is selected.
pub fn insert_next_to_cursor(
&mut self,
prefix_count: usize,
insertable: Insertable,
side: Side,
) -> EditResult<Node::Class> {
let (second_count, class) = match insertable {
Insertable::CountedNode(count, c) => (
count,
Node::Class::from_char(c).ok_or(EditErr::CharNotANode(c))?,
),
};
// For inserting next to the cursor, we can simply multiply the two counts together to form
// one single count
let count = prefix_count * second_count;
self.perform_edit(
|this: &mut Self,
parent_and_index: Option<(&'arena Node, usize)>,
_cursor: &'arena Node| {
// Find (and cache) the parent of the cursor. If the parent of the cursor doesn't
// exist, the cursor must be the root and we can't insert a node next to the root.
let (parent, cursor_index) = parent_and_index.ok_or(EditErr::AddSiblingToRoot)?;
// Calculate the index of the first child
let insert_start_index = cursor_index
+ match side {
Side::Prev => 0,
Side::Next => 1,
};
// Clone the parent, and insert the new nodes to it one by one
let mut cloned_parent = parent.clone();
for i in 0..count {
let insert_index = insert_start_index + i;
// Short circuit if not an insertable char
if !parent.is_valid_child(insert_index, class) {
return Err(EditErr::CannotBeChild {
class,
parent_name: parent.display_name(),
});
}
// Add the new child to the children of the cloned cursor
cloned_parent.insert_child(
this.arena.alloc(Node::from_class(class)),
this.arena,
insert_index,
)?;
}
// Move the cursor to the last inserted node. We can unwrap it here, because
// inserting siblings to the root would cause an error
*this.current_cursor_path.last_mut().unwrap() = insert_start_index + count - 1;
Ok((
cloned_parent,
EditLocation::Parent,
EditSuccess::InsertNextToCursor { side, class },
))
},
)
}
/// Deletes up to `count` nodes after the cursor
pub fn delete_cursor(&mut self, count: usize) -> EditResult<Node::Class> {
self.perform_edit(
|this: &mut Self,
parent_and_index: Option<(&'arena Node, usize)>,
cursor: &'arena Node| {
// Find (and cache) the parent of the cursor. If the parent of the cursor doesn't
// exist, the cursor must be the root and we can't delete the root.
let (parent, cursor_index) = parent_and_index.ok_or(EditErr::DeletingRoot)?;
// Cache the name of the cursor **before** it gets deleted
let deleted_node_name = cursor.display_name();
let mut cloned_parent = parent.clone();
// Delete the node under the cursor `count` many times, or until we run off the end
// of the children
for _ in 0..count {
let res = cloned_parent.delete_child(cursor_index);
// If we've run off the end of the children, this is not an error - we just
// break the loop and stop
if let Err(ast::DeleteError::IndexOutOfRange { .. }) = res {
break;
}
// Any other errors are hard errors, so we should stop in those cases
res?;
}
let new_parents_child_count = cloned_parent.children().len();
if new_parents_child_count == 0 {
// If we remove the only child of a node then we move the cursor up
this.current_cursor_path.pop();
} else if cursor_index == new_parents_child_count {
// If we deleted the last child of a node (and this isn't the last child), we
// move the cursor back by one. We can unwrap here because we know we aren't
// removing the root
*this.current_cursor_path.last_mut().unwrap() -= 1;
}
Ok((
cloned_parent,
EditLocation::Parent,
EditSuccess::Delete {
name: deleted_node_name,
},
))
},
)
}
/* DISPLAY METHODS */
/// Build the text representation of the current tree into the given [`String`]
pub fn write_text(&self, string: &mut String, format: &Node::FormatStyle) {
self.root().write_text(string, format);
}
/// Build and return a [`String`] of the current tree
pub fn to_text(&self, format: &Node::FormatStyle) -> String {
let mut s = String::new();
self.write_text(&mut s, format);
s
}
/// Generate `.dot` code of the internal state of the `Dag`
pub fn to_dot_code(&self) -> String {
/// Helper function that recursively builds dot code for the entire subtree of a given node
fn add_to_graph<'arena, Node: Ast<'arena>>(
node: &'arena Node,
digraph_edges: &mut String,
hmap_nodes: &mut HashMap<usize, String>,
) {
let name = node as *const Node as usize;
if hmap_nodes.get(&name).is_some() {
return;
}
hmap_nodes.insert(
name,
format!("node{} [label={:?}]\n", name, node.debug_name()),
);
if !node.children().is_empty() {
for &child in node.children() {
add_to_graph(child, digraph_edges, hmap_nodes);
}
let edge = format!("node{} -> ", name);
digraph_edges.push_str(&edge);
for i in 0..node.children().len() {
let child_name = node.children()[i] as *const Node as usize;
if i != node.children().len() - 1 {
digraph_edges.push_str(&format!("node{}, ", child_name));
} else {
digraph_edges.push_str(&format!("node{}", child_name));
}
}
digraph_edges.push('\n');
}
}
let mut hmap_nodes = HashMap::<usize, String>::new();
let mut dot_buffer = "digraph G {\nnode [ordering=out]\n".to_owned();
let mut digraph_edges = "\n".to_owned();
let digraph_tail = "\n}";
for snapshot in &self.root_history {
add_to_graph(snapshot.root, &mut digraph_edges, &mut hmap_nodes);
}
for value in hmap_nodes.values() {
dot_buffer.push_str(value);
}
dot_buffer.push('\n');
dot_buffer.push_str(&digraph_edges);
dot_buffer.push_str(digraph_tail);
dot_buffer
}
}
#[cfg(test)]
mod tests {
use super::{Dag, EditErr, EditResult, EditSuccess, Insertable};
use crate::arena::Arena;
use crate::ast::json::{add_value_to_arena, Class, Json, JsonFormat};
use crate::ast::Ast;
use crate::core::{Direction, Path, Side};
use crate::editor::normal_mode::Action;
use serde_json::{json, Value};
/// Extension trait used to add the `execute_action` and `execute_action_once` methods to Dag
/// (`execute_action` was removed but is incredibly helpful for unit testing).
trait ExecuteAction {
fn execute_action_once(&mut self, action: Action) -> EditResult<Class> {
self.execute_action(1, action)
}
fn execute_action(&mut self, count: usize, action: Action) -> EditResult<Class>;
}
impl<'arena> ExecuteAction for Dag<'arena, Json<'arena>> {
fn execute_action(&mut self, count: usize, action: Action) -> EditResult<Class> {
match action {
Action::Undo => self.undo(count),
Action::Redo => self.redo(count),
Action::MoveCursor(direction) => self.move_cursor(count, direction),
Action::Replace(c) => self.replace_cursor(count, c),
Action::InsertChild(c) => self.insert_child(count, c),
Action::InsertBefore(c) => self.insert_next_to_cursor(count, c, Side::Prev),
Action::InsertAfter(c) => self.insert_next_to_cursor(count, c, Side::Next),
Action::Delete => self.delete_cursor(count),
Action::Quit | Action::Write => unreachable!(),
}
}
}
fn run_test_ok_count(
start_tree: Value,
start_cursor_location: Path,
count: usize,
action: Action,
expected_edit_success: EditSuccess<Class>,
expected_tree: Value,
expected_cursor_location: Path,
) {
let arena: Arena<Json> = Arena::new();
let root = add_value_to_arena(start_tree, &arena);
let mut dag = Dag::new(&arena, root, start_cursor_location);
assert_eq!(
Ok(expected_edit_success),
dag.execute_action(count, action),
"Not equal in action result"
);
assert_eq!(*dag.root(), expected_tree, "Not equal in tree.");
assert_eq!(
expected_cursor_location, dag.current_cursor_path,
"Not equal in cursor location."
);
}
fn run_test_ok(
start_tree: Value,
start_cursor_location: Path,
action: Action,
expected_edit_success: EditSuccess<Class>,
expected_tree: Value,
expected_cursor_location: Path,
) {
run_test_ok_count(
start_tree,
start_cursor_location,
1,
action,
expected_edit_success,
expected_tree,
expected_cursor_location,
);
}
/// Helper function for successfully moving the cursor the full specified distance
fn test_movement(
start_tree: Value,
start_cursor_location: Path,
count: usize,
direction: Direction,
expected_cursor_location: Path,
) {
test_capped_movement(
start_tree,
start_cursor_location,
count,
direction,
count,
expected_cursor_location,
);
}
/// Helper function for when the specified distance is not necessarily the distance covered.
fn test_capped_movement(
start_tree: Value,
start_cursor_location: Path,
distance: usize,
direction: Direction,
actual_distance: usize,
expected_cursor_location: Path,
) {
let arena: Arena<Json> = Arena::new();
let root = add_value_to_arena(start_tree.clone(), &arena);
let mut dag = Dag::new(&arena, root, start_cursor_location);
assert_eq!(
Ok(EditSuccess::Move(actual_distance, direction)),
dag.move_cursor(distance, direction),
"Not equal in action result"
);
assert_eq!(*dag.root(), start_tree, "Not equal in tree.");
assert_eq!(
expected_cursor_location, dag.current_cursor_path,
"Not equal in cursor location."
);
}
fn run_test_err_count(
start_tree: Value,
start_cursor_location: Path,
count: usize,
action: Action,
expected_edit_err: EditErr<Class>,
) {
let arena: Arena<Json> = Arena::new();
let root = add_value_to_arena(start_tree.clone(), &arena);
let mut dag = Dag::new(&arena, root, start_cursor_location.clone());
assert_eq!(
Err(expected_edit_err),
dag.execute_action(count, action),
"Not equal in action result"
);
assert_eq!(*dag.root(), start_tree, "Not equal in tree.");
assert_eq!(
start_cursor_location, dag.current_cursor_path,
"Not equal in cursor location."
);
}
fn run_test_err(
start_tree: Value,
start_cursor_location: Path,
action: Action,
expected_edit_err: EditErr<Class>,
) {
let arena: Arena<Json> = Arena::new();
let root = add_value_to_arena(start_tree.clone(), &arena);
let mut dag = Dag::new(&arena, root, start_cursor_location.clone());
assert_eq!(
Err(expected_edit_err),
dag.execute_action_once(action),
"Not equal in action result"
);
assert_eq!(*dag.root(), start_tree, "Not equal in tree.");
assert_eq!(
start_cursor_location, dag.current_cursor_path,
"Not equal in cursor location."
);
}
/* REPLACE */
/// Helper function specifically to run a replace test
fn test_single_replace_ok(
start_tree: Value,
cursor: Path,
node: char,
class: Class,
end_tree: Value,
) {
run_test_ok(
start_tree,
cursor.clone(),