Move has_comments to CommentRanges (#11495)

## Summary

This PR moves the `has_comments` function from `Indexer` to
`CommentRanges`. The main motivation is that the `CommentRanges` will
now be built by the parser which is shared between the linter and the
formatter. Thus, the `CommentRanges` will be removed from the `Indexer`.

## Test Plan

`cargo test`
This commit is contained in:
Dhruv Manilawala 2024-05-22 19:05:16 +05:30 committed by GitHub
parent 5bb9720a10
commit f0046ab28e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 65 additions and 29 deletions

View file

@ -6,7 +6,7 @@ use ruff_source_file::Locator;
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::is_python_whitespace;
use crate::{has_leading_content, has_trailing_content, is_python_whitespace};
/// Stores the ranges of comments sorted by [`TextRange::start`] in increasing order. No two ranges are overlapping.
#[derive(Clone, Default)]
@ -49,6 +49,25 @@ impl CommentRanges {
}
}
/// Returns `true` if a statement or expression includes at least one comment.
pub fn has_comments<T>(&self, node: &T, locator: &Locator) -> bool
where
T: Ranged,
{
let start = if has_leading_content(node.start(), locator) {
node.start()
} else {
locator.line_start(node.start())
};
let end = if has_trailing_content(node.end(), locator) {
node.end()
} else {
locator.line_end(node.end())
};
self.intersects(TextRange::new(start, end))
}
/// Given a [`CommentRanges`], determine which comments are grouped together
/// in "comment blocks". A "comment block" is a sequence of consecutive
/// own-line comments in which the comment hash (`#`) appears in the same