Generic "comment to node" association logic (#4642)

This commit is contained in:
Micha Reiser 2023-05-30 11:28:01 +02:00 committed by GitHub
parent 84a5584888
commit 0cd453bdf0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 1574 additions and 65 deletions

View file

@ -1,24 +1,40 @@
use crate::comments::Comments;
use ruff_formatter::{FormatContext, SimpleFormatOptions, SourceCode};
use ruff_python_ast::source_code::Locator;
use std::fmt::{Debug, Formatter};
#[derive(Clone, Debug)]
pub struct ASTFormatContext<'source> {
#[derive(Clone)]
pub struct ASTFormatContext<'a> {
options: SimpleFormatOptions,
contents: &'source str,
contents: &'a str,
comments: Comments<'a>,
}
impl<'source> ASTFormatContext<'source> {
pub fn new(options: SimpleFormatOptions, contents: &'source str) -> Self {
Self { options, contents }
impl<'a> ASTFormatContext<'a> {
pub(crate) fn new(
options: SimpleFormatOptions,
contents: &'a str,
comments: Comments<'a>,
) -> Self {
Self {
options,
contents,
comments,
}
}
pub fn contents(&self) -> &'source str {
pub fn contents(&self) -> &'a str {
self.contents
}
pub fn locator(&self) -> Locator<'source> {
pub fn locator(&self) -> Locator<'a> {
Locator::new(self.contents)
}
#[allow(unused)]
pub(crate) fn comments(&self) -> &Comments<'a> {
&self.comments
}
}
impl FormatContext for ASTFormatContext<'_> {
@ -32,3 +48,13 @@ impl FormatContext for ASTFormatContext<'_> {
SourceCode::new(self.contents)
}
}
impl Debug for ASTFormatContext<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ASTFormatContext")
.field("options", &self.options)
.field("comments", &self.comments.debug(self.source_code()))
.field("source", &self.contents)
.finish()
}
}