Skip to content

Commit ad80396

Browse files
authored
Safe mode: search for extends_statement node instead of accessing it by index (#174)
1 parent 63393e6 commit ad80396

File tree

3 files changed

+26
-12
lines changed

3 files changed

+26
-12
lines changed

src/formatter.rs

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -931,22 +931,18 @@ impl GdTree {
931931
continue;
932932
}
933933

934-
// If this class extends from anything, extends_statement will be the second child,
935-
// because the first child will be the name of the class
936-
if child.children.len() < 2 {
934+
// Checking if this node has extends_statement node as child
935+
let Some(extends_statement_child_index) =
936+
self.first_named_child(child, "extends_statement")
937+
else {
937938
continue;
938-
}
939-
940-
let second_child_id = child.children[1];
941-
let second_child = &self.nodes[second_child_id];
942-
943-
if second_child.grammar_name != "extends_statement" {
944-
continue;
945-
}
939+
};
946940

947941
// When we found it, we move it to be a direct sibling of class_name_statement node
948942
let class_name_node = &mut self.nodes[child_id];
949-
let extends_node_id = class_name_node.children.remove(1);
943+
let extends_node_id = class_name_node
944+
.children
945+
.remove(extends_statement_child_index);
950946

951947
let root = &mut self.nodes[0];
952948
root.children.insert(child_index + 1, extends_node_id);
@@ -1044,6 +1040,21 @@ impl GdTree {
10441040
}
10451041
}
10461042
}
1043+
1044+
/// Returns index of the first child with the given grammar name.
1045+
fn first_named_child(&self, node: &GdTreeNode, grammar_name: &str) -> Option<usize> {
1046+
node.children
1047+
.iter()
1048+
.enumerate()
1049+
.find_map(|(index, &child_id)| {
1050+
let child = &self.nodes[child_id];
1051+
if child.grammar_name == grammar_name {
1052+
Some(index)
1053+
} else {
1054+
None
1055+
}
1056+
})
1057+
}
10471058
}
10481059

10491060
impl PartialEq for GdTree {
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
@abstract class_name MyNode
2+
extends Node
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
@abstract class_name MyNode extends Node

0 commit comments

Comments
 (0)