Skip to content

Commit 5a38126

Browse files
Make get_children an iterator
1 parent 1353cbc commit 5a38126

File tree

24 files changed

+940
-815
lines changed

24 files changed

+940
-815
lines changed

crates/cairo-lang-defs/src/db.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1350,9 +1350,8 @@ pub fn get_all_path_leaves<'db>(
13501350
match use_path {
13511351
ast::UsePath::Leaf(use_path) => res.push(use_path),
13521352
ast::UsePath::Single(use_path) => stack.push(use_path.use_path(db)),
1353-
ast::UsePath::Multi(use_path) => {
1354-
stack.extend(use_path.use_paths(db).elements(db).rev())
1355-
}
1353+
ast::UsePath::Multi(use_path) => stack
1354+
.extend(use_path.use_paths(db).elements(db).collect::<Vec<_>>().into_iter().rev()),
13561355
ast::UsePath::Star(_) => {}
13571356
}
13581357
}
@@ -1370,9 +1369,8 @@ pub fn get_all_path_stars<'db>(
13701369
match use_path {
13711370
ast::UsePath::Leaf(_) => {}
13721371
ast::UsePath::Single(use_path) => stack.push(use_path.use_path(db)),
1373-
ast::UsePath::Multi(use_path) => {
1374-
stack.extend(use_path.use_paths(db).elements(db).rev())
1375-
}
1372+
ast::UsePath::Multi(use_path) => stack
1373+
.extend(use_path.use_paths(db).elements(db).collect::<Vec<_>>().into_iter().rev()),
13761374
ast::UsePath::Star(use_path) => res.push(use_path),
13771375
}
13781376
}

