Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache node children. #4247

Merged
merged 1 commit into from
Oct 12, 2023
Merged
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
26 changes: 16 additions & 10 deletions crates/cairo-lang-defs/src/patcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,30 @@ impl RewriteNode {
match self {
RewriteNode::Copied(syntax_node) => {
*self = RewriteNode::new_modified(
syntax_node.children(db).map(RewriteNode::Copied).collect(),
db.get_children(syntax_node.clone())
.iter()
.cloned()
.map(RewriteNode::Copied)
.collect(),
);
extract_matches!(self, RewriteNode::Modified)
}

RewriteNode::Trimmed { node, trim_left, trim_right } => {
let num_children = node.children(db).len();
let children = db.get_children(node.clone());
let num_children = children.len();
let mut new_children = Vec::new();

// Get the index of the leftmost nonempty child.
let Some(left_idx) =
node.children(db).position(|child| child.width(db) != TextWidth::default())
children.iter().position(|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 = node
.children(db)
let right_idx = children
.iter()
.rposition(|child| child.width(db) != TextWidth::default())
.unwrap();
new_children.extend(itertools::repeat_n(
Expand All @@ -70,27 +75,28 @@ impl RewriteNode {

// The number of children between the first and last nonempty nodes.
let num_middle = right_idx - left_idx + 1;
let mut children_iter = node.children(db).skip(left_idx);
let children = db.get_children(node.clone());
let mut children_iter = children.iter().skip(left_idx);
match num_middle {
1 => {
new_children.push(RewriteNode::Trimmed {
node: children_iter.next().unwrap(),
node: children_iter.next().unwrap().clone(),
trim_left: *trim_left,
trim_right: *trim_right,
});
}
_ => {
new_children.push(RewriteNode::Trimmed {
node: children_iter.next().unwrap(),
node: children_iter.next().unwrap().clone(),
trim_left: *trim_left,
trim_right: false,
});
for _ in 0..(num_middle - 2) {
let child = children_iter.next().unwrap();
let child = children_iter.next().unwrap().clone();
new_children.push(RewriteNode::Copied(child));
}
new_children.push(RewriteNode::Trimmed {
node: children_iter.next().unwrap(),
node: children_iter.next().unwrap().clone(),
trim_left: false,
trim_right: *trim_right,
});
Expand Down
6 changes: 3 additions & 3 deletions crates/cairo-lang-defs/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ fn test_generic_item_id(
fn find_generics(
db: &DatabaseForTesting,
mut module_file_id: ModuleFileId,
node: SyntaxNode,
node: &SyntaxNode,
output: &mut String,
) {
match node.kind(db) {
Expand All @@ -111,11 +111,11 @@ fn test_generic_item_id(
}
_ => {}
}
for child in node.children(db) {
for child in db.get_children(node.clone()).iter() {
find_generics(db, module_file_id, child, output);
}
}
find_generics(db, module_file_id, node, &mut output);
find_generics(db, module_file_id, &node, &mut output);

TestRunnerResult::success(OrderedHashMap::from([("output".into(), output)]))
}
Expand Down
16 changes: 10 additions & 6 deletions crates/cairo-lang-formatter/src/formatter_impl.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::cmp::Ordering;
use std::fmt;
use std::ops::Deref;

use cairo_lang_filesystem::span::TextWidth;
use cairo_lang_syntax as syntax;
Expand Down Expand Up @@ -655,11 +656,13 @@ impl<'a> FormatterImpl<'a> {
let no_space_after = no_space_after || syntax_node.force_no_space_after(self.db);
let internal_break_line_points_positions =
syntax_node.get_internal_break_line_point_properties(self.db);
let mut children: Vec<SyntaxNode> = syntax_node.children(self.db).collect();

// TODO(ilya): consider not copying here.
let mut children = self.db.get_children(syntax_node.clone()).deref().clone();
let n_children = children.len();
if self.config.sort_module_level_items {
children.sort_by_key(|c| MovableNode::new(self.db, c));
}
};
for (i, child) in children.iter().enumerate() {
if child.width(self.db) == TextWidth::default() {
continue;
Expand All @@ -678,10 +681,11 @@ impl<'a> FormatterImpl<'a> {
/// Formats a terminal node and appends the formatted string to the result.
fn format_terminal(&mut self, syntax_node: &SyntaxNode, no_space_after: bool) {
// TODO(spapini): Introduce a Terminal and a Token enum in ast.rs to make this cleaner.
let mut children = syntax_node.children(self.db);
let leading_trivia = ast::Trivia::from_syntax_node(self.db, children.next().unwrap());
let token = children.next().unwrap();
let trailing_trivia = ast::Trivia::from_syntax_node(self.db, children.next().unwrap());
let children = self.db.get_children(syntax_node.clone());
let mut children_iter = children.iter().cloned();
let leading_trivia = ast::Trivia::from_syntax_node(self.db, children_iter.next().unwrap());
let token = children_iter.next().unwrap();
let trailing_trivia = ast::Trivia::from_syntax_node(self.db, children_iter.next().unwrap());

// The first newlines is the leading trivia correspond exactly to empty lines.
self.format_trivia(leading_trivia, true);
Expand Down
9 changes: 4 additions & 5 deletions crates/cairo-lang-formatter/src/node_properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,9 @@ impl SyntaxNodeFormat for SyntaxNode {
}
SyntaxKind::ExprPath
if matches!(parent_kind(db, self), Some(SyntaxKind::PatternEnum))
&& self
.parent()
.unwrap()
.children(db)
&& db
.get_children(self.parent().unwrap())
.iter()
.any(|c| c.kind(db) == SyntaxKind::PatternEnumInnerPattern) =>
{
true
Expand Down Expand Up @@ -607,7 +606,7 @@ fn is_statement_list_break_point_optional(db: &dyn SyntaxGroup, node: &SyntaxNod
// Currently, we only want single line blocks for match arms, with a single statments, with no
// single line comments.
grandparent_kind(db, node) == Some(SyntaxKind::MatchArm)
&& node.children(db).len() == 1
&& db.get_children(node.clone()).len() == 1
&& node.descendants(db).all(|d| {
d.kind(db) != SyntaxKind::Trivia
|| ast::Trivia::from_syntax_node(db, d)
Expand Down
3 changes: 2 additions & 1 deletion crates/cairo-lang-language-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ use cairo_lang_semantic::{SemanticDiagnostic, TypeLongId};
use cairo_lang_starknet::inline_macros::selector::SelectorMacro;
use cairo_lang_starknet::plugin::StarkNetPlugin;
use cairo_lang_syntax::node::ast::PathSegment;
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::helpers::GetIdentifier;
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_syntax::node::kind::SyntaxKind;
Expand Down Expand Up @@ -935,7 +936,7 @@ fn completion_kind(db: &RootDatabase, node: SyntaxNode) -> CompletionKind {
let grandparent = parent.parent().unwrap();
eprintln!("grandparent.kind: {:#?}", grandparent.kind(db));
if grandparent.kind(db) == SyntaxKind::ExprPath {
if grandparent.children(db).next().unwrap().stable_ptr() != parent.stable_ptr() {
if db.get_children(grandparent.clone())[0].stable_ptr() != parent.stable_ptr() {
// Not first segment.
eprintln!("Not first segment");
return completion_kind_from_path_node(db, grandparent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl SemanticTokensTraverser {
}
}
syntax::node::green::GreenNodeDetails::Node { .. } => {
let children = node.children(syntax_db);
let children = syntax_db.get_children(node.clone());
match green_node.kind {
SyntaxKind::Param => {
self.mark_future_token(
Expand Down Expand Up @@ -97,8 +97,8 @@ impl SemanticTokensTraverser {
),
_ => {}
}
for child in children {
self.find_semantic_tokens(db, file_id, data, child);
for child in children.iter() {
self.find_semantic_tokens(db, file_id, data, child.clone());
}
}
}
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<'a> ColoredPrinter<'a> {
} else if self.verbose && is_empty_kind(node.kind) {
self.result.push_str(format!("{}", "<e>".red()).as_str());
} else {
for child in syntax_node.children(self.db) {
self.print(&child);
for child in self.db.get_children(syntax_node.clone()).iter() {
self.print(child);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/cairo-lang-parser/src/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ impl<'a> Printer<'a> {
format!(" (kind: {kind:?})")
};

let children: Vec<_> = syntax_node.children(self.db).collect();
let children = self.db.get_children(syntax_node.clone());
let num_children = children.len();
let suffix = if self.ignored_kinds.contains(&format!("{kind:?}")) {
" <ignored>".to_string()
Expand Down
2 changes: 1 addition & 1 deletion crates/cairo-lang-plugins/src/plugins/generate_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ fn generate_trait_for_impl(db: &dyn SyntaxGroup, impl_ast: ast::ItemImpl) -> Plu
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.children(db) {
for node in db.get_children(signature.parameters(db).node.clone()).iter().cloned() {
if node.kind(db) != SyntaxKind::Param {
builder.add_node(node);
} else {
Expand Down
4 changes: 2 additions & 2 deletions crates/cairo-lang-syntax-codegen/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ fn gen_struct_code(name: String, members: Vec<Member>, is_terminal: bool) -> rus
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct $(&name){
node: SyntaxNode,
children: Vec<SyntaxNode>,
children: Arc<Vec<SyntaxNode>>,
}
$new_green_impl
impl $(&name) {
Expand Down Expand Up @@ -672,7 +672,7 @@ fn gen_struct_code(name: String, members: Vec<Member>, is_terminal: bool) -> rus
fn from_syntax_node(db: &dyn SyntaxGroup, node: SyntaxNode) -> Self {
let kind = node.kind(db);
assert_eq!(kind, SyntaxKind::$(&name), "Unexpected SyntaxKind {:?}. Expected {:?}.", kind, SyntaxKind::$(&name));
let children = node.children(db).collect();
let children = db.get_children(node.clone());
Self { node, children }
}
fn as_syntax_node(&self) -> SyntaxNode {
Expand Down
Loading