Track formatted comments (#4979)

This commit is contained in:
Micha Reiser 2023-06-09 11:09:45 +02:00 committed by GitHub
parent 646ab64850
commit 68d52da43b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 60 additions and 85 deletions

View file

@ -1,25 +1,11 @@
use crate::comments::leading_node_comments;
use crate::prelude::*;
use crate::FormatNodeRule;
use ruff_formatter::{write, FormatRuleWithOptions};
use ruff_formatter::write;
use ruff_text_size::{TextLen, TextRange};
use rustpython_parser::ast::Arg;
#[derive(Default)]
pub struct FormatArg {
kind: ArgumentKind,
}
#[derive(Copy, Clone, Debug, Default)]
pub enum ArgumentKind {
/// Positional only, regular argument, or a keyword only argument.
#[default]
Normal,
/// A `*args` arguments
Varg,
/// A `**kwargs` argument
Kwarg,
}
pub struct FormatArg;
impl FormatNodeRule<Arg> for FormatArg {
fn fmt_fields(&self, item: &Arg, f: &mut PyFormatter) -> FormatResult<()> {
@ -46,21 +32,4 @@ impl FormatNodeRule<Arg> for FormatArg {
Ok(())
}
fn fmt_leading_comments(&self, node: &Arg, f: &mut PyFormatter) -> FormatResult<()> {
match self.kind {
ArgumentKind::Normal => leading_node_comments(node).fmt(f),
// Formatted as part of the `Arguments` to avoid emitting leading comments between the `*` and the argument.
ArgumentKind::Kwarg | ArgumentKind::Varg => Ok(()),
}
}
}
impl FormatRuleWithOptions<Arg, PyFormatContext<'_>> for FormatArg {
type Options = ArgumentKind;
fn with_options(mut self, options: Self::Options) -> Self {
self.kind = options;
self
}
}

View file

@ -1,6 +1,5 @@
use crate::comments::{dangling_node_comments, leading_node_comments};
use crate::context::NodeLevel;
use crate::other::arg::ArgumentKind;
use crate::prelude::*;
use crate::trivia::{first_non_trivia_token, SimpleTokenizer, Token, TokenKind};
use crate::FormatNodeRule;
@ -63,7 +62,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
joiner.entry(&format_args![
leading_node_comments(vararg.as_ref()),
text("*"),
vararg.format().with_options(ArgumentKind::Varg)
vararg.format()
]);
last_node = Some(vararg.as_any_node_ref());
}
@ -90,7 +89,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
joiner.entry(&format_args![
leading_node_comments(kwarg.as_ref()),
text("**"),
kwarg.format().with_options(ArgumentKind::Kwarg)
kwarg.format()
]);
last_node = Some(kwarg.as_any_node_ref());
}