mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-28 12:55:05 +00:00
Generic "comment to node" association logic (#4642)
This commit is contained in:
parent
84a5584888
commit
0cd453bdf0
29 changed files with 1574 additions and 65 deletions
50
crates/ruff_python_ast/src/source_code/comment_ranges.rs
Normal file
50
crates/ruff_python_ast/src/source_code/comment_ranges.rs
Normal file
|
@ -0,0 +1,50 @@
|
|||
use ruff_text_size::TextRange;
|
||||
use rustpython_parser::Tok;
|
||||
use std::fmt::{Debug, Formatter};
|
||||
use std::ops::Deref;
|
||||
|
||||
/// Stores the ranges of comments sorted by [`TextRange::start`] in increasing order. No two ranges are overlapping.
|
||||
#[derive(Clone)]
|
||||
pub struct CommentRanges {
|
||||
raw: Vec<TextRange>,
|
||||
}
|
||||
|
||||
impl Deref for CommentRanges {
|
||||
type Target = [TextRange];
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.raw.as_slice()
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for CommentRanges {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("CommentRanges").field(&self.raw).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a CommentRanges {
|
||||
type Item = &'a TextRange;
|
||||
type IntoIter = std::slice::Iter<'a, TextRange>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.raw.iter()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CommentRangesBuilder {
|
||||
ranges: Vec<TextRange>,
|
||||
}
|
||||
|
||||
impl CommentRangesBuilder {
|
||||
pub fn visit_token(&mut self, token: &Tok, range: TextRange) {
|
||||
if token.is_comment() {
|
||||
self.ranges.push(range);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish(self) -> CommentRanges {
|
||||
CommentRanges { raw: self.ranges }
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue