Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions crates/cairo-lang-defs/src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1635,7 +1635,7 @@ impl SyntaxNodeIdCached {
SyntaxNodeId::Root(file_id) => Self::Root(FileIdCached::new(*file_id, ctx)),
SyntaxNodeId::Child { parent, key_fields, index } => Self::Child {
parent: SyntaxNodeCached::new(*parent, ctx),
key_fields: key_fields.into_iter().map(|id| GreenIdCached::new(*id, ctx)).collect(),
key_fields: key_fields.iter().map(|id| GreenIdCached::new(*id, ctx)).collect(),
index: *index,
},
}
Expand All @@ -1646,7 +1646,9 @@ impl SyntaxNodeIdCached {
SyntaxNodeIdCached::Root(file_id) => SyntaxNodeId::Root(file_id.embed(ctx)),
SyntaxNodeIdCached::Child { parent, key_fields, index } => SyntaxNodeId::Child {
parent: parent.embed(ctx),
key_fields: Box::from_iter(key_fields.iter().map(|id| id.embed(ctx))),
key_fields: cairo_lang_syntax::node::ids::ArcGreenIds {
ids: Arc::from_iter(key_fields.iter().map(|id| id.embed(ctx))),
},
index: *index,
},
}
Expand Down
25 changes: 11 additions & 14 deletions crates/cairo-lang-defs/src/patcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,55 +65,52 @@ impl<'db> RewriteNode<'db> {
match self {
RewriteNode::Copied(syntax_node) => {
*self = RewriteNode::new_modified(
syntax_node.get_children(db).iter().copied().map(RewriteNode::Copied).collect(),
syntax_node.get_children(db).map(RewriteNode::Copied).collect(),
);
extract_matches!(self, RewriteNode::Modified)
}
RewriteNode::Trimmed { node, trim_left, trim_right } => {
let children = node.get_children(db);
let mut children = node.get_children(db).enumerate();
let num_children = children.len();
let mut new_children = Vec::new();

// Get the index of the leftmost nonempty child.
let Some(left_idx) =
children.iter().position(|child| child.width(db) != TextWidth::default())
let Some((left_idx, first_syntax)) =
children.find(|(_, child)| child.width(db) != TextWidth::default())
else {
*self = RewriteNode::Modified(ModifiedNode { children: None });
return extract_matches!(self, RewriteNode::Modified);
};
// Get the index of the rightmost nonempty child.
let right_idx = children
.iter()
.rposition(|child| child.width(db) != TextWidth::default())
.unwrap();
let (right_idx, last_syntax) = children
.rfind(|(_, child)| child.width(db) != TextWidth::default())
.unwrap_or((left_idx, first_syntax));
new_children.extend(itertools::repeat_n(
RewriteNode::Modified(ModifiedNode { children: None }),
left_idx,
));

// The number of children between the first and last nonempty nodes.
let num_middle = right_idx - left_idx + 1;
let mut children_iter = children.iter().skip(left_idx);
match num_middle {
1 => {
new_children.push(RewriteNode::Trimmed {
node: *children_iter.next().unwrap(),
node: first_syntax,
trim_left: *trim_left,
trim_right: *trim_right,
});
}
_ => {
new_children.push(RewriteNode::Trimmed {
node: *children_iter.next().unwrap(),
node: first_syntax,
trim_left: *trim_left,
trim_right: false,
});
for _ in 0..(num_middle - 2) {
let child = *children_iter.next().unwrap();
for (_, child) in children {
new_children.push(RewriteNode::Copied(child));
}
new_children.push(RewriteNode::Trimmed {
node: *children_iter.next().unwrap(),
node: last_syntax,
trim_left: false,
trim_right: *trim_right,
});
Expand Down
4 changes: 2 additions & 2 deletions crates/cairo-lang-defs/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ fn test_generic_item_id(
}
_ => {}
}
for child in node.get_children(db).iter() {
find_generics(db, module_id, child, output);
for child in node.get_children(db) {
find_generics(db, module_id, &child, output);
}
}
find_generics(&db_val, module_id, &file_syntax.as_syntax_node(), &mut output);
Expand Down
8 changes: 4 additions & 4 deletions crates/cairo-lang-doc/src/documentable_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -865,7 +865,7 @@ fn write_function_signature<'db>(

/// Retrieves [`SyntaxKind::TypeClause`] text from [`SyntaxNode`].
fn get_type_clause<'db>(syntax_node: SyntaxNode<'db>, db: &'db dyn Database) -> Option<String> {
for child in syntax_node.get_children(db).iter() {
for child in syntax_node.get_children(db) {
if child.kind(db) == SyntaxKind::TypeClause {
return Some(child.get_text_without_all_comment_trivia(db));
}
Expand Down Expand Up @@ -959,7 +959,7 @@ fn write_struct_attributes_syntax<'db>(
) -> Result<(), fmt::Error> {
for attribute in attributes {
let syntax_node = attribute.stable_ptr.lookup(f.db).as_syntax_node();
for child in syntax_node.get_children(f.db).iter() {
for child in syntax_node.get_children(f.db) {
let to_text = child.get_text_without_all_comment_trivia(f.db);
let cleaned_text = to_text.replace("\n", "");
f.write_str(&cleaned_text)?;
Expand All @@ -978,7 +978,7 @@ fn write_syntactic_evaluation<'db>(
let syntax_node = stable_location.syntax_node(f.db);
if matches!(&syntax_node.green_node(f.db).details, green::GreenNodeDetails::Node { .. }) {
let mut is_after_evaluation_value = false;
for child in syntax_node.get_children(f.db).iter() {
for child in syntax_node.get_children(f.db) {
let kind = child.kind(f.db);
if !matches!(kind, SyntaxKind::Trivia) {
if matches!(kind, SyntaxKind::TerminalSemicolon) {
Expand All @@ -987,7 +987,7 @@ fn write_syntactic_evaluation<'db>(
}
if is_after_evaluation_value {
f.buf.write_str(&SyntaxNode::get_text_without_all_comment_trivia(
child, f.db,
&child, f.db,
))?;
};
if matches!(kind, SyntaxKind::TerminalEq) {
Expand Down
4 changes: 2 additions & 2 deletions crates/cairo-lang-doc/src/location_links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ fn collect_green_nodes<'db>(
GreenNodeDetails::Token(text) => green_nodes.push((green_node.kind, text.to_string(db))),
GreenNodeDetails::Node { .. } => {
let syntax_node_children = syntax_node.get_children(db);
syntax_node_children.iter().for_each(|child| {
collect_green_nodes(db, child, green_nodes);
syntax_node_children.for_each(|child| {
collect_green_nodes(db, &child, green_nodes);
});
}
}
Expand Down
15 changes: 8 additions & 7 deletions crates/cairo-lang-formatter/src/formatter_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1033,7 +1033,7 @@ impl<'a> FormatterImpl<'a> {
let internal_break_line_points_positions =
syntax_node.get_internal_break_line_point_properties(self.db, &self.config);
// TODO(ilya): consider not copying here.
let mut children = syntax_node.get_children(self.db).to_vec();
let mut children: Vec<_> = syntax_node.get_children(self.db).collect();
let n_children = children.len();

if self.config.merge_use_items {
Expand Down Expand Up @@ -1118,8 +1118,8 @@ impl<'a> FormatterImpl<'a> {
);

// Add merged children to the new_children list.
if let Some(child) = merged_node.get_children(self.db).iter().next() {
new_children.extend(child.get_children(self.db).iter().copied());
if let Some(child) = merged_node.get_children(self.db).next() {
new_children.extend(child.get_children(self.db));
}
}
}
Expand Down Expand Up @@ -1212,15 +1212,16 @@ impl<'a> FormatterImpl<'a> {
fn format_terminal(&mut self, syntax_node: &SyntaxNode<'a>) {
// TODO(spapini): Introduce a Terminal and a Token enum in ast.rs to make this cleaner.
let children = syntax_node.get_children(self.db);
let [leading, token, trailing] = children else {
let Some([leading, token, trailing]) = children.collect_array() else {
panic!("Terminal node should have 3 children.");
};

// The first newlines is the leading trivia correspond exactly to empty lines.
self.format_trivia(ast::Trivia::from_syntax_node(self.db, *leading), true);
self.format_trivia(ast::Trivia::from_syntax_node(self.db, leading), true);
if !syntax_node.should_skip_terminal(self.db) {
self.format_token(token);
self.format_token(&token);
}
self.format_trivia(ast::Trivia::from_syntax_node(self.db, *trailing), false);
self.format_trivia(ast::Trivia::from_syntax_node(self.db, trailing), false);
}
/// Appends a trivia node (if needed) to the result.
fn format_trivia(&mut self, trivia: syntax::node::ast::Trivia<'a>, is_leading: bool) {
Expand Down
13 changes: 5 additions & 8 deletions crates/cairo-lang-formatter/src/node_properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
.parent(db)
.unwrap()
.get_children(db)
.iter()
.any(|c| c.kind(db) == SyntaxKind::PatternEnumInnerPattern) =>
{
true
Expand Down Expand Up @@ -931,8 +930,6 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
}

fn should_skip_terminal(&self, db: &dyn Database) -> bool {
let is_last =
|node: &SyntaxNode<'_>, siblings: &[SyntaxNode<'_>]| siblings.last() == Some(node);
// Check for TerminalComma with specific conditions on list types and position.
if self.kind(db) == SyntaxKind::TerminalComma
&& matches!(
Expand Down Expand Up @@ -963,7 +960,7 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
);
if (!is_expr_or_pattern_list || children.len() > 2)
// Ensure that this node is the last element in the list.
&& is_last(self, children)
&& children.last() == Some(*self)
{
return true;
}
Expand All @@ -978,11 +975,11 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
let statements_node = statement_node.parent(db).unwrap();
// Checking if not the last statement, as `;` may be there to prevent the block from
// returning the value of the current block.
let not_last = !is_last(&statement_node, statements_node.get_children(db));
let children = statement_node.get_children(db);
let statements_children = statements_node.get_children(db);
let not_last = statements_children.last() != Some(statement_node);
if not_last
&& matches!(
children[1].kind(db),
statement_node.get_child(db, 1).kind(db),
SyntaxKind::ExprBlock
| SyntaxKind::ExprIf
| SyntaxKind::ExprMatch
Expand All @@ -999,7 +996,7 @@ impl<'a> SyntaxNodeFormat for SyntaxNode<'a> {
{
let path_segment_node = self.parent(db).unwrap();
let path_node = path_segment_node.parent(db).unwrap();
if !is_last(&path_segment_node, path_node.get_children(db)) {
if path_node.get_children(db).last() != Some(path_segment_node) {
false
} else {
matches!(
Expand Down
4 changes: 2 additions & 2 deletions crates/cairo-lang-parser/src/colored_printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ impl ColoredPrinter<'_> {
} else if self.verbose && is_empty_kind(node.kind) {
self.result.push_str(format!("{}", "<e>".red()).as_str());
} else {
for child in syntax_node.get_children(self.db).iter() {
self.print(child);
for child in syntax_node.get_children(self.db) {
self.print(&child);
}
}
}
Expand Down
26 changes: 13 additions & 13 deletions crates/cairo-lang-parser/src/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,29 +209,29 @@ impl<'a> Printer<'a> {
NodeKind::Struct { members: expected_children }
| NodeKind::Terminal { members: expected_children, .. } => {
self.print_internal_struct(
children,
syntax_node.get_children(self.db),
&expected_children,
indent.as_str(),
under_top_level,
);
}
NodeKind::List { .. } => {
for (i, child) in children.iter().enumerate() {
for (i, child) in syntax_node.get_children(self.db).enumerate() {
self.print_tree(
format!("child #{i}").as_str(),
child,
&child,
indent.as_str(),
i == num_children - 1,
under_top_level,
);
}
}
NodeKind::SeparatedList { .. } => {
for (i, child) in children.iter().enumerate() {
for (i, child) in syntax_node.get_children(self.db).enumerate() {
let description = if i.is_multiple_of(2) { "item" } else { "separator" };
self.print_tree(
format!("{description} #{}", i / 2).as_str(),
child,
&child,
indent.as_str(),
i == num_children - 1,
under_top_level,
Expand All @@ -244,20 +244,20 @@ impl<'a> Printer<'a> {

/// Assumes children and expected children are non-empty of the same length.
/// `under_top_level`: whether we are in a subtree of the top-level kind.
fn print_internal_struct(
fn print_internal_struct<'b>(
&mut self,
children: &[SyntaxNode<'_>],
mut children: impl ExactSizeIterator<Item = SyntaxNode<'b>> + DoubleEndedIterator,
expected_children: &[Member],
indent: &str,
under_top_level: bool,
) {
let (last_child, non_last_children) = children.split_last().unwrap();
let (last_expected_child, non_last_expected_children) =
expected_children.split_last().unwrap();
for (child, expected_child) in zip_eq(non_last_children, non_last_expected_children) {
self.print_tree(&expected_child.name, child, indent, false, under_top_level);
let mut expected_children = expected_children.iter();
let last_child = children.next_back().unwrap();
let last_expected_child = expected_children.next_back().unwrap();
for (child, expected_child) in zip_eq(children, expected_children) {
self.print_tree(&expected_child.name, &child, indent, false, under_top_level);
}
self.print_tree(&last_expected_child.name, last_child, indent, true, under_top_level);
self.print_tree(&last_expected_child.name, &last_child, indent, true, under_top_level);
}

fn get_node_kind(&self, name: String) -> NodeKind {
Expand Down
6 changes: 3 additions & 3 deletions crates/cairo-lang-plugins/src/plugins/generate_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,8 @@ fn generate_trait_for_impl<'db>(
builder.add_node(decl.name(db).as_syntax_node());
builder.add_node(decl.generic_params(db).as_syntax_node());
builder.add_node(signature.lparen(db).as_syntax_node());
for node in signature.parameters(db).node.get_children(db).iter() {
if let Some(param) = ast::Param::cast(db, *node) {
for node in signature.parameters(db).node.get_children(db) {
if let Some(param) = ast::Param::cast(db, node) {
for modifier in param.modifiers(db).elements(db) {
// `mut` modifiers are only relevant for impls, not traits.
if !matches!(modifier, ast::Modifier::Mut(_)) {
Expand All @@ -195,7 +195,7 @@ fn generate_trait_for_impl<'db>(
builder.add_node(param.name(db).as_syntax_node());
builder.add_node(param.type_clause(db).as_syntax_node());
} else {
builder.add_node(*node);
builder.add_node(node);
}
}
let rparen = signature.rparen(db);
Expand Down
12 changes: 6 additions & 6 deletions crates/cairo-lang-semantic/src/items/macro_declaration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,8 @@ fn collect_expansion_placeholders<'db>(
return placeholders;
}
if !node.kind(db).is_terminal() {
for child in node.get_children(db).iter() {
placeholders.extend(collect_expansion_placeholders(db, *child));
for child in node.get_children(db) {
placeholders.extend(collect_expansion_placeholders(db, child));
}
}
placeholders
Expand Down Expand Up @@ -571,8 +571,8 @@ fn expand_macro_rule_ex(
return Ok(());
}

for child in node.get_children(db).iter() {
expand_macro_rule_ex(db, *child, matcher_ctx, res_buffer, code_mappings)?;
for child in node.get_children(db) {
expand_macro_rule_ex(db, child, matcher_ctx, res_buffer, code_mappings)?;
}
return Ok(());
}
Expand All @@ -581,8 +581,8 @@ fn expand_macro_rule_ex(
res_buffer.push_str(node.get_text(db));
return Ok(());
}
for child in node.get_children(db).iter() {
expand_macro_rule_ex(db, *child, matcher_ctx, res_buffer, code_mappings)?;
for child in node.get_children(db) {
expand_macro_rule_ex(db, child, matcher_ctx, res_buffer, code_mappings)?;
}
Ok(())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -792,9 +792,9 @@ fn try_extract_named_macro_argument<'db>(
return Some(path);
}
let segments = path.segments(db);
let mut elements = segments.elements(db);
let elements = segments.elements(db);
if elements.len() != 1
|| !matches!(elements.next_back().unwrap(), ast::PathSegment::Simple(_))
|| !matches!(elements.last().unwrap(), ast::PathSegment::Simple(_))
{
diagnostics.push(PluginDiagnostic::error_with_inner_span(
db,
Expand Down
2 changes: 1 addition & 1 deletion crates/cairo-lang-syntax-codegen/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,7 @@ fn gen_struct_code(name: String, members: Vec<Member>, is_terminal: bool) -> rus
params.extend(quote! {$name: $(&child_green)<'db>,});
body.extend(quote! {
pub fn $name(&self, db: &'db dyn Database) -> $kind<'db> {
$kind::from_syntax_node(db, self.node.get_children(db)[$i])
$kind::from_syntax_node(db, self.node.get_child(db, $i))
}
});
args_for_missing.extend(quote! {$kind::missing(db).0,});
Expand Down
Loading