Skip to content

Commit

Permalink
If any child has non-trivial trivia, do not sort (#6761)
Browse files Browse the repository at this point in the history
  • Loading branch information
dean-starkware authored Nov 28, 2024
1 parent a2b9ddd commit abf7c20
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions crates/cairo-lang-formatter/src/formatter_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1037,24 +1037,7 @@ impl<'a> FormatterImpl<'a> {
OrderedHashMap::default();

for node in section_nodes {
// Check if the node has any non-trivial trivia (i.e., comments).
let has_non_whitespace_trivia = !node.descendants(self.db).all(|descendant| {
if descendant.kind(self.db) == SyntaxKind::Trivia {
ast::Trivia::from_syntax_node(self.db, descendant)
.elements(self.db)
.into_iter()
.all(|element| {
matches!(
element,
ast::Trivium::Whitespace(_) | ast::Trivium::Newline(_)
)
})
} else {
true
}
});

if has_non_whitespace_trivia {
if !self.has_only_whitespace_trivia(node) {
new_children.push(node.clone());
continue;
}
Expand Down Expand Up @@ -1097,8 +1080,28 @@ impl<'a> FormatterImpl<'a> {
*children = new_children;
}

/// Returns whether the node has only whitespace trivia.
fn has_only_whitespace_trivia(&self, node: &SyntaxNode) -> bool {
node.descendants(self.db).all(|descendant| {
if descendant.kind(self.db) == SyntaxKind::Trivia {
ast::Trivia::from_syntax_node(self.db, descendant)
.elements(self.db)
.into_iter()
.all(|element| {
matches!(element, ast::Trivium::Whitespace(_) | ast::Trivium::Newline(_))
})
} else {
true
}
})
}

/// Sorting function for `UsePathMulti` children.
fn sort_inner_use_path(&self, children: &mut Vec<SyntaxNode>) {
// If any child has non-trivial trivia, do not sort.
if children.iter().any(|child| !self.has_only_whitespace_trivia(child)) {
return;
}
// Split list into `use` path parts and TokenComma.
let (mut sorted_elements, commas): (Vec<_>, Vec<_>) = std::mem::take(children)
.into_iter()
Expand Down

0 comments on commit abf7c20

Please sign in to comment.