crates/cairo-lang-defs/src/patcher.rs

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -65,55 +65,52 @@ impl<'db> RewriteNode<'db> {
6565
match self {
6666
RewriteNode::Copied(syntax_node) => {
6767
*self = RewriteNode::new_modified(
68-
syntax_node.get_children(db).iter().copied().map(RewriteNode::Copied).collect(),
68+
syntax_node.get_children(db).map(RewriteNode::Copied).collect(),
6969
);
7070
extract_matches!(self, RewriteNode::Modified)
7171
}
7272
RewriteNode::Trimmed { node, trim_left, trim_right } => {
73-
let children = node.get_children(db);
73+
let mut children = node.get_children(db).enumerate();
7474
let num_children = children.len();
7575
let mut new_children = Vec::new();
7676

7777
// Get the index of the leftmost nonempty child.
78-
let Some(left_idx) =
79-
children.iter().position(|child| child.width(db) != TextWidth::default())
78+
let Some((left_idx, first_syntax)) =
79+
children.find(|(_, child)| child.width(db) != TextWidth::default())
8080
else {
8181
*self = RewriteNode::Modified(ModifiedNode { children: None });
8282
return extract_matches!(self, RewriteNode::Modified);
8383
};
8484
// Get the index of the rightmost nonempty child.
85-
let right_idx = children
86-
.iter()
87-
.rposition(|child| child.width(db) != TextWidth::default())
88-
.unwrap();
85+
let (right_idx, last_syntax) = children
86+
.rfind(|(_, child)| child.width(db) != TextWidth::default())
87+
.unwrap_or((left_idx, first_syntax));
8988
new_children.extend(itertools::repeat_n(
9089
RewriteNode::Modified(ModifiedNode { children: None }),
9190
left_idx,
9291
));
9392

9493
// The number of children between the first and last nonempty nodes.
9594
let num_middle = right_idx - left_idx + 1;
96-
let mut children_iter = children.iter().skip(left_idx);
9795
match num_middle {
9896
1 => {
9997
new_children.push(RewriteNode::Trimmed {
100-
node: *children_iter.next().unwrap(),
98+
node: first_syntax,
10199
trim_left: *trim_left,
102100
trim_right: *trim_right,
103101
});
104102
}
105103
_ => {
106104
new_children.push(RewriteNode::Trimmed {
107-
node: *children_iter.next().unwrap(),
105+
node: first_syntax,
108106
trim_left: *trim_left,
109107
trim_right: false,
110108
});
111-
for _ in 0..(num_middle - 2) {
112-
let child = *children_iter.next().unwrap();
109+
for (_, child) in children {
113110
new_children.push(RewriteNode::Copied(child));
114111
}
115112
new_children.push(RewriteNode::Trimmed {
116-
node: *children_iter.next().unwrap(),
113+
node: last_syntax,
117114
trim_left: false,
118115
trim_right: *trim_right,
119116
});

crates/cairo-lang-defs/src/test.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,8 @@ fn test_generic_item_id(
9292
}
9393
_ => {}
9494
}
95-
for child in node.get_children(db).iter() {
96-
find_generics(db, module_id, child, output);
95+
for child in node.get_children(db) {
96+
find_generics(db, module_id, &child, output);
9797
}
9898
}
9999
find_generics(&db_val, module_id, &file_syntax.as_syntax_node(), &mut output);

crates/cairo-lang-doc/src/documentable_formatter.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -865,7 +865,7 @@ fn write_function_signature<'db>(
865865

866866
/// Retrieves [`SyntaxKind::TypeClause`] text from [`SyntaxNode`].
867867
fn get_type_clause<'db>(syntax_node: SyntaxNode<'db>, db: &'db dyn Database) -> Option<String> {
868-
for child in syntax_node.get_children(db).iter() {
868+
for child in syntax_node.get_children(db) {
869869
if child.kind(db) == SyntaxKind::TypeClause {
870870
return Some(child.get_text_without_all_comment_trivia(db));
871871
}
@@ -959,7 +959,7 @@ fn write_struct_attributes_syntax<'db>(
959959
) -> Result<(), fmt::Error> {
960960
for attribute in attributes {
961961
let syntax_node = attribute.stable_ptr.lookup(f.db).as_syntax_node();
962-
for child in syntax_node.get_children(f.db).iter() {
962+
for child in syntax_node.get_children(f.db) {
963963
let to_text = child.get_text_without_all_comment_trivia(f.db);
964964
let cleaned_text = to_text.replace("\n", "");
965965
f.write_str(&cleaned_text)?;
@@ -978,7 +978,7 @@ fn write_syntactic_evaluation<'db>(
978978
let syntax_node = stable_location.syntax_node(f.db);
979979
if matches!(&syntax_node.green_node(f.db).details, green::GreenNodeDetails::Node { .. }) {
980980
let mut is_after_evaluation_value = false;
981-
for child in syntax_node.get_children(f.db).iter() {
981+
for child in syntax_node.get_children(f.db) {
982982
let kind = child.kind(f.db);
983983
if !matches!(kind, SyntaxKind::Trivia) {
984984
if matches!(kind, SyntaxKind::TerminalSemicolon) {
@@ -987,7 +987,7 @@ fn write_syntactic_evaluation<'db>(
987987
}
988988
if is_after_evaluation_value {
989989
f.buf.write_str(&SyntaxNode::get_text_without_all_comment_trivia(
990-
child, f.db,
990+
&child, f.db,
991991
))?;
992992
};
993993
if matches!(kind, SyntaxKind::TerminalEq) {

crates/cairo-lang-doc/src/location_links.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ fn collect_green_nodes<'db>(
3636
GreenNodeDetails::Token(text) => green_nodes.push((green_node.kind, text.to_string(db))),
3737
GreenNodeDetails::Node { .. } => {
3838
let syntax_node_children = syntax_node.get_children(db);
39-
syntax_node_children.iter().for_each(|child| {
40-
collect_green_nodes(db, child, green_nodes);
39+
syntax_node_children.for_each(|child| {
40+
collect_green_nodes(db, &child, green_nodes);
4141
});
4242
}
4343
}

crates/cairo-lang-formatter/src/formatter_impl.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1033,7 +1033,7 @@ impl<'a> FormatterImpl<'a> {
10331033
let internal_break_line_points_positions =
10341034
syntax_node.get_internal_break_line_point_properties(self.db, &self.config);
10351035
// TODO(ilya): consider not copying here.
1036-
let mut children = syntax_node.get_children(self.db).to_vec();
1036+
let mut children: Vec<_> = syntax_node.get_children(self.db).collect();
10371037
let n_children = children.len();
10381038

10391039
if self.config.merge_use_items {
@@ -1118,8 +1118,8 @@ impl<'a> FormatterImpl<'a> {
11181118
);
11191119

11201120
// Add merged children to the new_children list.
1121-
if let Some(child) = merged_node.get_children(self.db).iter().next() {
1122-
new_children.extend(child.get_children(self.db).iter().copied());
1121+
if let Some(child) = merged_node.get_children(self.db).next() {
1122+
new_children.extend(child.get_children(self.db));
11231123
}
11241124
}
11251125
}
@@ -1211,16 +1211,16 @@ impl<'a> FormatterImpl<'a> {
12111211
/// Formats a terminal node and appends the formatted string to the result.
12121212
fn format_terminal(&mut self, syntax_node: &SyntaxNode<'a>) {
12131213
// TODO(spapini): Introduce a Terminal and a Token enum in ast.rs to make this cleaner.
1214-
let children = syntax_node.get_children(self.db);
1215-
let [leading, token, trailing] = children else {
1216-
panic!("Terminal node should have 3 children.");
1217-
};
1214+
let mut children = syntax_node.get_children(self.db);
1215+
let leading = children.next().unwrap();
1216+
let token = children.next().unwrap();
1217+
let trailing = children.next().unwrap();
12181218
// The first newlines is the leading trivia correspond exactly to empty lines.
1219-
self.format_trivia(ast::Trivia::from_syntax_node(self.db, *leading), true);
1219+
self.format_trivia(ast::Trivia::from_syntax_node(self.db, leading), true);
12201220
if !syntax_node.should_skip_terminal(self.db) {
1221-
self.format_token(token);
1221+
self.format_token(&token);
12221222
}
1223-
self.format_trivia(ast::Trivia::from_syntax_node(self.db, *trailing), false);
1223+
self.format_trivia(ast::Trivia::from_syntax_node(self.db, trailing), false);
12241224
}
12251225
/// Appends a trivia node (if needed) to the result.
12261226
fn format_trivia(&mut self, trivia: syntax::node::ast::Trivia<'a>, is_leading: bool) {

crates/cairo-lang-formatter/src/node_properties.rs

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,6 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
140140
.parent(db)
141141
.unwrap()
142142
.get_children(db)
143-
.iter()
144143
.any(|c| c.kind(db) == SyntaxKind::PatternEnumInnerPattern) =>
145144
{
146145
true
@@ -931,8 +930,6 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
931930
}
932931

933932
fn should_skip_terminal(&self, db: &dyn Database) -> bool {
934-
let is_last =
935-
|node: &SyntaxNode<'_>, siblings: &[SyntaxNode<'_>]| siblings.last() == Some(node);
936933
// Check for TerminalComma with specific conditions on list types and position.
937934
if self.kind(db) == SyntaxKind::TerminalComma
938935
&& matches!(
@@ -961,9 +958,10 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
961958
self.parent_kind(db),
962959
Some(SyntaxKind::ExprList | SyntaxKind::PatternList)
963960
);
964-
if (!is_expr_or_pattern_list || children.len() > 2)
961+
let len = children.len();
962+
if (!is_expr_or_pattern_list || len > 2)
965963
// Ensure that this node is the last element in the list.
966-
&& is_last(self, children)
964+
&& children.last() == Some(*self)
967965
{
968966
return true;
969967
}
@@ -978,11 +976,11 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
978976
let statements_node = statement_node.parent(db).unwrap();
979977
// Checking if not the last statement, as `;` may be there to prevent the block from
980978
// returning the value of the current block.
981-
let not_last = !is_last(&statement_node, statements_node.get_children(db));
982-
let children = statement_node.get_children(db);
979+
let statements_children = statements_node.get_children(db);
980+
let not_last = statements_children.last() != Some(statement_node);
983981
if not_last
984982
&& matches!(
985-
children[1].kind(db),
983+
statement_node.get_child(db, 1).kind(db),
986984
SyntaxKind::ExprBlock
987985
| SyntaxKind::ExprIf
988986
| SyntaxKind::ExprMatch
@@ -999,7 +997,7 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
999997
{
1000998
let path_segment_node = self.parent(db).unwrap();
1001999
let path_node = path_segment_node.parent(db).unwrap();
1002-
if !is_last(&path_segment_node, path_node.get_children(db)) {
1000+
if path_node.get_children(db).last() != Some(path_segment_node) {
10031001
false
10041002
} else {
10051003
matches!(

crates/cairo-lang-parser/src/colored_printer.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ impl ColoredPrinter<'_> {
2828
} else if self.verbose && is_empty_kind(node.kind) {
2929
self.result.push_str(format!("{}", "<e>".red()).as_str());
3030
} else {
31-
for child in syntax_node.get_children(self.db).iter() {
32-
self.print(child);
31+
for child in syntax_node.get_children(self.db) {
32+
self.print(&child);
3333
}
3434
}
3535
}

crates/cairo-lang-parser/src/printer.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -209,29 +209,29 @@ impl<'a> Printer<'a> {
209209
NodeKind::Struct { members: expected_children }
210210
| NodeKind::Terminal { members: expected_children, .. } => {
211211
self.print_internal_struct(
212-
children,
212+
syntax_node.get_children(self.db),
213213
&expected_children,
214214
indent.as_str(),
215215
under_top_level,
216216
);
217217
}
218218
NodeKind::List { .. } => {
219-
for (i, child) in children.iter().enumerate() {
219+
for (i, child) in syntax_node.get_children(self.db).enumerate() {
220220
self.print_tree(
221221
format!("child #{i}").as_str(),
222-
child,
222+
&child,
223223
indent.as_str(),
224224
i == num_children - 1,
225225
under_top_level,
226226
);
227227
}
228228
}
229229
NodeKind::SeparatedList { .. } => {
230-
for (i, child) in children.iter().enumerate() {
230+
for (i, child) in syntax_node.get_children(self.db).enumerate() {
231231
let description = if i.is_multiple_of(2) { "item" } else { "separator" };
232232
self.print_tree(
233233
format!("{description} #{}", i / 2).as_str(),
234-
child,
234+
&child,
235235
indent.as_str(),
236236
i == num_children - 1,
237237
under_top_level,
@@ -244,20 +244,20 @@ impl<'a> Printer<'a> {
244244

245245
/// Assumes children and expected children are non-empty of the same length.
246246
/// `under_top_level`: whether we are in a subtree of the top-level kind.
247-
fn print_internal_struct(
247+
fn print_internal_struct<'b>(
248248
&mut self,
249-
children: &[SyntaxNode<'_>],
249+
children: impl ExactSizeIterator<Item = SyntaxNode<'b>>,
250250
expected_children: &[Member],
251251
indent: &str,
252252
under_top_level: bool,
253253
) {
254-
let (last_child, non_last_children) = children.split_last().unwrap();
255-
let (last_expected_child, non_last_expected_children) =
256-
expected_children.split_last().unwrap();
257-
for (child, expected_child) in zip_eq(non_last_children, non_last_expected_children) {
258-
self.print_tree(&expected_child.name, child, indent, false, under_top_level);
254+
let mut iter = zip_eq(children, expected_children);
255+
for _ in 1..iter.len() {
256+
let (child, expected_child) = iter.next().unwrap();
257+
self.print_tree(&expected_child.name, &child, indent, false, under_top_level);
259258
}
260-
self.print_tree(&last_expected_child.name, last_child, indent, true, under_top_level);
259+
let (last_child, last_expected_child) = iter.next().unwrap();
260+
self.print_tree(&last_expected_child.name, &last_child, indent, true, under_top_level);
261261
}
262262

263263
fn get_node_kind(&self, name: String) -> NodeKind {

crates/cairo-lang-plugins/src/plugins/generate_trait.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,8 @@ fn generate_trait_for_impl<'db>(
184184
builder.add_node(decl.name(db).as_syntax_node());
185185
builder.add_node(decl.generic_params(db).as_syntax_node());
186186
builder.add_node(signature.lparen(db).as_syntax_node());
187-
for node in signature.parameters(db).node.get_children(db).iter() {
188-
if let Some(param) = ast::Param::cast(db, *node) {
187+
for node in signature.parameters(db).node.get_children(db) {
188+
if let Some(param) = ast::Param::cast(db, node) {
189189
for modifier in param.modifiers(db).elements(db) {
190190
// `mut` modifiers are only relevant for impls, not traits.
191191
if !matches!(modifier, ast::Modifier::Mut(_)) {
@@ -195,7 +195,7 @@ fn generate_trait_for_impl<'db>(
195195
builder.add_node(param.name(db).as_syntax_node());
196196
builder.add_node(param.type_clause(db).as_syntax_node());
197197
} else {
198-
builder.add_node(*node);
198+
builder.add_node(node);
199199
}
200200
}
201201
let rparen = signature.rparen(db);

0 commit comments

Comments
 (0)