repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/string/normalize.rs
crates/ruff_python_formatter/src/string/normalize.rs
use std::borrow::Cow; use std::cmp::Ordering; use std::iter::FusedIterator; use ruff_formatter::FormatContext; use ruff_python_ast::visitor::source_order::SourceOrderVisitor; use ruff_python_ast::{ AnyStringFlags, BytesLiteral, FString, InterpolatedStringElement, InterpolatedStringElements, StringFlags, StringLikePart, StringLiteral, }; use ruff_text_size::{Ranged, TextRange, TextSlice}; use crate::QuoteStyle; use crate::context::InterpolatedStringState; use crate::prelude::*; use crate::string::{Quote, StringQuotes, TripleQuotes}; pub(crate) struct StringNormalizer<'a, 'src> { preferred_quote_style: Option<QuoteStyle>, context: &'a PyFormatContext<'src>, } impl<'a, 'src> StringNormalizer<'a, 'src> { pub(crate) fn from_context(context: &'a PyFormatContext<'src>) -> Self { Self { preferred_quote_style: None, context, } } pub(crate) fn with_preferred_quote_style(mut self, quote_style: QuoteStyle) -> Self { self.preferred_quote_style = Some(quote_style); self } /// Determines the preferred quote style for `string`. /// The formatter should use the preferred quote style unless /// it can't because the string contains the preferred quotes OR /// it leads to more escaping. /// /// Note: If you add more cases here where we return `QuoteStyle::Preserve`, make sure to also /// add them to /// [`FormatImplicitConcatenatedStringFlat::new`](crate::string::implicit::FormatImplicitConcatenatedStringFlat::new). pub(super) fn preferred_quote_style(&self, string: StringLikePart) -> QuoteStyle { let preferred_quote_style = self .preferred_quote_style .unwrap_or(self.context.options().quote_style()); let supports_pep_701 = self.context.options().target_version().supports_pep_701(); // Preserve the existing quote style for nested interpolations more than one layer deep, if // PEP 701 isn't supported. if !supports_pep_701 && self.context.interpolated_string_state().is_nested() { return QuoteStyle::Preserve; } // For f-strings and t-strings prefer alternating the quotes unless The outer string is triple quoted and the inner isn't. if let InterpolatedStringState::InsideInterpolatedElement(parent_context) | InterpolatedStringState::NestedInterpolatedElement(parent_context) = self.context.interpolated_string_state() { let parent_flags = parent_context.flags(); if !parent_flags.is_triple_quoted() || string.flags().is_triple_quoted() { // This logic is even necessary when using preserve and the target python version doesn't support PEP701 because // we might end up joining two f-strings that have different quote styles, in which case we need to alternate the quotes // for inner strings to avoid a syntax error: `string = "this is my string with " f'"{params.get("mine")}"'` if !preferred_quote_style.is_preserve() || !supports_pep_701 { return QuoteStyle::from(parent_flags.quote_style().opposite()); } } } // Leave the quotes unchanged for all other strings. if preferred_quote_style.is_preserve() { return QuoteStyle::Preserve; } // There are cases where it is necessary to preserve the quotes to prevent an invalid f-string or t-string. match string { StringLikePart::FString(fstring) => { // There are two cases where it's necessary to preserve the quotes if the // target version is pre 3.12 and the part is an f-string. if !supports_pep_701 { // An f-string expression contains a debug text with a quote character // because the formatter will emit the debug expression **exactly** the // same as in the source text. if is_fstring_with_quoted_debug_expression(fstring, self.context) { return QuoteStyle::Preserve; } // An f-string expression that contains a triple quoted string literal // expression that contains a quote. if is_fstring_with_triple_quoted_literal_expression_containing_quotes( fstring, self.context, ) { return QuoteStyle::Preserve; } } // An f-string expression element contains a debug text and the corresponding // format specifier has a literal element with a quote character. if is_interpolated_string_with_quoted_format_spec_and_debug( &fstring.elements, fstring.flags.into(), self.context, ) { return QuoteStyle::Preserve; } } StringLikePart::TString(tstring) => { if is_interpolated_string_with_quoted_format_spec_and_debug( &tstring.elements, tstring.flags.into(), self.context, ) { return QuoteStyle::Preserve; } } _ => {} } // Per PEP 8, always prefer double quotes for triple-quoted strings. if string.flags().is_triple_quoted() { // ... unless we're formatting a code snippet inside a docstring, // then we specifically want to invert our quote style to avoid // writing out invalid Python. // // It's worth pointing out that we can actually wind up being // somewhat out of sync with PEP8 in this case. Consider this // example: // // def foo(): // ''' // Something. // // >>> """tricksy""" // ''' // pass // // Ideally, this would be reformatted as: // // def foo(): // """ // Something. // // >>> '''tricksy''' // """ // pass // // But the logic here results in the original quoting being // preserved. This is because the quoting style of the outer // docstring is determined, in part, by looking at its contents. In // this case, it notices that it contains a `"""` and thus infers // that using `'''` would overall read better because it avoids // the need to escape the interior `"""`. Except... in this case, // the `"""` is actually part of a code snippet that could get // reformatted to using a different quoting style itself. // // Fixing this would, I believe, require some fairly seismic // changes to how formatting strings works. Namely, we would need // to look for code snippets before normalizing the docstring, and // then figure out the quoting style more holistically by looking // at the various kinds of quotes used in the code snippets and // what reformatting them might look like. // // Overall this is a bit of a corner case and just inverting the // style from what the parent ultimately decided upon works, even // if it doesn't have perfect alignment with PEP8. if let Some(quote) = self.context.docstring() { QuoteStyle::from(quote.opposite()) } else { QuoteStyle::Double } } else { preferred_quote_style } } /// Computes the strings preferred quotes. pub(crate) fn choose_quotes(&self, string: StringLikePart) -> QuoteSelection { let raw_content = &self.context.source()[string.content_range()]; let first_quote_or_normalized_char_offset = raw_content .bytes() .position(|b| matches!(b, b'\\' | b'"' | b'\'' | b'\r')); let string_flags = string.flags(); let preferred_style = self.preferred_quote_style(string); let new_kind = match ( Quote::try_from(preferred_style), first_quote_or_normalized_char_offset, ) { // The string contains no quotes so it's safe to use the preferred quote style (Ok(preferred_quote), None) => string_flags.with_quote_style(preferred_quote), // The preferred quote style is single or double quotes, and the string contains a quote or // another character that may require escaping (Ok(preferred_quote), Some(first_quote_or_normalized_char_offset)) => { let metadata = if string.is_interpolated_string() { QuoteMetadata::from_part(string, self.context, preferred_quote) } else { QuoteMetadata::from_str( &raw_content[first_quote_or_normalized_char_offset..], string.flags(), preferred_quote, ) }; let quote = metadata.choose(preferred_quote); string_flags.with_quote_style(quote) } // The preferred quote style is to preserve the quotes, so let's do that. (Err(()), _) => string_flags, }; QuoteSelection { flags: new_kind, first_quote_or_normalized_char_offset, } } /// Computes the strings preferred quotes and normalizes its content. pub(crate) fn normalize(&self, string: StringLikePart) -> NormalizedString<'src> { let raw_content = &self.context.source()[string.content_range()]; let quote_selection = self.choose_quotes(string); let normalized = if let Some(first_quote_or_escape_offset) = quote_selection.first_quote_or_normalized_char_offset { normalize_string( raw_content, first_quote_or_escape_offset, quote_selection.flags, false, ) } else { Cow::Borrowed(raw_content) }; NormalizedString { flags: quote_selection.flags, content_range: string.content_range(), text: normalized, } } } #[derive(Debug)] pub(crate) struct QuoteSelection { flags: AnyStringFlags, /// Offset to the first quote character or character that needs special handling in [`normalize_string`]. first_quote_or_normalized_char_offset: Option<usize>, } impl QuoteSelection { pub(crate) fn flags(&self) -> AnyStringFlags { self.flags } } #[derive(Clone, Debug)] pub(crate) struct QuoteMetadata { kind: QuoteMetadataKind, /// The quote style in the source. source_style: Quote, } /// Tracks information about the used quotes in a string which is used /// to choose the quotes for a part. impl QuoteMetadata { pub(crate) fn from_part( part: StringLikePart, context: &PyFormatContext, preferred_quote: Quote, ) -> Self { match part { StringLikePart::String(_) | StringLikePart::Bytes(_) => { let text = &context.source()[part.content_range()]; Self::from_str(text, part.flags(), preferred_quote) } StringLikePart::FString(fstring) => { let metadata = QuoteMetadata::from_str("", part.flags(), preferred_quote); metadata.merge_interpolated_string_elements( &fstring.elements, fstring.flags.into(), context, preferred_quote, ) } StringLikePart::TString(tstring) => { let metadata = QuoteMetadata::from_str("", part.flags(), preferred_quote); metadata.merge_interpolated_string_elements( &tstring.elements, tstring.flags.into(), context, preferred_quote, ) } } } pub(crate) fn from_str(text: &str, flags: AnyStringFlags, preferred_quote: Quote) -> Self { let kind = if flags.is_raw_string() { QuoteMetadataKind::raw(text, preferred_quote, flags.triple_quotes()) } else if flags.is_triple_quoted() { QuoteMetadataKind::triple_quoted(text, preferred_quote) } else { QuoteMetadataKind::regular(text) }; Self { kind, source_style: flags.quote_style(), } } pub(super) fn choose(&self, preferred_quote: Quote) -> Quote { match self.kind { QuoteMetadataKind::Raw { contains_preferred } => { if contains_preferred { self.source_style } else { preferred_quote } } QuoteMetadataKind::Triple { contains_preferred } => { if contains_preferred { self.source_style } else { preferred_quote } } QuoteMetadataKind::Regular { single_quotes, double_quotes, } => match single_quotes.cmp(&double_quotes) { Ordering::Less => Quote::Single, Ordering::Equal => preferred_quote, Ordering::Greater => Quote::Double, }, } } /// Merges the quotes metadata of different literals. /// /// ## Raw and triple quoted strings /// Merging raw and triple quoted strings is only correct if all literals are from the same part. /// E.g. it's okay to merge triple and raw strings from a single `FString` part's literals /// but it isn't safe to merge raw and triple quoted strings from different parts of an implicit /// concatenated string. Where safe means, it may lead to incorrect results. pub(super) fn merge(self, other: &QuoteMetadata) -> Option<QuoteMetadata> { let kind = match (self.kind, other.kind) { ( QuoteMetadataKind::Regular { single_quotes: self_single, double_quotes: self_double, }, QuoteMetadataKind::Regular { single_quotes: other_single, double_quotes: other_double, }, ) => QuoteMetadataKind::Regular { single_quotes: self_single + other_single, double_quotes: self_double + other_double, }, // Can't merge quotes from raw strings (even when both strings are raw) ( QuoteMetadataKind::Raw { contains_preferred: self_contains_preferred, }, QuoteMetadataKind::Raw { contains_preferred: other_contains_preferred, }, ) => QuoteMetadataKind::Raw { contains_preferred: self_contains_preferred || other_contains_preferred, }, ( QuoteMetadataKind::Triple { contains_preferred: self_contains_preferred, }, QuoteMetadataKind::Triple { contains_preferred: other_contains_preferred, }, ) => QuoteMetadataKind::Triple { contains_preferred: self_contains_preferred || other_contains_preferred, }, (_, _) => return None, }; Some(Self { kind, source_style: self.source_style, }) } /// For f-strings and t-strings, only consider the quotes inside string-literals but ignore /// quotes inside expressions (except inside the format spec). This allows both the outer and the nested literals /// to make the optimal local-choice to reduce the total number of quotes necessary. /// This doesn't require any pre 312 special handling because an expression /// can never contain the outer quote character, not even escaped: /// ```python /// f"{'escaping a quote like this \" is a syntax error pre 312'}" /// ``` fn merge_interpolated_string_elements( self, elements: &InterpolatedStringElements, flags: AnyStringFlags, context: &PyFormatContext, preferred_quote: Quote, ) -> Self { let mut merged = self; for element in elements { match element { InterpolatedStringElement::Literal(literal) => { merged = merged .merge(&QuoteMetadata::from_str( context.source().slice(literal), flags, preferred_quote, )) .expect("Merge to succeed because all parts have the same flags"); } InterpolatedStringElement::Interpolation(expression) => { if let Some(spec) = expression.format_spec.as_deref() { if expression.debug_text.is_none() { merged = merged.merge_interpolated_string_elements( &spec.elements, flags, context, preferred_quote, ); } } } } } merged } } #[derive(Copy, Clone, Debug)] enum QuoteMetadataKind { /// A raw string. /// /// For raw strings it's only possible to change the quotes if the preferred quote style /// isn't used inside the string. Raw { contains_preferred: bool }, /// Regular (non raw) triple quoted string. /// /// For triple quoted strings it's only possible to change the quotes if no /// triple of the preferred quotes is used inside the string. Triple { contains_preferred: bool }, /// A single quoted string that uses either double or single quotes. /// /// For regular strings it's desired to pick the quote style that requires the least escaping. /// E.g. pick single quotes for `'A "dog"'` because using single quotes would require escaping /// the two `"`. Regular { single_quotes: u32, double_quotes: u32, }, } impl QuoteMetadataKind { /// For triple quoted strings, the preferred quote style can't be used if the string contains /// a tripled of the quote character (e.g., if double quotes are preferred, double quotes will be /// used unless the string contains `"""`). fn triple_quoted(content: &str, preferred_quote: Quote) -> Self { // True if the string contains a triple quote sequence of the configured quote style. let mut uses_triple_quotes = false; let mut chars = content.chars().peekable(); while let Some(c) = chars.next() { let preferred_quote_char = preferred_quote.as_char(); match c { '\\' => { if matches!(chars.peek(), Some('"' | '\\')) { chars.next(); } } // `"` or `'` c if c == preferred_quote_char => { match chars.peek().copied() { Some(c) if c == preferred_quote_char => { // `""` or `''` chars.next(); match chars.peek().copied() { Some(c) if c == preferred_quote_char => { // `"""` or `'''` chars.next(); uses_triple_quotes = true; break; } Some(_) => {} None => { // Handle `''' ""'''`. At this point we have consumed both // double quotes, so on the next iteration the iterator is empty // and we'd miss the string ending with a preferred quote uses_triple_quotes = true; break; } } } Some(_) => { // A single quote char, this is ok } None => { // Trailing quote at the end of the comment uses_triple_quotes = true; break; } } } _ => continue, } } Self::Triple { contains_preferred: uses_triple_quotes, } } /// For single quoted strings, the preferred quote style is used, unless the alternative quote style /// would require fewer escapes. fn regular(text: &str) -> Self { let mut single_quotes = 0u32; let mut double_quotes = 0u32; for c in text.chars() { match c { '\'' => { single_quotes += 1; } '"' => { double_quotes += 1; } _ => continue, } } Self::Regular { single_quotes, double_quotes, } } /// Computes if a raw string uses the preferred quote. If it does, then it's not possible /// to change the quote style because it would require escaping which isn't possible in raw strings. fn raw(text: &str, preferred: Quote, triple_quotes: TripleQuotes) -> Self { let mut chars = text.chars().peekable(); let preferred_quote_char = preferred.as_char(); let contains_unescaped_configured_quotes = loop { match chars.next() { Some('\\') => { // Ignore escaped characters chars.next(); } // `"` or `'` Some(c) if c == preferred_quote_char => { if triple_quotes.is_no() { break true; } match chars.peek() { // We can't turn `r'''\""'''` into `r"""\"""""`, this would confuse the parser // about where the closing triple quotes start None => break true, Some(next) if *next == preferred_quote_char => { // `""` or `''` chars.next(); // We can't turn `r'''""'''` into `r""""""""`, nor can we have // `"""` or `'''` respectively inside the string if chars.peek().is_none() || chars.peek() == Some(&preferred_quote_char) { break true; } } _ => {} } } Some(_) => continue, None => break false, } }; Self::Raw { contains_preferred: contains_unescaped_configured_quotes, } } } #[derive(Debug)] pub(crate) struct NormalizedString<'a> { /// Holds data about the quotes and prefix of the string flags: AnyStringFlags, /// The range of the string's content in the source (minus prefix and quotes). content_range: TextRange, /// The normalized text text: Cow<'a, str>, } impl<'a> NormalizedString<'a> { pub(crate) fn text(&self) -> &Cow<'a, str> { &self.text } pub(crate) fn flags(&self) -> AnyStringFlags { self.flags } } impl Ranged for NormalizedString<'_> { fn range(&self) -> TextRange { self.content_range } } impl Format<PyFormatContext<'_>> for NormalizedString<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { let quotes = StringQuotes::from(self.flags); ruff_formatter::write!(f, [self.flags.prefix(), quotes])?; match &self.text { Cow::Borrowed(_) => source_text_slice(self.range()).fmt(f)?, Cow::Owned(normalized) => text(normalized).fmt(f)?, } quotes.fmt(f) } } pub(crate) fn normalize_string( input: &str, start_offset: usize, new_flags: AnyStringFlags, escape_braces: bool, ) -> Cow<'_, str> { // The normalized string if `input` is not yet normalized. // `output` must remain empty if `input` is already normalized. let mut output = String::new(); // Tracks the last index of `input` that has been written to `output`. // If `last_index` is `0` at the end, then the input is already normalized and can be returned as is. let mut last_index = 0; let quote = new_flags.quote_style(); let preferred_quote = quote.as_char(); let opposite_quote = quote.opposite().as_char(); let mut chars = CharIndicesWithOffset::new(input, start_offset).peekable(); let is_raw = new_flags.is_raw_string(); while let Some((index, c)) = chars.next() { if matches!(c, '{' | '}') { if escape_braces { // Escape `{` and `}` when converting a regular string literal to an f-string literal. output.push_str(&input[last_index..=index]); output.push(c); last_index = index + c.len_utf8(); continue; } } if c == '\r' { output.push_str(&input[last_index..index]); // Skip over the '\r' character, keep the `\n` if chars.peek().copied().is_some_and(|(_, next)| next == '\n') { chars.next(); } // Replace the `\r` with a `\n` else { output.push('\n'); } last_index = index + '\r'.len_utf8(); } else if !is_raw { if c == '\\' { if let Some((_, next)) = chars.clone().next() { if next == '\\' { // Skip over escaped backslashes chars.next(); } else { // Length of the `\` plus the length of the escape sequence character (`u` | `U` | `x`) let escape_start_len = '\\'.len_utf8() + next.len_utf8(); if let Some(normalised) = UnicodeEscape::new(next, !new_flags.is_byte_string()).and_then( |escape| escape.normalize(&input[index + escape_start_len..]), ) { let escape_start_offset = index + escape_start_len; if let Cow::Owned(normalised) = &normalised { output.push_str(&input[last_index..escape_start_offset]); output.push_str(normalised); last_index = escape_start_offset + normalised.len(); } // Move the `chars` iterator passed the escape sequence. // Simply reassigning `chars` doesn't work because the indices` would // then be off. for _ in 0..next.len_utf8() + normalised.len() { chars.next(); } } } if !new_flags.is_triple_quoted() { if next == opposite_quote { // Remove the escape by ending before the backslash and starting again with the quote chars.next(); output.push_str(&input[last_index..index]); last_index = index + '\\'.len_utf8(); } else if next == preferred_quote { // Quote is already escaped, skip over it. chars.next(); } } } } else if !new_flags.is_triple_quoted() && c == preferred_quote { // Escape the quote output.push_str(&input[last_index..index]); output.push('\\'); output.push(c); last_index = index + preferred_quote.len_utf8(); } } } if last_index == 0 { Cow::Borrowed(input) } else { output.push_str(&input[last_index..]); Cow::Owned(output) } } #[derive(Clone, Debug)] struct CharIndicesWithOffset<'str> { chars: std::str::Chars<'str>, next_offset: usize, } impl<'str> CharIndicesWithOffset<'str> { fn new(input: &'str str, start_offset: usize) -> Self { Self { chars: input[start_offset..].chars(), next_offset: start_offset, } } } impl Iterator for CharIndicesWithOffset<'_> { type Item = (usize, char); fn next(&mut self) -> Option<Self::Item> { self.chars.next().map(|c| { let index = self.next_offset; self.next_offset += c.len_utf8(); (index, c) }) } } impl FusedIterator for CharIndicesWithOffset<'_> {} #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum UnicodeEscape { /// A hex escape sequence of either 2 (`\x`), 4 (`\u`) or 8 (`\U`) hex characters. Hex(usize), /// An escaped unicode name (`\N{name}`) CharacterName, } impl UnicodeEscape { fn new(first: char, allow_unicode: bool) -> Option<UnicodeEscape> { Some(match first { 'x' => UnicodeEscape::Hex(2), 'u' if allow_unicode => UnicodeEscape::Hex(4), 'U' if allow_unicode => UnicodeEscape::Hex(8), 'N' if allow_unicode => UnicodeEscape::CharacterName, _ => return None, }) } /// Normalises `\u..`, `\U..`, `\x..` and `\N{..}` escape sequences to: /// /// * `\u`, `\U'` and `\x`: To use lower case for the characters `a-f`. /// * `\N`: To use uppercase letters fn normalize(self, input: &str) -> Option<Cow<'_, str>> { let mut normalised = String::new(); let len = match self { UnicodeEscape::Hex(len) => { // It's not a valid escape sequence if the input string has fewer characters // left than required by the escape sequence. if input.len() < len { return None; } for (index, c) in input.char_indices().take(len) { match c { '0'..='9' | 'a'..='f' => { if !normalised.is_empty() { normalised.push(c); } } 'A'..='F' => { if normalised.is_empty() { normalised.reserve(len); normalised.push_str(&input[..index]); normalised.push(c.to_ascii_lowercase()); } else { normalised.push(c.to_ascii_lowercase()); } } _ => { // not a valid escape sequence return None; } } } len } UnicodeEscape::CharacterName => { let mut char_indices = input.char_indices(); if !matches!(char_indices.next(), Some((_, '{'))) { return None; } loop {
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/type_param/type_param_param_spec.rs
crates/ruff_python_formatter/src/type_param/type_param_param_spec.rs
use ruff_formatter::write; use ruff_python_ast::TypeParamParamSpec; use crate::prelude::*; #[derive(Default)] pub struct FormatTypeParamParamSpec; impl FormatNodeRule<TypeParamParamSpec> for FormatTypeParamParamSpec { fn fmt_fields(&self, item: &TypeParamParamSpec, f: &mut PyFormatter) -> FormatResult<()> { let TypeParamParamSpec { range: _, node_index: _, name, default, } = item; write!(f, [token("**"), name.format()])?; if let Some(default) = default { write!(f, [space(), token("="), space(), default.format()])?; } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/type_param/type_param_type_var_tuple.rs
crates/ruff_python_formatter/src/type_param/type_param_type_var_tuple.rs
use ruff_formatter::write; use ruff_python_ast::TypeParamTypeVarTuple; use crate::prelude::*; #[derive(Default)] pub struct FormatTypeParamTypeVarTuple; impl FormatNodeRule<TypeParamTypeVarTuple> for FormatTypeParamTypeVarTuple { fn fmt_fields(&self, item: &TypeParamTypeVarTuple, f: &mut PyFormatter) -> FormatResult<()> { let TypeParamTypeVarTuple { range: _, node_index: _, name, default, } = item; write!(f, [token("*"), name.format()])?; if let Some(default) = default { write!(f, [space(), token("="), space(), default.format()])?; } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/type_param/type_params.rs
crates/ruff_python_formatter/src/type_param/type_params.rs
use ruff_formatter::FormatResult; use ruff_python_ast::TypeParams; use ruff_text_size::Ranged; use crate::builders::PyFormatterExtensions; use crate::expression::parentheses::parenthesized; use crate::prelude::*; #[derive(Default)] pub struct FormatTypeParams; /// Formats a sequence of [`TypeParam`](ruff_python_ast::TypeParam) nodes. impl FormatNodeRule<TypeParams> for FormatTypeParams { fn fmt_fields(&self, item: &TypeParams, f: &mut PyFormatter) -> FormatResult<()> { // A dangling comment indicates a comment on the same line as the opening bracket, e.g.: // ```python // type foo[ # This type parameter clause has a dangling comment. // a, // b, // c, // ] = ... let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(item); let items = format_with(|f| { f.join_comma_separated(item.end()) .nodes(item.type_params.iter()) .finish() }); parenthesized("[", &items, "]") .with_dangling_comments(dangling_comments) .fmt(f) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/type_param/mod.rs
crates/ruff_python_formatter/src/type_param/mod.rs
use ruff_formatter::{FormatOwnedWithRule, FormatRefWithRule}; use ruff_python_ast::TypeParam; use crate::prelude::*; pub(crate) mod type_param_param_spec; pub(crate) mod type_param_type_var; pub(crate) mod type_param_type_var_tuple; pub(crate) mod type_params; #[derive(Default)] pub struct FormatTypeParam; impl FormatRule<TypeParam, PyFormatContext<'_>> for FormatTypeParam { fn fmt(&self, item: &TypeParam, f: &mut PyFormatter) -> FormatResult<()> { match item { TypeParam::TypeVar(x) => x.format().fmt(f), TypeParam::TypeVarTuple(x) => x.format().fmt(f), TypeParam::ParamSpec(x) => x.format().fmt(f), } } } impl<'ast> AsFormat<PyFormatContext<'ast>> for TypeParam { type Format<'a> = FormatRefWithRule<'a, TypeParam, FormatTypeParam, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatTypeParam) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for TypeParam { type Format = FormatOwnedWithRule<TypeParam, FormatTypeParam, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatTypeParam) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/type_param/type_param_type_var.rs
crates/ruff_python_formatter/src/type_param/type_param_type_var.rs
use ruff_formatter::write; use ruff_python_ast::TypeParamTypeVar; use crate::prelude::*; #[derive(Default)] pub struct FormatTypeParamTypeVar; impl FormatNodeRule<TypeParamTypeVar> for FormatTypeParamTypeVar { fn fmt_fields(&self, item: &TypeParamTypeVar, f: &mut PyFormatter) -> FormatResult<()> { let TypeParamTypeVar { range: _, node_index: _, name, bound, default, } = item; name.format().fmt(f)?; if let Some(bound) = bound { write!(f, [token(":"), space(), bound.format()])?; } if let Some(default) = default { write!(f, [space(), token("="), space(), default.format()])?; } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_try.rs
crates/ruff_python_formatter/src/statement/stmt_try.rs
use ruff_formatter::{FormatRuleWithOptions, write}; use ruff_python_ast::{ExceptHandler, StmtTry}; use ruff_text_size::Ranged; use crate::comments; use crate::comments::SourceComment; use crate::comments::leading_alternate_branch_comments; use crate::other::except_handler_except_handler::{ ExceptHandlerKind, FormatExceptHandlerExceptHandler, }; use crate::prelude::*; use crate::statement::clause::{ClauseHeader, ElseClause, clause}; use crate::statement::suite::SuiteKind; use crate::statement::{FormatRefWithRule, Stmt}; #[derive(Default)] pub struct FormatStmtTry; #[derive(Copy, Clone, Default)] pub struct FormatExceptHandler { except_handler_kind: ExceptHandlerKind, last_suite_in_statement: bool, } impl FormatRuleWithOptions<ExceptHandler, PyFormatContext<'_>> for FormatExceptHandler { type Options = FormatExceptHandler; fn with_options(mut self, options: Self::Options) -> Self { self.except_handler_kind = options.except_handler_kind; self.last_suite_in_statement = options.last_suite_in_statement; self } } impl FormatRule<ExceptHandler, PyFormatContext<'_>> for FormatExceptHandler { fn fmt(&self, item: &ExceptHandler, f: &mut PyFormatter) -> FormatResult<()> { match item { ExceptHandler::ExceptHandler(except_handler) => except_handler .format() .with_options(FormatExceptHandlerExceptHandler { except_handler_kind: self.except_handler_kind, last_suite_in_statement: self.last_suite_in_statement, }) .fmt(f), } } } impl<'ast> AsFormat<PyFormatContext<'ast>> for ExceptHandler { type Format<'a> = FormatRefWithRule<'a, ExceptHandler, FormatExceptHandler, PyFormatContext<'ast>> where Self: 'a; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatExceptHandler::default()) } } impl FormatNodeRule<StmtTry> for FormatStmtTry { fn fmt_fields(&self, item: &StmtTry, f: &mut PyFormatter) -> FormatResult<()> { let StmtTry { body, handlers, orelse, finalbody, is_star, range: _, node_index: _, } = item; let comments_info = f.context().comments().clone(); let mut dangling_comments = comments_info.dangling(item); (_, dangling_comments) = format_case(item, CaseKind::Try, None, dangling_comments, false, f)?; let mut previous_node = body.last(); for handler in handlers { let handler_comments = comments_info.leading(handler); let ExceptHandler::ExceptHandler(except_handler) = handler; let except_handler_kind = if *is_star { ExceptHandlerKind::Starred } else { ExceptHandlerKind::Regular }; let last_suite_in_statement = handler == handlers.last().unwrap() && orelse.is_empty() && finalbody.is_empty(); write!( f, [ leading_alternate_branch_comments(handler_comments, previous_node), &handler.format().with_options(FormatExceptHandler { except_handler_kind, last_suite_in_statement }) ] )?; previous_node = except_handler.body.last(); } (previous_node, dangling_comments) = format_case( item, CaseKind::Else, previous_node, dangling_comments, finalbody.is_empty(), f, )?; format_case( item, CaseKind::Finally, previous_node, dangling_comments, true, f, )?; write!(f, [comments::dangling_comments(dangling_comments)]) } } fn format_case<'a>( try_statement: &'a StmtTry, kind: CaseKind, previous_node: Option<&'a Stmt>, dangling_comments: &'a [SourceComment], last_suite_in_statement: bool, f: &mut PyFormatter, ) -> FormatResult<(Option<&'a Stmt>, &'a [SourceComment])> { let body = match kind { CaseKind::Try => &try_statement.body, CaseKind::Else => &try_statement.orelse, CaseKind::Finally => &try_statement.finalbody, }; Ok(if let Some(last) = body.last() { let case_comments_start = dangling_comments.partition_point(|comment| comment.end() <= last.end()); let (case_comments, rest) = dangling_comments.split_at(case_comments_start); let partition_point = case_comments.partition_point(|comment| comment.line_position().is_own_line()); let (leading_case_comments, trailing_case_comments) = case_comments.split_at(partition_point); let header = match kind { CaseKind::Try => ClauseHeader::Try(try_statement), CaseKind::Else => ClauseHeader::OrElse(ElseClause::Try(try_statement)), CaseKind::Finally => ClauseHeader::TryFinally(try_statement), }; write!( f, [clause( header, &token(kind.keyword()), trailing_case_comments, body, SuiteKind::other(last_suite_in_statement), ) .with_leading_comments(leading_case_comments, previous_node),] )?; (Some(last), rest) } else { (previous_node, dangling_comments) }) } #[derive(Copy, Clone)] enum CaseKind { Try, Else, Finally, } impl CaseKind { fn keyword(self) -> &'static str { match self { CaseKind::Try => "try", CaseKind::Else => "else", CaseKind::Finally => "finally", } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_expr.rs
crates/ruff_python_formatter/src/statement/stmt_expr.rs
use ruff_python_ast as ast; use ruff_python_ast::{Expr, Operator, StmtExpr}; use crate::comments::SourceComment; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::statement::trailing_semicolon; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtExpr; impl FormatNodeRule<StmtExpr> for FormatStmtExpr { fn fmt_fields(&self, item: &StmtExpr, f: &mut PyFormatter) -> FormatResult<()> { let StmtExpr { value, .. } = item; if is_arithmetic_like(value) { maybe_parenthesize_expression(value, item, Parenthesize::Optional).fmt(f)?; } else { value.format().fmt(f)?; } if f.options().source_type().is_ipynb() && f.context().node_level().is_last_top_level_statement() && trailing_semicolon(item.into(), f.context().source()).is_some() { token(";").fmt(f)?; } Ok(()) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } } const fn is_arithmetic_like(expression: &Expr) -> bool { matches!( expression, Expr::BinOp(ast::ExprBinOp { op: Operator::BitOr | Operator::BitXor | Operator::LShift | Operator::RShift | Operator::Add | Operator::Sub, .. }) ) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_break.rs
crates/ruff_python_formatter/src/statement/stmt_break.rs
use ruff_python_ast::StmtBreak; use crate::comments::SourceComment; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtBreak; impl FormatNodeRule<StmtBreak> for FormatStmtBreak { fn fmt_fields(&self, _item: &StmtBreak, f: &mut PyFormatter) -> FormatResult<()> { token("break").fmt(f) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_delete.rs
crates/ruff_python_formatter/src/statement/stmt_delete.rs
use ruff_formatter::write; use ruff_python_ast::StmtDelete; use ruff_text_size::Ranged; use crate::builders::{PyFormatterExtensions, parenthesize_if_expands}; use crate::comments::{SourceComment, dangling_node_comments}; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtDelete; impl FormatNodeRule<StmtDelete> for FormatStmtDelete { fn fmt_fields(&self, item: &StmtDelete, f: &mut PyFormatter) -> FormatResult<()> { let StmtDelete { range: _, node_index: _, targets, } = item; write!(f, [token("del"), space()])?; match targets.as_slice() { [] => { write!( f, [ // Handle special case of delete statements without targets. // ``` // del ( // # Dangling comment // ) token("("), block_indent(&dangling_node_comments(item)), token(")"), ] ) } [single] => { write!( f, [maybe_parenthesize_expression( single, item, Parenthesize::IfBreaks )] ) } targets => { let item = format_with(|f| { f.join_comma_separated(item.end()) .nodes(targets.iter()) .finish() }); parenthesize_if_expands(&item).fmt(f) } } } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_pass.rs
crates/ruff_python_formatter/src/statement/stmt_pass.rs
use ruff_python_ast::StmtPass; use crate::comments::SourceComment; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtPass; impl FormatNodeRule<StmtPass> for FormatStmtPass { fn fmt_fields(&self, _item: &StmtPass, f: &mut PyFormatter) -> FormatResult<()> { token("pass").fmt(f) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/suite.rs
crates/ruff_python_formatter/src/statement/suite.rs
use ruff_formatter::{ FormatContext, FormatOwnedWithRule, FormatRefWithRule, FormatRuleWithOptions, write, }; use ruff_python_ast::helpers::is_compound_statement; use ruff_python_ast::{self as ast, Expr, PySourceType, Stmt, Suite}; use ruff_python_ast::{AnyNodeRef, StmtExpr}; use ruff_python_trivia::{lines_after, lines_after_ignoring_end_of_line_trivia, lines_before}; use ruff_text_size::{Ranged, TextRange}; use crate::comments::{ Comments, LeadingDanglingTrailingComments, leading_comments, trailing_comments, }; use crate::context::{NodeLevel, TopLevelStatementPosition, WithIndentLevel, WithNodeLevel}; use crate::other::string_literal::StringLiteralKind; use crate::prelude::*; use crate::preview::{ is_allow_newline_after_block_open_enabled, is_blank_line_before_decorated_class_in_stub_enabled, }; use crate::statement::stmt_expr::FormatStmtExpr; use crate::verbatim::{ suppressed_node, write_suppressed_statements_starting_with_leading_comment, write_suppressed_statements_starting_with_trailing_comment, }; /// Level at which the [`Suite`] appears in the source code. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum SuiteKind { /// Statements at the module level / top level TopLevel, /// Statements in a function body. Function, /// Statements in a class body. Class, /// Statements in any other body (e.g., `if` or `while`). Other { /// Whether this suite is the last suite in the current statement. /// /// Below, `last_suite_in_statement` is `false` for the suite containing `foo10` and `foo12` /// and `true` for the suite containing `bar`. /// ```python /// if sys.version_info >= (3, 10): /// def foo10(): /// return "new" /// elif sys.version_info >= (3, 12): /// def foo12(): /// return "new" /// else: /// def bar(): /// return "old" /// ``` /// /// When this value is true, we don't insert trailing empty lines since the containing suite /// will do that. last_suite_in_statement: bool, }, } impl Default for SuiteKind { fn default() -> Self { Self::Other { // For stability, we can't insert an empty line if we don't know if the outer suite // also does. last_suite_in_statement: true, } } } impl SuiteKind { /// See [`SuiteKind::Other`]. pub fn other(last_suite_in_statement: bool) -> Self { Self::Other { last_suite_in_statement, } } pub fn last_suite_in_statement(self) -> bool { match self { Self::Other { last_suite_in_statement, } => last_suite_in_statement, _ => true, } } } #[derive(Debug, Default)] pub struct FormatSuite { kind: SuiteKind, } impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite { fn fmt(&self, statements: &Suite, f: &mut PyFormatter) -> FormatResult<()> { let mut iter = statements.iter(); let Some(first) = iter.next() else { return Ok(()); }; let node_level = match self.kind { SuiteKind::TopLevel => NodeLevel::TopLevel( iter.clone() .next() .map_or(TopLevelStatementPosition::Last, |_| { TopLevelStatementPosition::Other }), ), SuiteKind::Function | SuiteKind::Class | SuiteKind::Other { .. } => { NodeLevel::CompoundStatement } }; let comments = f.context().comments().clone(); let source = f.context().source(); let source_type = f.options().source_type(); let f = WithNodeLevel::new(node_level, f); let f = &mut WithIndentLevel::new(f.context().indent_level().increment(), f); // Format the first statement in the body, which often has special formatting rules. let first = match self.kind { SuiteKind::Other { .. } => { if is_class_or_function_definition(first) && !comments.has_leading(first) && !source_type.is_stub() { // Add an empty line for any nested functions or classes defined within // non-function or class compound statements, e.g., this is stable formatting: // ```python // if True: // // def test(): // ... // ``` empty_line().fmt(f)?; } SuiteChildStatement::Other(first) } SuiteKind::Function | SuiteKind::Class | SuiteKind::TopLevel => { if let Some(docstring) = DocstringStmt::try_from_statement(first, self.kind, f.context()) { SuiteChildStatement::Docstring(docstring) } else { SuiteChildStatement::Other(first) } } }; let first_comments = comments.leading_dangling_trailing(first); let (mut preceding, mut empty_line_after_docstring) = if first_comments .leading .iter() .any(|comment| comment.is_suppression_off_comment(source)) { ( write_suppressed_statements_starting_with_leading_comment(first, &mut iter, f)?, false, ) } else if first_comments .trailing .iter() .any(|comment| comment.is_suppression_off_comment(source)) { ( write_suppressed_statements_starting_with_trailing_comment(first, &mut iter, f)?, false, ) } else { // Allow an empty line after a function header in preview, if the function has no // docstring and no initial comment. let allow_newline_after_block_open = is_allow_newline_after_block_open_enabled(f.context()) && matches!(self.kind, SuiteKind::Function) && matches!(first, SuiteChildStatement::Other(_)); let start = comments .leading(first) .first() .map_or_else(|| first.start(), Ranged::start); if allow_newline_after_block_open && lines_before(start, f.context().source()) > 1 { empty_line().fmt(f)?; } first.fmt(f)?; let empty_line_after_docstring = if matches!(first, SuiteChildStatement::Docstring(_)) && self.kind == SuiteKind::Class { true } else { // Insert a newline after a module level docstring, but treat // it as a docstring otherwise. See: https://github.com/psf/black/pull/3932. self.kind == SuiteKind::TopLevel && DocstringStmt::try_from_statement(first.statement(), self.kind, f.context()) .is_some() }; (first.statement(), empty_line_after_docstring) }; let mut preceding_comments = comments.leading_dangling_trailing(preceding); while let Some(following) = iter.next() { if self.kind == SuiteKind::TopLevel && iter.clone().next().is_none() { f.context_mut() .set_node_level(NodeLevel::TopLevel(TopLevelStatementPosition::Last)); } let following_comments = comments.leading_dangling_trailing(following); let needs_empty_lines = if is_class_or_function_definition(following) { // Here we insert empty lines even if the preceding has a trailing own line comment true } else { trailing_function_or_class_def(Some(preceding), &comments).is_some() }; // Add empty lines before and after a function or class definition. If the preceding // node is a function or class, and contains trailing comments, then the statement // itself will add the requisite empty lines when formatting its comments. if needs_empty_lines { if source_type.is_stub() { stub_file_empty_lines( self.kind, preceding, following, &preceding_comments, &following_comments, f, )?; } else { // Preserve empty lines after a stub implementation but don't insert a new one if there isn't any present in the source. // This is useful when having multiple function overloads that should be grouped together by omitting new lines between them. let is_preceding_stub_function_without_empty_line = following .is_function_def_stmt() && preceding .as_function_def_stmt() .is_some_and(|preceding_stub| { contains_only_an_ellipsis( &preceding_stub.body, f.context().comments(), ) && lines_after_ignoring_end_of_line_trivia( preceding_stub.end(), f.context().source(), ) < 2 }) && !preceding_comments.has_trailing_own_line(); if !is_preceding_stub_function_without_empty_line { match self.kind { SuiteKind::TopLevel => { write!(f, [empty_line(), empty_line()])?; } SuiteKind::Function | SuiteKind::Class | SuiteKind::Other { .. } => { empty_line().fmt(f)?; } } } } } else if is_import_definition(preceding) && (!is_import_definition(following) || following_comments.has_leading()) { // Enforce _at least_ one empty line after an import statement (but allow up to // two at the top-level). In this context, "after an import statement" means that // that the previous node is an import, and the following node is an import _or_ has // a leading comment. match self.kind { SuiteKind::TopLevel => { let end = if let Some(last_trailing) = preceding_comments.trailing.last() { last_trailing.end() } else { preceding.end() }; match lines_after(end, source) { 0..=2 => empty_line().fmt(f)?, _ => match source_type { PySourceType::Stub => { empty_line().fmt(f)?; } PySourceType::Python | PySourceType::Ipynb => { write!(f, [empty_line(), empty_line()])?; } }, } } SuiteKind::Function | SuiteKind::Class | SuiteKind::Other { .. } => { empty_line().fmt(f)?; } } } else if is_compound_statement(preceding) { // Handles the case where a body has trailing comments. The issue is that RustPython does not include // the comments in the range of the suite. This means, the body ends right after the last statement in the body. // ```python // def test(): // ... // # The body of `test` ends right after `...` and before this comment // // # leading comment // // // a = 10 // ``` // Using `lines_after` for the node doesn't work because it would count the lines after the `...` // which is 0 instead of 1, the number of lines between the trailing comment and // the leading comment. This is why the suite handling counts the lines before the // start of the next statement or before the first leading comments for compound statements. let start = if let Some(first_leading) = following_comments.leading.first() { first_leading.start() } else { following.start() }; match lines_before(start, source) { 0 | 1 => hard_line_break().fmt(f)?, 2 => empty_line().fmt(f)?, _ => match self.kind { SuiteKind::TopLevel => match source_type { PySourceType::Stub => { empty_line().fmt(f)?; } PySourceType::Python | PySourceType::Ipynb => { write!(f, [empty_line(), empty_line()])?; } }, SuiteKind::Function | SuiteKind::Class | SuiteKind::Other { .. } => { empty_line().fmt(f)?; } }, } } else if empty_line_after_docstring { // Enforce an empty line after a class docstring, e.g., these are both stable // formatting: // ```python // class Test: // """Docstring""" // // ... // // // class Test: // // """Docstring""" // // ... // ``` empty_line().fmt(f)?; } else { // Insert the appropriate number of empty lines based on the node level, e.g.: // * [`NodeLevel::Module`]: Up to two empty lines // * [`NodeLevel::CompoundStatement`]: Up to one empty line // * [`NodeLevel::Expression`]: No empty lines // It's necessary to skip any trailing line comment because our parser doesn't // include trailing comments in the node's range: // ```python // a # The range of `a` ends right before this comment // // b // ``` let end = preceding_comments .trailing .last() .map_or(preceding.end(), |comment| comment.slice().end()); match node_level { NodeLevel::TopLevel(_) => match lines_after(end, source) { 0 | 1 => hard_line_break().fmt(f)?, 2 => empty_line().fmt(f)?, _ => match source_type { PySourceType::Stub => { empty_line().fmt(f)?; } PySourceType::Python | PySourceType::Ipynb => { write!(f, [empty_line(), empty_line()])?; } }, }, NodeLevel::CompoundStatement => match lines_after(end, source) { 0 | 1 => hard_line_break().fmt(f)?, _ => empty_line().fmt(f)?, }, NodeLevel::Expression(_) | NodeLevel::ParenthesizedExpression => { hard_line_break().fmt(f)?; } } } if following_comments .leading .iter() .any(|comment| comment.is_suppression_off_comment(source)) { preceding = write_suppressed_statements_starting_with_leading_comment( SuiteChildStatement::Other(following), &mut iter, f, )?; preceding_comments = comments.leading_dangling_trailing(preceding); } else if following_comments .trailing .iter() .any(|comment| comment.is_suppression_off_comment(source)) { preceding = write_suppressed_statements_starting_with_trailing_comment( SuiteChildStatement::Other(following), &mut iter, f, )?; preceding_comments = comments.leading_dangling_trailing(preceding); } else { following.format().fmt(f)?; preceding = following; preceding_comments = following_comments; } empty_line_after_docstring = false; } self.between_alternative_blocks_empty_line(statements, &comments, f)?; Ok(()) } } impl FormatSuite { /// Add an empty line between a function or class and an alternative body. /// /// We only insert an empty if we're between suites in a multi-suite statement. In the /// if-else-statement below, we insert an empty line after the `foo` in the if-block, but none /// after the else-block `foo`, since in the latter case the enclosing suite already adds /// empty lines. /// /// ```python /// if sys.version_info >= (3, 10): /// def foo(): /// return "new" /// else: /// def foo(): /// return "old" /// class Bar: /// pass /// ``` fn between_alternative_blocks_empty_line( &self, statements: &Suite, comments: &Comments, f: &mut PyFormatter, ) -> FormatResult<()> { if self.kind.last_suite_in_statement() { // If we're at the end of the current statement, the outer suite will insert one or // two empty lines already. return Ok(()); } let Some(last_def_or_class) = trailing_function_or_class_def(statements.last(), comments) else { // An empty line is only inserted for function and class definitions. return Ok(()); }; // Skip the last trailing own line comment of the suite, if any, otherwise we count // the lines wrongly by stopping at that comment. let node_with_last_trailing_comment = std::iter::successors( statements.last().map(AnyNodeRef::from), AnyNodeRef::last_child_in_body, ) .find(|last_child| comments.has_trailing_own_line(*last_child)); let end_of_def_or_class = node_with_last_trailing_comment .and_then(|child| comments.trailing(child).last().map(Ranged::end)) .unwrap_or(last_def_or_class.end()); let existing_newlines = lines_after_ignoring_end_of_line_trivia(end_of_def_or_class, f.context().source()); if existing_newlines < 2 { if f.context().is_preview() { empty_line().fmt(f)?; } else { if last_def_or_class.is_stmt_class_def() && f.options().source_type().is_stub() { empty_line().fmt(f)?; } } } Ok(()) } } /// Find nested class or function definitions that need an empty line after them. /// /// ```python /// def f(): /// if True: /// /// def double(s): /// return s + s /// /// print("below function") /// ``` fn trailing_function_or_class_def<'a>( preceding: Option<&'a Stmt>, comments: &Comments, ) -> Option<AnyNodeRef<'a>> { std::iter::successors( preceding.map(AnyNodeRef::from), AnyNodeRef::last_child_in_body, ) .take_while(|last_child| // If there is a comment between preceding and following the empty lines were // inserted before the comment by preceding and there are no extra empty lines // after the comment. // ```python // class Test: // def a(self): // pass // # trailing comment // // // # two lines before, one line after // // c = 30 // ```` // This also includes nested class/function definitions, so we stop recursing // once we see a node with a trailing own line comment: // ```python // def f(): // if True: // // def double(s): // return s + s // // # nested trailing own line comment // print("below function with trailing own line comment") // ``` !comments.has_trailing_own_line(*last_child)) .find(|last_child| { matches!( last_child, AnyNodeRef::StmtFunctionDef(_) | AnyNodeRef::StmtClassDef(_) ) }) } /// Stub files have bespoke rules for empty lines. /// /// These rules are ported from black (preview mode at time of writing) using the stubs test case: /// <https://github.com/psf/black/blob/c160e4b7ce30c661ac4f2dfa5038becf1b8c5c33/src/black/lines.py#L576-L744> fn stub_file_empty_lines( kind: SuiteKind, preceding: &Stmt, following: &Stmt, preceding_comments: &LeadingDanglingTrailingComments, following_comments: &LeadingDanglingTrailingComments, f: &mut PyFormatter, ) -> FormatResult<()> { let source = f.context().source(); // Preserve the empty line if the definitions are separated by a comment let empty_line_condition = preceding_comments.has_trailing() || following_comments.has_leading() || !stub_suite_can_omit_empty_line(preceding, following, f); let require_empty_line = should_insert_blank_line_after_class_in_stub_file( preceding.into(), Some(following.into()), f.context(), ); match kind { SuiteKind::TopLevel => { if empty_line_condition || require_empty_line { empty_line().fmt(f) } else { hard_line_break().fmt(f) } } SuiteKind::Class | SuiteKind::Other { .. } | SuiteKind::Function => { if (empty_line_condition && lines_after_ignoring_end_of_line_trivia(preceding.end(), source) > 1) || require_empty_line { empty_line().fmt(f) } else { hard_line_break().fmt(f) } } } } /// Checks if an empty line should be inserted after a class definition. /// /// This is only valid if the [`blank_line_after_nested_stub_class`](https://github.com/astral-sh/ruff/issues/8891) /// preview rule is enabled and the source to be formatted is a stub file. /// /// If `following` is `None`, then the preceding node is the last one in a suite. The /// caller needs to make sure that the suite which the preceding node is part of is /// followed by an alternate branch and shouldn't be a top-level suite. pub(crate) fn should_insert_blank_line_after_class_in_stub_file( preceding: AnyNodeRef<'_>, following: Option<AnyNodeRef<'_>>, context: &PyFormatContext, ) -> bool { if !context.options().source_type().is_stub() { return false; } let Some(following) = following else { // We handle newlines at the end of a suite in `between_alternative_blocks_empty_line`. return false; }; let comments = context.comments(); match preceding.as_stmt_class_def() { Some(class) if contains_only_an_ellipsis(&class.body, comments) => { // If the preceding class has decorators, then we need to add an empty // line even if it only contains ellipsis. // // ```python // class Top: // @decorator // class Nested1: ... // foo = 1 // ``` let preceding_has_decorators = !class.decorator_list.is_empty(); // If the following statement is a class definition, then an empty line // should be inserted if it (1) doesn't just contain ellipsis, or (2) has decorators. // // ```python // class Top: // class Nested1: ... // class Nested2: // pass // // class Top: // class Nested1: ... // @decorator // class Nested2: ... // ``` // // Both of the above examples should add a blank line in between. let following_is_class_without_only_ellipsis_or_has_decorators = following.as_stmt_class_def().is_some_and(|following| { !contains_only_an_ellipsis(&following.body, comments) || !following.decorator_list.is_empty() }); preceding_has_decorators || following_is_class_without_only_ellipsis_or_has_decorators || following.is_stmt_function_def() } Some(_) => { // Preceding statement is a class definition whose body isn't only an ellipsis. // Here, we should only add a blank line if the class doesn't have a trailing // own line comment as that's handled by the class formatting itself. !comments.has_trailing_own_line(preceding) } None => { // If preceding isn't a class definition, let's check if the last statement // in the body, going all the way down, is a class definition. // // ```python // if foo: // if bar: // class Nested: // pass // if other: // pass // ``` // // But, if it contained a trailing own line comment, then it's handled // by the class formatting itself. // // ```python // if foo: // if bar: // class Nested: // pass // # comment // if other: // pass // ``` std::iter::successors( preceding.last_child_in_body(), AnyNodeRef::last_child_in_body, ) .take_while(|last_child| !comments.has_trailing_own_line(*last_child)) .any(|last_child| last_child.is_stmt_class_def()) } } } /// Only a function to compute it lazily fn stub_suite_can_omit_empty_line(preceding: &Stmt, following: &Stmt, f: &PyFormatter) -> bool { // Two subsequent class definitions that both have an ellipsis only body // ```python // class A: ... // class B: ... // // @decorator // class C: ... // ``` let class_sequences_with_ellipsis_only = preceding .as_class_def_stmt() .is_some_and(|class| contains_only_an_ellipsis(&class.body, f.context().comments())) && following.as_class_def_stmt().is_some_and(|class| { contains_only_an_ellipsis(&class.body, f.context().comments()) && class.decorator_list.is_empty() }); // Black for some reasons accepts decorators in place of empty lines // ```python // def _count1(): ... // @final // class LockType1: ... // // def _count2(): ... // // class LockType2: ... // ``` // // However, this behavior is incorrect and should not be replicated in preview mode. // See: https://github.com/astral-sh/ruff/issues/18865 let class_decorator_instead_of_empty_line = !is_blank_line_before_decorated_class_in_stub_enabled(f.context()) && preceding.is_function_def_stmt() && following .as_class_def_stmt() .is_some_and(|class| !class.decorator_list.is_empty()); // A function definition following a stub function definition // ```python // def test(): ... // def b(): a // ``` let function_with_ellipsis = preceding .as_function_def_stmt() .is_some_and(|function| contains_only_an_ellipsis(&function.body, f.context().comments())) && following.is_function_def_stmt(); class_sequences_with_ellipsis_only || class_decorator_instead_of_empty_line || function_with_ellipsis } /// Returns `true` if a function or class body contains only an ellipsis with no comments. pub(crate) fn contains_only_an_ellipsis(body: &[Stmt], comments: &Comments) -> bool { as_only_an_ellipsis(body, comments).is_some() } /// Returns `Some(Stmt::Ellipsis)` if a function or class body contains only an ellipsis with no /// comments. pub(crate) fn as_only_an_ellipsis<'a>(body: &'a [Stmt], comments: &Comments) -> Option<&'a Stmt> { if let [node @ Stmt::Expr(ast::StmtExpr { value, .. })] = body && value.is_ellipsis_literal_expr() && !comments.has_leading(node) && !comments.has_trailing_own_line(node) { return Some(node); } None } /// Returns `true` if a [`Stmt`] is a class or function definition. const fn is_class_or_function_definition(stmt: &Stmt) -> bool { matches!(stmt, Stmt::FunctionDef(_) | Stmt::ClassDef(_)) } /// Returns `true` if a [`Stmt`] is an import. const fn is_import_definition(stmt: &Stmt) -> bool { matches!(stmt, Stmt::Import(_) | Stmt::ImportFrom(_)) } impl FormatRuleWithOptions<Suite, PyFormatContext<'_>> for FormatSuite { type Options = SuiteKind; fn with_options(mut self, options: Self::Options) -> Self { self.kind = options; self } } impl<'ast> AsFormat<PyFormatContext<'ast>> for Suite { type Format<'a> = FormatRefWithRule<'a, Suite, FormatSuite, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatSuite::default()) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for Suite { type Format = FormatOwnedWithRule<Suite, FormatSuite, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatSuite::default()) } } /// A statement representing a docstring. #[derive(Copy, Clone, Debug)] pub(crate) struct DocstringStmt<'a> { /// The [`Stmt::Expr`] docstring: &'a Stmt, /// The parent suite kind suite_kind: SuiteKind, } impl<'a> DocstringStmt<'a> { /// Checks if the statement is a simple string that can be formatted as a docstring fn try_from_statement( stmt: &'a Stmt, suite_kind: SuiteKind, context: &PyFormatContext, ) -> Option<DocstringStmt<'a>> { // Notebooks don't have a concept of modules, therefore, don't recognise the first string as the module docstring. if context.options().source_type().is_ipynb() && suite_kind == SuiteKind::TopLevel { return None; } Self::is_docstring_statement(stmt.as_expr_stmt()?, context).then_some(DocstringStmt { docstring: stmt, suite_kind, }) } pub(crate) fn is_docstring_statement(stmt: &StmtExpr, context: &PyFormatContext) -> bool { if let Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) = stmt.value.as_ref() { !value.is_implicit_concatenated() || !value.iter().any(|literal| context.comments().has(literal)) } else { false } } } impl Format<PyFormatContext<'_>> for DocstringStmt<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { let comments = f.context().comments().clone(); let node_comments = comments.leading_dangling_trailing(self.docstring); if FormatStmtExpr.is_suppressed(node_comments.trailing, f.context()) { suppressed_node(self.docstring).fmt(f) } else {
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_function_def.rs
crates/ruff_python_formatter/src/statement/stmt_function_def.rs
use crate::comments::format::{ empty_lines_after_leading_comments, empty_lines_before_trailing_comments, }; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::{Parentheses, Parenthesize}; use crate::prelude::*; use crate::statement::clause::{ClauseHeader, clause}; use crate::statement::stmt_class_def::FormatDecorators; use crate::statement::suite::SuiteKind; use ruff_formatter::write; use ruff_python_ast::{NodeKind, StmtFunctionDef}; #[derive(Default)] pub struct FormatStmtFunctionDef; impl FormatNodeRule<StmtFunctionDef> for FormatStmtFunctionDef { fn fmt_fields(&self, item: &StmtFunctionDef, f: &mut PyFormatter) -> FormatResult<()> { let StmtFunctionDef { decorator_list, body, .. } = item; let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(item); let trailing_definition_comments_start = dangling_comments.partition_point(|comment| comment.line_position().is_own_line()); let (leading_definition_comments, trailing_definition_comments) = dangling_comments.split_at(trailing_definition_comments_start); // If the class contains leading comments, insert newlines before them. // For example, given: // ```python // # comment // // def func(): // ... // ``` // // At the top-level in a non-stub file, reformat as: // ```python // # comment // // // def func(): // ... // ``` // Note that this is only really relevant for the specific case in which there's a single // newline between the comment and the node, but we _require_ two newlines. If there are // _no_ newlines between the comment and the node, we don't insert _any_ newlines; if there // are more than two, then `leading_comments` will preserve the correct number of newlines. empty_lines_after_leading_comments(comments.leading(item)).fmt(f)?; write!( f, [ FormatDecorators { decorators: decorator_list, leading_definition_comments, }, clause( ClauseHeader::Function(item), &format_with(|f| format_function_header(f, item)), trailing_definition_comments, body, SuiteKind::Function, ), ] )?; // If the function contains trailing comments, insert newlines before them. // For example, given: // ```python // def func(): // ... // # comment // ``` // // At the top-level in a non-stub file, reformat as: // ```python // def func(): // ... // // // # comment // ``` empty_lines_before_trailing_comments(comments.trailing(item), NodeKind::StmtFunctionDef) .fmt(f) } } fn format_function_header(f: &mut PyFormatter, item: &StmtFunctionDef) -> FormatResult<()> { let StmtFunctionDef { range: _, node_index: _, is_async, decorator_list: _, name, type_params, parameters, returns, body: _, } = item; let comments = f.context().comments().clone(); if *is_async { write!(f, [token("async"), space()])?; } write!(f, [token("def"), space(), name.format()])?; if let Some(type_params) = type_params.as_ref() { type_params.format().fmt(f)?; } let format_inner = format_with(|f: &mut PyFormatter| { parameters.format().fmt(f)?; if let Some(return_annotation) = returns.as_deref() { write!(f, [space(), token("->"), space()])?; if return_annotation.is_tuple_expr() { let parentheses = if comments.has_leading(return_annotation) { Parentheses::Always } else { Parentheses::Never }; return_annotation.format().with_options(parentheses).fmt(f) } else if comments.has_trailing(return_annotation) { // Intentionally parenthesize any return annotations with trailing comments. // This avoids an instability in cases like: // ```python // def double( // a: int // ) -> ( // int # Hello // ): // pass // ``` // If we allow this to break, it will be formatted as follows: // ```python // def double( // a: int // ) -> int: # Hello // pass // ``` // On subsequent formats, the `# Hello` will be interpreted as a dangling // comment on a function, yielding: // ```python // def double(a: int) -> int: # Hello // pass // ``` // Ideally, we'd reach that final formatting in a single pass, but doing so // requires that the parent be aware of how the child is formatted, which // is challenging. As a compromise, we break those expressions to avoid an // instability. return_annotation .format() .with_options(Parentheses::Always) .fmt(f) } else { let parenthesize = if parameters.is_empty() && !comments.has(parameters.as_ref()) { // If the parameters are empty, add parentheses around literal expressions // (any non splitable expression) but avoid parenthesizing subscripts and // other parenthesized expressions unless necessary. Parenthesize::IfBreaksParenthesized } else { // Otherwise, use our normal rules for parentheses, which allows us to break // like: // ```python // def f( // x, // ) -> Tuple[ // int, // int, // ]: // ... // ``` Parenthesize::IfBreaks }; maybe_parenthesize_expression(return_annotation, item, parenthesize).fmt(f) } } else { Ok(()) } }); group(&format_inner).fmt(f) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_raise.rs
crates/ruff_python_formatter/src/statement/stmt_raise.rs
use ruff_formatter::write; use ruff_python_ast::StmtRaise; use crate::comments::SourceComment; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtRaise; impl FormatNodeRule<StmtRaise> for FormatStmtRaise { fn fmt_fields(&self, item: &StmtRaise, f: &mut PyFormatter) -> FormatResult<()> { let StmtRaise { range: _, node_index: _, exc, cause, } = item; token("raise").fmt(f)?; if let Some(value) = exc { write!( f, [ space(), maybe_parenthesize_expression(value, item, Parenthesize::Optional) ] )?; } if let Some(value) = cause { write!( f, [ space(), token("from"), space(), maybe_parenthesize_expression(value, item, Parenthesize::Optional) ] )?; } Ok(()) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_if.rs
crates/ruff_python_formatter/src/statement/stmt_if.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::{AnyNodeRef, ElifElseClause, StmtIf}; use ruff_text_size::Ranged; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::prelude::*; use crate::statement::clause::{ClauseHeader, clause}; use crate::statement::suite::SuiteKind; #[derive(Default)] pub struct FormatStmtIf; impl FormatNodeRule<StmtIf> for FormatStmtIf { fn fmt_fields(&self, item: &StmtIf, f: &mut PyFormatter) -> FormatResult<()> { let StmtIf { range: _, node_index: _, test, body, elif_else_clauses, } = item; let comments = f.context().comments().clone(); let trailing_colon_comment = comments.dangling(item); write!( f, [clause( ClauseHeader::If(item), &format_args![ token("if"), space(), maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks), ], trailing_colon_comment, body, SuiteKind::other(elif_else_clauses.is_empty()), )] )?; let mut last_node = body.last().unwrap().into(); for clause in elif_else_clauses { format_elif_else_clause( clause, f, Some(last_node), SuiteKind::other(clause == elif_else_clauses.last().unwrap()), )?; last_node = clause.body.last().unwrap().into(); } Ok(()) } } /// Extracted so we can implement `FormatElifElseClause` but also pass in `last_node` from /// `FormatStmtIf` pub(crate) fn format_elif_else_clause( item: &ElifElseClause, f: &mut PyFormatter, last_node: Option<AnyNodeRef>, suite_kind: SuiteKind, ) -> FormatResult<()> { let ElifElseClause { range: _, node_index: _, test, body, } = item; let comments = f.context().comments().clone(); let trailing_colon_comment = comments.dangling(item); let leading_comments = comments.leading(item); write!( f, [ clause( ClauseHeader::ElifElse(item), &format_with(|f: &mut PyFormatter| { f.options() .source_map_generation() .is_enabled() .then_some(source_position(item.start())) .fmt(f)?; if let Some(test) = test { write!( f, [ token("elif"), space(), maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks), ] ) } else { token("else").fmt(f) } }), trailing_colon_comment, body, suite_kind, ) .with_leading_comments(leading_comments, last_node), f.options() .source_map_generation() .is_enabled() .then_some(source_position(item.end())) ] ) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_assign.rs
crates/ruff_python_formatter/src/statement/stmt_assign.rs
use ruff_formatter::{FormatError, RemoveSoftLinesBuffer, format_args, write}; use ruff_python_ast::{ AnyNodeRef, Expr, ExprAttribute, ExprCall, FString, Operator, StmtAssign, StringLike, TString, TypeParams, }; use crate::builders::parenthesize_if_expands; use crate::comments::{ Comments, LeadingDanglingTrailingComments, SourceComment, trailing_comments, }; use crate::context::{NodeLevel, WithNodeLevel}; use crate::expression::expr_lambda::ExprLambdaLayout; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parentheses, Parenthesize, is_expression_parenthesized, optional_parentheses, }; use crate::expression::{ can_omit_optional_parentheses, has_own_parentheses, has_parentheses, maybe_parenthesize_expression, }; use crate::other::interpolated_string::InterpolatedStringLayout; use crate::preview::is_parenthesize_lambda_bodies_enabled; use crate::statement::trailing_semicolon; use crate::string::StringLikeExtensions; use crate::string::implicit::{ FormatImplicitConcatenatedStringExpanded, FormatImplicitConcatenatedStringFlat, ImplicitConcatenatedLayout, }; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtAssign; impl FormatNodeRule<StmtAssign> for FormatStmtAssign { fn fmt_fields(&self, item: &StmtAssign, f: &mut PyFormatter) -> FormatResult<()> { let StmtAssign { range: _, node_index: _, targets, value, } = item; let (first, rest) = targets.split_first().ok_or(FormatError::syntax_error( "Expected at least on assignment target", ))?; // The first target is special because it never gets parenthesized nor does the formatter remove parentheses if unnecessary. let format_first = FormatTargetWithEqualOperator { target: first, preserve_parentheses: true, }; // Avoid parenthesizing the value if the last target before the assigned value expands. if let Some((last, head)) = rest.split_last() { format_first.fmt(f)?; for target in head { FormatTargetWithEqualOperator { target, preserve_parentheses: false, } .fmt(f)?; } FormatStatementsLastExpression::RightToLeft { before_operator: AnyBeforeOperator::Expression(last), operator: AnyAssignmentOperator::Assign, value, statement: item.into(), } .fmt(f)?; } // Avoid parenthesizing the value for single-target assignments where the // target has its own parentheses (list, dict, tuple, ...) and the target expands. else if has_target_own_parentheses(first, f.context()) && !is_expression_parenthesized( first.into(), f.context().comments().ranges(), f.context().source(), ) { FormatStatementsLastExpression::RightToLeft { before_operator: AnyBeforeOperator::Expression(first), operator: AnyAssignmentOperator::Assign, value, statement: item.into(), } .fmt(f)?; } // For single targets that have no split points, parenthesize the value only // if it makes it fit. Otherwise omit the parentheses. else { format_first.fmt(f)?; FormatStatementsLastExpression::left_to_right(value, item).fmt(f)?; } if f.options().source_type().is_ipynb() && f.context().node_level().is_last_top_level_statement() && trailing_semicolon(item.into(), f.context().source()).is_some() && matches!(targets.as_slice(), [Expr::Name(_)]) { token(";").fmt(f)?; } Ok(()) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } } /// Formats a single target with the equal operator. struct FormatTargetWithEqualOperator<'a> { target: &'a Expr, /// Whether parentheses should be preserved as in the source or if the target /// should only be parenthesized if necessary (because of comments or because it doesn't fit). preserve_parentheses: bool, } impl Format<PyFormatContext<'_>> for FormatTargetWithEqualOperator<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { // Preserve parentheses for the first target or around targets with leading or trailing comments. if self.preserve_parentheses || f.context().comments().has_leading(self.target) || f.context().comments().has_trailing(self.target) { self.target.format().fmt(f)?; } else if should_parenthesize_target(self.target, f.context()) { parenthesize_if_expands(&self.target.format().with_options(Parentheses::Never)) .fmt(f)?; } else { self.target .format() .with_options(Parentheses::Never) .fmt(f)?; } write!(f, [space(), token("="), space()]) } } /// Formats the last expression in statements that start with a keyword (like `return`) or after an operator (assignments). /// /// The implementation avoids parenthesizing unsplittable values (like `None`, `True`, `False`, Names, a subset of strings) /// if the value won't fit even when parenthesized. /// /// ## Trailing comments /// Trailing comments are inlined inside the `value`'s parentheses rather than formatted at the end /// of the statement for unsplittable values if the `value` gets parenthesized. /// /// Inlining the trailing comments prevent situations where the parenthesized value /// still exceeds the configured line width, but parenthesizing helps to make the trailing comment fit. /// Instead, it only parenthesizes `value` if it makes both the `value` and the trailing comment fit. /// See [PR 8431](https://github.com/astral-sh/ruff/pull/8431) for more details. /// /// The implementation formats the statement's and value's trailing end of line comments: /// * after the expression if the expression needs no parentheses (necessary or the `expand_parent` makes the group never fit). /// * inside the parentheses if the expression exceeds the line-width. /// /// ```python /// a = loooooooooooooooooooooooooooong # with_comment /// b = ( /// short # with_comment /// ) /// ``` /// /// Which gets formatted to: /// /// ```python /// # formatted /// a = ( /// loooooooooooooooooooooooooooong # with comment /// ) /// b = short # with comment /// ``` /// /// The long name gets parenthesized because it exceeds the configured line width and the trailing comment of the /// statement gets formatted inside (instead of outside) the parentheses. /// /// No parentheses are added for `short` because it fits into the configured line length, regardless of whether /// the comment exceeds the line width or not. /// /// This logic isn't implemented in `place_comment` by associating trailing statement comments to the expression because /// doing so breaks the suite empty lines formatting that relies on trailing comments to be stored on the statement. #[derive(Debug)] pub(super) enum FormatStatementsLastExpression<'a> { /// Prefers to split what's left of `value` before splitting the value. /// /// ```python /// aaaaaaa[bbbbbbbb] = some_long_value /// ``` /// /// This layout splits `aaaaaaa[bbbbbbbb]` first assuming the whole statements exceeds the line width, resulting in /// /// ```python /// aaaaaaa[ /// bbbbbbbb /// ] = some_long_value /// ``` /// /// This layout is preferred over [`Self::RightToLeft`] if the left is unsplittable (single /// keyword like `return` or a Name) because it has better performance characteristics. LeftToRight { /// The right side of an assignment or the value returned in a return statement. value: &'a Expr, /// The parent statement that encloses the `value` expression. statement: AnyNodeRef<'a>, }, /// Prefers parenthesizing the value before splitting the left side. Specific to assignments. /// /// Formats what's left of `value` together with the assignment operator and the assigned `value`. /// This layout prefers parenthesizing the value over parenthesizing the left (target or type annotation): /// /// ```python /// aaaaaaa[bbbbbbbb] = some_long_value /// ``` /// /// gets formatted to... /// /// ```python /// aaaaaaa[bbbbbbbb] = ( /// some_long_value /// ) /// ``` /// /// ... regardless whether the value will fit or not. /// /// The left only gets parenthesized if the left exceeds the configured line width on its own or /// is forced to split because of a magical trailing comma or contains comments: /// /// ```python /// aaaaaaa[bbbbbbbb_exceeds_the_line_width] = some_long_value /// ``` /// /// gets formatted to /// ```python /// aaaaaaa[ /// bbbbbbbb_exceeds_the_line_width /// ] = some_long_value /// ``` /// /// The layout avoids parenthesizing the value when the left splits to avoid /// unnecessary parentheses. Adding the parentheses, as shown in the below example, reduces readability. /// /// ```python /// aaaaaaa[ /// bbbbbbbb_exceeds_the_line_width /// ] = ( /// some_long_value /// ) /// /// ## Non-fluent Call Expressions /// Non-fluent call expressions in the `value` position are only parenthesized if the opening parentheses /// exceeds the configured line length. The layout prefers splitting after the opening parentheses /// if the `callee` expression and the opening parentheses fit. /// fits on the line. RightToLeft { /// The expression that comes before the assignment operator. This is either /// the last target, or the type annotation of an annotated assignment. before_operator: AnyBeforeOperator<'a>, /// The assignment operator. Either `Assign` (`=`) or the operator used by the augmented assignment statement. operator: AnyAssignmentOperator, /// The assigned `value`. value: &'a Expr, /// The assignment statement. statement: AnyNodeRef<'a>, }, } impl<'a> FormatStatementsLastExpression<'a> { pub(super) fn left_to_right<S: Into<AnyNodeRef<'a>>>(value: &'a Expr, statement: S) -> Self { Self::LeftToRight { value, statement: statement.into(), } } } impl Format<PyFormatContext<'_>> for FormatStatementsLastExpression<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { match self { FormatStatementsLastExpression::LeftToRight { value, statement } => { let can_inline_comment = should_inline_comments(value, *statement, f.context()); let string_like = StringLike::try_from(*value).ok(); let format_interpolated_string = string_like .and_then(|string| format_interpolated_string_assignment(string, f.context())); let format_implicit_flat = string_like.and_then(|string| { FormatImplicitConcatenatedStringFlat::new(string, f.context()) }); if !can_inline_comment && format_implicit_flat.is_none() && format_interpolated_string.is_none() { return maybe_parenthesize_value(value, *statement).fmt(f); } let comments = f.context().comments().clone(); let expression_comments = comments.leading_dangling_trailing(*value); if let Some(inline_comments) = OptionalParenthesesInlinedComments::new( &expression_comments, *statement, &comments, ) { let group_id = f.group_id("optional_parentheses"); // Special case for implicit concatenated strings in assignment value positions. // The special handling is necessary to prevent an instability where an assignment has // a trailing own line comment and the implicit concatenated string fits on the line, // but only if the comment doesn't get inlined. // // ```python // ____aaa = ( // "aaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvvvvv" // ) # c // ``` // // Without the special handling, this would get formatted to: // ```python // ____aaa = ( // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvvvvv" // ) # c // ``` // // However, this now gets reformatted again because Ruff now takes the `BestFit` layout for the string // because the value is no longer an implicit concatenated string. // ```python // ____aaa = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbvvvvvvvvvvvvvvv" # c // ``` // // The special handling here ensures that the implicit concatenated string only gets // joined **if** it fits with the trailing comment inlined. Otherwise, keep the multiline // formatting. if let Some(flat) = format_implicit_flat { inline_comments.mark_formatted(); let string = flat.string(); let flat = format_with(|f| { if string.is_interpolated_string() { let mut buffer = RemoveSoftLinesBuffer::new(&mut *f); write!(buffer, [flat]) } else { flat.fmt(f) } }) .memoized(); // F-string or T-string containing an expression with a magic trailing comma, a comment, or a // multiline debug expression should never be joined. Use the default layout. // ```python // aaaa = f"abcd{[ // 1, // 2, // ]}" "more" // ``` if string.is_interpolated_string() && flat.inspect(f)?.will_break() { inline_comments.mark_unformatted(); return write!( f, [maybe_parenthesize_expression( value, *statement, Parenthesize::IfBreaks, )] ); } let expanded = format_with(|f| { let f = &mut WithNodeLevel::new(NodeLevel::Expression(Some(group_id)), f); write!( f, [FormatImplicitConcatenatedStringExpanded::new( string, ImplicitConcatenatedLayout::MaybeFlat )] ) }); // Join the implicit concatenated string if it fits on a single line // ```python // a = "testmorelong" # comment // ``` let single_line = format_with(|f| write!(f, [flat, inline_comments])); // Parenthesize the string but join the implicit concatenated string and inline the comment. // ```python // a = ( // "testmorelong" # comment // ) // ``` let joined_parenthesized = format_with(|f| { group(&format_args![ token("("), soft_block_indent(&format_args![flat, inline_comments]), token(")"), ]) .with_id(Some(group_id)) .should_expand(true) .fmt(f) }); // Keep the implicit concatenated string multiline and don't inline the comment. // ```python // a = ( // "test" // "more" // "long" // ) # comment // ``` let implicit_expanded = format_with(|f| { group(&format_args![ token("("), block_indent(&expanded), token(")"), inline_comments, ]) .with_id(Some(group_id)) .should_expand(true) .fmt(f) }); // We can't use `optional_parentheses` here because the `inline_comments` contains // a `expand_parent` which results in an instability because the next format // collapses the parentheses. // We can't use `parenthesize_if_expands` because it defaults to // the *flat* layout when the expanded layout doesn't fit. best_fitting![single_line, joined_parenthesized, implicit_expanded] .with_mode(BestFittingMode::AllLines) .fmt(f)?; } else if let Some(format_interpolated_string) = format_interpolated_string { inline_comments.mark_formatted(); let interpolated_string_flat = format_with(|f| { let mut buffer = RemoveSoftLinesBuffer::new(&mut *f); write!(buffer, [format_interpolated_string]) }) .memoized(); // F/T-String containing an interpolation with a magic trailing comma, a comment, or a // multiline debug interpolation should never be joined. Use the default layout. // ```python // aaaa = f"aaaa {[ // 1, 2, // ]} bbbb" // ``` if interpolated_string_flat.inspect(f)?.will_break() { inline_comments.mark_unformatted(); return write!( f, [maybe_parenthesize_expression( value, *statement, Parenthesize::IfBreaks, )] ); } // Considering the following example: // ```python // aaaaaaaaaaaaaaaaaa = f"testeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee{ // expression}moreeeeeeeeeeeeeeeee" // ``` // Flatten the f/t-string. // ```python // aaaaaaaaaaaaaaaaaa = f"testeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee{expression}moreeeeeeeeeeeeeeeee" // ``` let single_line = format_with(|f| write!(f, [interpolated_string_flat, inline_comments])); // Parenthesize the t-string and flatten the t-string. // ```python // aaaaaaaaaaaaaaaaaa = ( // t"testeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee{expression}moreeeeeeeeeeeeeeeee" // ) // ``` let joined_parenthesized = format_with(|f| { group(&format_args![ token("("), soft_block_indent(&format_args![ interpolated_string_flat, inline_comments ]), token(")"), ]) .with_id(Some(group_id)) .should_expand(true) .fmt(f) }); // Avoid flattening or parenthesizing the f/t-string, keep the original // f/t-string formatting. // ```python // aaaaaaaaaaaaaaaaaa = t"testeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee{ // expression // }moreeeeeeeeeeeeeeeee" // ``` let format_interpolated_string = format_with(|f| { write!(f, [format_interpolated_string, inline_comments]) }); best_fitting![ single_line, joined_parenthesized, format_interpolated_string ] .with_mode(BestFittingMode::AllLines) .fmt(f)?; } else { best_fit_parenthesize(&format_once(|f| { inline_comments.mark_formatted(); value.format().with_options(Parentheses::Never).fmt(f)?; if !inline_comments.is_empty() { // If the expressions exceeds the line width, format the comments in the parentheses if_group_breaks(&inline_comments).fmt(f)?; } Ok(()) })) .with_group_id(Some(group_id)) .fmt(f)?; if !inline_comments.is_empty() { // If the line fits into the line width, format the comments after the parenthesized expression if_group_fits_on_line(&inline_comments) .with_group_id(Some(group_id)) .fmt(f)?; } } Ok(()) } else { // Preserve the parentheses if the expression has any leading or trailing comments, // to avoid syntax errors, similar to `maybe_parenthesize_expression`. value.format().with_options(Parentheses::Always).fmt(f) } } FormatStatementsLastExpression::RightToLeft { before_operator, operator, value, statement, } => { let should_inline_comments = should_inline_comments(value, *statement, f.context()); let string_like = StringLike::try_from(*value).ok(); let format_interpolated_string = string_like .and_then(|string| format_interpolated_string_assignment(string, f.context())); let format_implicit_flat = string_like.and_then(|string| { FormatImplicitConcatenatedStringFlat::new(string, f.context()) }); // Use the normal `maybe_parenthesize_layout` for splittable `value`s. if !should_inline_comments && !should_non_inlineable_use_best_fit(value, *statement, f.context()) && format_implicit_flat.is_none() && format_interpolated_string.is_none() { return write!( f, [ before_operator, space(), operator, space(), maybe_parenthesize_value(value, *statement) ] ); } let comments = f.context().comments().clone(); let expression_comments = comments.leading_dangling_trailing(*value); // Don't inline comments for attribute and call expressions for black compatibility let inline_comments = if should_inline_comments || format_implicit_flat.is_some() || format_interpolated_string.is_some() { OptionalParenthesesInlinedComments::new( &expression_comments, *statement, &comments, ) } else if expression_comments.has_leading() || expression_comments.has_trailing_own_line() { None } else { Some(OptionalParenthesesInlinedComments::default()) }; let Some(inline_comments) = inline_comments else { // Preserve the parentheses if the expression has any leading or trailing own line comments // same as `maybe_parenthesize_expression` return write!( f, [ before_operator, space(), operator, space(), value.format().with_options(Parentheses::Always) ] ); }; // Prevent inline comments to be formatted as part of the expression. inline_comments.mark_formatted(); let last_target = before_operator.memoized(); let last_target_breaks = last_target.inspect(f)?.will_break(); // Don't parenthesize the `value` if it is known that the target will break. // This is mainly a performance optimisation that avoids unnecessary memoization // and using the costly `BestFitting` layout if it is already known that only the last variant // can ever fit because the left breaks. if format_implicit_flat.is_none() && format_interpolated_string.is_none() && last_target_breaks { return write!( f, [ last_target, space(), operator, space(), value.format().with_options(Parentheses::Never), inline_comments ] ); } let format_value = format_with(|f| { if let Some(format_implicit_flat) = format_implicit_flat.as_ref() { if format_implicit_flat.string().is_interpolated_string() { // Remove any soft line breaks emitted by the f-string formatting. // This is important when formatting f-strings as part of an assignment right side // because `best_fit_parenthesize` will otherwise still try to break inner // groups if wrapped in a `group(..).should_expand(true)` let mut buffer = RemoveSoftLinesBuffer::new(&mut *f); write!(buffer, [format_implicit_flat]) } else { format_implicit_flat.fmt(f) } } else if let Some(format_interpolated_string) = format_interpolated_string.as_ref() { // Similar to above, remove any soft line breaks emitted by the f-string // formatting. let mut buffer = RemoveSoftLinesBuffer::new(&mut *f); write!(buffer, [format_interpolated_string]) } else { value.format().with_options(Parentheses::Never).fmt(f) } }) .memoized(); // Tries to fit the `left` and the `value` on a single line: // ```python // a = b = c // ``` let single_line = format_with(|f| { write!( f, [ last_target, space(), operator, space(), format_value, inline_comments ] ) }); // Don't break the last assignment target but parenthesize the value to see if it fits (break right first). // // ```python // a["bbbbb"] = ( // c // ) // ``` let flat_target_parenthesize_value = format_with(|f| { write!( f, [ last_target, space(), operator, space(), token("("), group(&soft_block_indent(&format_args![ format_value, inline_comments ])) .should_expand(true), token(")") ] ) }); // Fall back to parenthesizing (or splitting) the last target part if we can't make the value // fit. Don't parenthesize the value to avoid unnecessary parentheses. // // ```python // a[ // "bbbbb" // ] = c // ``` let split_target_flat_value = format_with(|f| { write!( f, [ group(&last_target).should_expand(true), space(), operator, space(), format_value, inline_comments ] ) }); // For call expressions, prefer breaking after the call expression's opening parentheses // over parenthesizing the entire call expression. // For subscripts, try breaking the subscript first // For attribute chains that contain any parenthesized value: Try expanding the parenthesized value first. if value.is_call_expr() || value.is_subscript_expr() || value.is_attribute_expr() { best_fitting![
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_import_from.rs
crates/ruff_python_formatter/src/statement/stmt_import_from.rs
use ruff_formatter::write; use ruff_python_ast::StmtImportFrom; use ruff_text_size::Ranged; use crate::builders::{PyFormatterExtensions, TrailingComma, parenthesize_if_expands}; use crate::comments::SourceComment; use crate::expression::parentheses::parenthesized; use crate::has_skip_comment; use crate::other::identifier::DotDelimitedIdentifier; use crate::prelude::*; #[derive(Default)] pub struct FormatStmtImportFrom; impl FormatNodeRule<StmtImportFrom> for FormatStmtImportFrom { fn fmt_fields(&self, item: &StmtImportFrom, f: &mut PyFormatter) -> FormatResult<()> { let StmtImportFrom { module, names, level, range: _, node_index: _, } = item; write!( f, [ token("from"), space(), format_with(|f| { for _ in 0..*level { token(".").fmt(f)?; } Ok(()) }), module.as_ref().map(DotDelimitedIdentifier::new), space(), token("import"), space(), ] )?; if let [name] = names.as_slice() { // star can't be surrounded by parentheses if name.name.as_str() == "*" { return token("*").fmt(f); } } let names = format_with(|f| { f.join_comma_separated(item.end()) .with_trailing_comma(TrailingComma::OneOrMore) .entries(names.iter().map(|name| (name, name.format()))) .finish() }); // A dangling comment on an import is a parenthesized comment, like: // ```python // from example import ( # comment // A, // B, // ) // ``` let comments = f.context().comments().clone(); let parenthesized_comments = comments.dangling(item); if parenthesized_comments.is_empty() { parenthesize_if_expands(&names).fmt(f) } else { parenthesized("(", &names, ")") .with_dangling_comments(parenthesized_comments) .fmt(f) } } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_match.rs
crates/ruff_python_formatter/src/statement/stmt_match.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::StmtMatch; use crate::comments::leading_alternate_branch_comments; use crate::context::{NodeLevel, WithNodeLevel}; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::prelude::*; use crate::statement::clause::{ClauseHeader, clause_header}; #[derive(Default)] pub struct FormatStmtMatch; impl FormatNodeRule<StmtMatch> for FormatStmtMatch { fn fmt_fields(&self, item: &StmtMatch, f: &mut PyFormatter) -> FormatResult<()> { let StmtMatch { range: _, node_index: _, subject, cases, } = item; let comments = f.context().comments().clone(); let dangling_item_comments = comments.dangling(item); // There can be at most one dangling comment after the colon in a match statement. debug_assert!(dangling_item_comments.len() <= 1); clause_header( ClauseHeader::Match(item), dangling_item_comments, &format_args![ token("match"), space(), maybe_parenthesize_expression(subject, item, Parenthesize::IfBreaks), ], ) .fmt(f)?; let mut cases_iter = cases.iter(); let Some(first) = cases_iter.next() else { return Ok(()); }; // The new level is for the `case` nodes. let mut f = WithNodeLevel::new(NodeLevel::CompoundStatement, f); write!(f, [block_indent(&first.format())])?; let mut last_case = first; for case in cases_iter { let last_suite_in_statement = Some(case) == cases.last(); write!( f, [block_indent(&format_args!( leading_alternate_branch_comments( comments.leading(case), last_case.body.last(), ), case.format().with_options(last_suite_in_statement) ))] )?; last_case = case; } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_while.rs
crates/ruff_python_formatter/src/statement/stmt_while.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::{Stmt, StmtWhile}; use ruff_text_size::Ranged; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::prelude::*; use crate::statement::clause::{ClauseHeader, ElseClause, clause}; use crate::statement::suite::SuiteKind; #[derive(Default)] pub struct FormatStmtWhile; impl FormatNodeRule<StmtWhile> for FormatStmtWhile { fn fmt_fields(&self, item: &StmtWhile, f: &mut PyFormatter) -> FormatResult<()> { let StmtWhile { range: _, node_index: _, test, body, orelse, } = item; let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(item); let body_start = body.first().map_or(test.end(), Stmt::start); let or_else_comments_start = dangling_comments.partition_point(|comment| comment.end() < body_start); let (trailing_condition_comments, or_else_comments) = dangling_comments.split_at(or_else_comments_start); write!( f, [clause( ClauseHeader::While(item), &format_args![ token("while"), space(), maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks), ], trailing_condition_comments, body, SuiteKind::other(orelse.is_empty()), )] )?; if !orelse.is_empty() { // Split between leading comments before the `else` keyword and end of line comments at the end of // the `else:` line. let trailing_start = or_else_comments.partition_point(|comment| comment.line_position().is_own_line()); let (leading, trailing) = or_else_comments.split_at(trailing_start); write!( f, [clause( ClauseHeader::OrElse(ElseClause::While(item)), &token("else"), trailing, orelse, SuiteKind::other(true), ) .with_leading_comments(leading, body.last()),] )?; } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_class_def.rs
crates/ruff_python_formatter/src/statement/stmt_class_def.rs
use ruff_formatter::write; use ruff_python_ast::{Decorator, NodeKind, StmtClassDef}; use ruff_python_trivia::lines_after_ignoring_end_of_line_trivia; use ruff_text_size::Ranged; use crate::comments::format::{ empty_lines_after_leading_comments, empty_lines_before_trailing_comments, }; use crate::comments::{SourceComment, leading_comments, trailing_comments}; use crate::prelude::*; use crate::statement::clause::{ClauseHeader, clause}; use crate::statement::suite::SuiteKind; #[derive(Default)] pub struct FormatStmtClassDef; impl FormatNodeRule<StmtClassDef> for FormatStmtClassDef { fn fmt_fields(&self, item: &StmtClassDef, f: &mut PyFormatter) -> FormatResult<()> { let StmtClassDef { range: _, node_index: _, name, arguments, body, type_params, decorator_list, } = item; let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(item); let trailing_definition_comments_start = dangling_comments.partition_point(|comment| comment.line_position().is_own_line()); let (leading_definition_comments, trailing_definition_comments) = dangling_comments.split_at(trailing_definition_comments_start); // If the class contains leading comments, insert newlines before them. // For example, given: // ```python // # comment // // class Class: // ... // ``` // // At the top-level in a non-stub file, reformat as: // ```python // # comment // // // class Class: // ... // ``` // Note that this is only really relevant for the specific case in which there's a single // newline between the comment and the node, but we _require_ two newlines. If there are // _no_ newlines between the comment and the node, we don't insert _any_ newlines; if there // are more than two, then `leading_comments` will preserve the correct number of newlines. empty_lines_after_leading_comments(comments.leading(item)).fmt(f)?; write!( f, [ FormatDecorators { decorators: decorator_list, leading_definition_comments, }, clause( ClauseHeader::Class(item), &format_with(|f| { write!(f, [token("class"), space(), name.format()])?; if let Some(type_params) = type_params.as_deref() { write!(f, [type_params.format()])?; } if let Some(arguments) = arguments.as_deref() { // Drop empty the arguments node entirely (i.e., remove the parentheses) if it is empty, // e.g., given: // ```python // class A(): // ... // ``` // // Format as: // ```python // class A: // ... // ``` // // However, preserve any dangling end-of-line comments, e.g., given: // ```python // class A( # comment // ): // ... // // Format as: // ```python // class A: # comment // ... // ``` // // However, the arguments contain any dangling own-line comments, we retain the // parentheses, e.g., given: // ```python // class A( # comment // # comment // ): // ... // ``` // // Format as: // ```python // class A( # comment // # comment // ): // ... // ``` if arguments.is_empty() && comments .dangling(arguments) .iter() .all(|comment| comment.line_position().is_end_of_line()) { let dangling = comments.dangling(arguments); write!(f, [trailing_comments(dangling)])?; } else { write!(f, [arguments.format()])?; } } Ok(()) }), trailing_definition_comments, body, SuiteKind::Class, ), ] )?; // If the class contains trailing comments, insert newlines before them. // For example, given: // ```python // class Class: // ... // # comment // ``` // // At the top-level in a non-stub file, reformat as: // ```python // class Class: // ... // // // # comment // ``` empty_lines_before_trailing_comments(comments.trailing(item), NodeKind::StmtClassDef) .fmt(f)?; Ok(()) } } pub(super) struct FormatDecorators<'a> { pub(super) decorators: &'a [Decorator], pub(super) leading_definition_comments: &'a [SourceComment], } impl Format<PyFormatContext<'_>> for FormatDecorators<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { if let Some(last_decorator) = self.decorators.last() { f.join_with(hard_line_break()) .entries(self.decorators.iter().formatted()) .finish()?; if self.leading_definition_comments.is_empty() { write!(f, [hard_line_break()])?; } else { // Write any leading definition comments (between last decorator and the header) // while maintaining the right amount of empty lines between the comment // and the last decorator. let leading_line = if lines_after_ignoring_end_of_line_trivia( last_decorator.end(), f.context().source(), ) <= 1 { hard_line_break() } else { empty_line() }; write!( f, [ leading_line, leading_comments(self.leading_definition_comments) ] )?; } } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_aug_assign.rs
crates/ruff_python_formatter/src/statement/stmt_aug_assign.rs
use ruff_formatter::write; use ruff_python_ast::StmtAugAssign; use crate::comments::SourceComment; use crate::expression::parentheses::is_expression_parenthesized; use crate::statement::stmt_assign::{ AnyAssignmentOperator, AnyBeforeOperator, FormatStatementsLastExpression, has_target_own_parentheses, }; use crate::statement::trailing_semicolon; use crate::{AsFormat, FormatNodeRule}; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtAugAssign; impl FormatNodeRule<StmtAugAssign> for FormatStmtAugAssign { fn fmt_fields(&self, item: &StmtAugAssign, f: &mut PyFormatter) -> FormatResult<()> { let StmtAugAssign { target, op, value, range: _, node_index: _, } = item; if has_target_own_parentheses(target, f.context()) && !is_expression_parenthesized( target.into(), f.context().comments().ranges(), f.context().source(), ) { FormatStatementsLastExpression::RightToLeft { before_operator: AnyBeforeOperator::Expression(target), operator: AnyAssignmentOperator::AugAssign(*op), value, statement: item.into(), } .fmt(f)?; } else { write!( f, [ target.format(), space(), op.format(), token("="), space(), FormatStatementsLastExpression::left_to_right(value, item) ] )?; } if f.options().source_type().is_ipynb() && f.context().node_level().is_last_top_level_statement() && target.is_name_expr() && trailing_semicolon(item.into(), f.context().source()).is_some() { token(";").fmt(f)?; } Ok(()) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_assert.rs
crates/ruff_python_formatter/src/statement/stmt_assert.rs
use ruff_formatter::prelude::{space, token}; use ruff_formatter::write; use ruff_python_ast::StmtAssert; use crate::comments::SourceComment; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtAssert; impl FormatNodeRule<StmtAssert> for FormatStmtAssert { fn fmt_fields(&self, item: &StmtAssert, f: &mut PyFormatter) -> FormatResult<()> { let StmtAssert { range: _, node_index: _, test, msg, } = item; write!( f, [ token("assert"), space(), maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks) ] )?; if let Some(msg) = msg { write!( f, [ token(","), space(), maybe_parenthesize_expression(msg, item, Parenthesize::IfBreaksParenthesized), ] )?; } Ok(()) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_ann_assign.rs
crates/ruff_python_formatter/src/statement/stmt_ann_assign.rs
use ruff_formatter::write; use ruff_python_ast::StmtAnnAssign; use crate::comments::SourceComment; use crate::expression::is_splittable_expression; use crate::expression::parentheses::Parentheses; use crate::statement::stmt_assign::{ AnyAssignmentOperator, AnyBeforeOperator, FormatStatementsLastExpression, }; use crate::statement::trailing_semicolon; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtAnnAssign; impl FormatNodeRule<StmtAnnAssign> for FormatStmtAnnAssign { fn fmt_fields(&self, item: &StmtAnnAssign, f: &mut PyFormatter) -> FormatResult<()> { let StmtAnnAssign { range: _, node_index: _, target, annotation, value, simple: _, } = item; write!(f, [target.format(), token(":"), space()])?; if let Some(value) = value { if is_splittable_expression(annotation, f.context()) { FormatStatementsLastExpression::RightToLeft { before_operator: AnyBeforeOperator::Expression(annotation), operator: AnyAssignmentOperator::Assign, value, statement: item.into(), } .fmt(f)?; } else { // Remove unnecessary parentheses around the annotation if the parenthesize long type hints preview style is enabled. // Ensure we keep the parentheses if the annotation has any comments. if f.context().comments().has_leading(annotation.as_ref()) || f.context().comments().has_trailing(annotation.as_ref()) { annotation .format() .with_options(Parentheses::Always) .fmt(f)?; } else { annotation .format() .with_options(Parentheses::Never) .fmt(f)?; } write!( f, [ space(), token("="), space(), FormatStatementsLastExpression::left_to_right(value, item) ] )?; } } else { // Parenthesize the value and inline the comment if it is a "simple" type annotation, similar // to what we do with the value. // ```python // class Test: // safe_age: ( // Decimal # the user's age, used to determine if it's safe for them to use ruff // ) // ``` FormatStatementsLastExpression::left_to_right(annotation, item).fmt(f)?; } if f.options().source_type().is_ipynb() && f.context().node_level().is_last_top_level_statement() && target.is_name_expr() && trailing_semicolon(item.into(), f.context().source()).is_some() { token(";").fmt(f)?; } Ok(()) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/clause.rs
crates/ruff_python_formatter/src/statement/clause.rs
use ruff_formatter::{Argument, Arguments, FormatError, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{ ElifElseClause, ExceptHandlerExceptHandler, MatchCase, StmtClassDef, StmtFor, StmtFunctionDef, StmtIf, StmtMatch, StmtTry, StmtWhile, StmtWith, Suite, }; use ruff_python_trivia::{SimpleToken, SimpleTokenKind, SimpleTokenizer}; use ruff_source_file::LineRanges; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::comments::{SourceComment, leading_alternate_branch_comments, trailing_comments}; use crate::statement::suite::{SuiteKind, as_only_an_ellipsis}; use crate::verbatim::{verbatim_text, write_suppressed_clause_header}; use crate::{has_skip_comment, prelude::*}; /// The header of a compound statement clause. /// /// > A compound statement consists of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ /// > The clause headers of a particular compound statement are all at the same indentation level. /// > Each clause header begins with a uniquely identifying keyword and ends with a colon. /// /// [source](https://docs.python.org/3/reference/compound_stmts.html#compound-statements) #[derive(Copy, Clone)] pub(crate) enum ClauseHeader<'a> { Class(&'a StmtClassDef), Function(&'a StmtFunctionDef), If(&'a StmtIf), ElifElse(&'a ElifElseClause), Try(&'a StmtTry), ExceptHandler(&'a ExceptHandlerExceptHandler), TryFinally(&'a StmtTry), Match(&'a StmtMatch), MatchCase(&'a MatchCase), For(&'a StmtFor), While(&'a StmtWhile), With(&'a StmtWith), OrElse(ElseClause<'a>), } impl<'a> ClauseHeader<'a> { /// Returns the last child in the clause body immediately following this clause header. /// /// For most clauses, this is the last statement in /// the primary body. For clauses like `try`, it specifically returns the last child /// in the `try` body, not the `except`/`else`/`finally` clauses. /// /// This is similar to [`ruff_python_ast::AnyNodeRef::last_child_in_body`] /// but restricted to the clause. pub(crate) fn last_child_in_clause(self) -> Option<AnyNodeRef<'a>> { match self { ClauseHeader::Class(StmtClassDef { body, .. }) | ClauseHeader::Function(StmtFunctionDef { body, .. }) | ClauseHeader::If(StmtIf { body, .. }) | ClauseHeader::ElifElse(ElifElseClause { body, .. }) | ClauseHeader::Try(StmtTry { body, .. }) | ClauseHeader::MatchCase(MatchCase { body, .. }) | ClauseHeader::For(StmtFor { body, .. }) | ClauseHeader::While(StmtWhile { body, .. }) | ClauseHeader::With(StmtWith { body, .. }) | ClauseHeader::ExceptHandler(ExceptHandlerExceptHandler { body, .. }) | ClauseHeader::OrElse( ElseClause::Try(StmtTry { orelse: body, .. }) | ElseClause::For(StmtFor { orelse: body, .. }) | ElseClause::While(StmtWhile { orelse: body, .. }), ) | ClauseHeader::TryFinally(StmtTry { finalbody: body, .. }) => body.last().map(AnyNodeRef::from), ClauseHeader::Match(StmtMatch { cases, .. }) => cases .last() .and_then(|case| case.body.last().map(AnyNodeRef::from)), } } /// The range from the clause keyword up to and including the final colon. pub(crate) fn range(self, source: &str) -> FormatResult<TextRange> { let keyword_range = self.first_keyword_range(source)?; let mut last_child_end = None; self.visit(&mut |child| last_child_end = Some(child.end())); let end = match self { ClauseHeader::Class(class) => Some(last_child_end.unwrap_or(class.name.end())), ClauseHeader::Function(function) => Some(last_child_end.unwrap_or(function.name.end())), ClauseHeader::ElifElse(_) | ClauseHeader::Try(_) | ClauseHeader::If(_) | ClauseHeader::TryFinally(_) | ClauseHeader::Match(_) | ClauseHeader::MatchCase(_) | ClauseHeader::For(_) | ClauseHeader::While(_) | ClauseHeader::With(_) | ClauseHeader::OrElse(_) => last_child_end, ClauseHeader::ExceptHandler(handler) => { handler.name.as_ref().map(Ranged::end).or(last_child_end) } }; let colon = colon_range(end.unwrap_or(keyword_range.end()), source)?; Ok(TextRange::new(keyword_range.start(), colon.end())) } /// Visits the nodes in the case header. pub(crate) fn visit<F>(self, visitor: &mut F) where F: FnMut(AnyNodeRef), { fn visit<'a, N, F>(node: N, visitor: &mut F) where N: Into<AnyNodeRef<'a>>, F: FnMut(AnyNodeRef<'a>), { visitor(node.into()); } match self { ClauseHeader::Class(StmtClassDef { type_params, arguments, range: _, node_index: _, decorator_list: _, name: _, body: _, }) => { if let Some(type_params) = type_params.as_deref() { visit(type_params, visitor); } if let Some(arguments) = arguments { visit(arguments.as_ref(), visitor); } } ClauseHeader::Function(StmtFunctionDef { type_params, parameters, range: _, node_index: _, is_async: _, decorator_list: _, name: _, returns, body: _, }) => { if let Some(type_params) = type_params.as_deref() { visit(type_params, visitor); } visit(parameters.as_ref(), visitor); if let Some(returns) = returns.as_deref() { visit(returns, visitor); } } ClauseHeader::If(StmtIf { test, range: _, node_index: _, body: _, elif_else_clauses: _, }) => { visit(test.as_ref(), visitor); } ClauseHeader::ElifElse(ElifElseClause { test, range: _, node_index: _, body: _, }) => { if let Some(test) = test.as_ref() { visit(test, visitor); } } ClauseHeader::ExceptHandler(ExceptHandlerExceptHandler { type_: type_expr, range: _, node_index: _, name: _, body: _, }) => { if let Some(type_expr) = type_expr.as_deref() { visit(type_expr, visitor); } } ClauseHeader::Match(StmtMatch { subject, range: _, node_index: _, cases: _, }) => { visit(subject.as_ref(), visitor); } ClauseHeader::MatchCase(MatchCase { guard, pattern, range: _, node_index: _, body: _, }) => { visit(pattern, visitor); if let Some(guard) = guard.as_deref() { visit(guard, visitor); } } ClauseHeader::For(StmtFor { target, iter, range: _, node_index: _, is_async: _, body: _, orelse: _, }) => { visit(target.as_ref(), visitor); visit(iter.as_ref(), visitor); } ClauseHeader::While(StmtWhile { test, range: _, node_index: _, body: _, orelse: _, }) => { visit(test.as_ref(), visitor); } ClauseHeader::With(StmtWith { items, range: _, node_index: _, is_async: _, body: _, }) => { for item in items { visit(item, visitor); } } ClauseHeader::Try(_) | ClauseHeader::TryFinally(_) | ClauseHeader::OrElse(_) => {} } } /// Returns the range of the first keyword that marks the start of the clause header. fn first_keyword_range(self, source: &str) -> FormatResult<TextRange> { match self { ClauseHeader::Class(header) => { let start_position = header .decorator_list .last() .map_or_else(|| header.start(), Ranged::end); find_keyword( StartPosition::ClauseStart(start_position), SimpleTokenKind::Class, source, ) } ClauseHeader::Function(header) => { let start_position = header .decorator_list .last() .map_or_else(|| header.start(), Ranged::end); let keyword = if header.is_async { SimpleTokenKind::Async } else { SimpleTokenKind::Def }; find_keyword(StartPosition::ClauseStart(start_position), keyword, source) } ClauseHeader::If(header) => find_keyword( StartPosition::clause_start(header), SimpleTokenKind::If, source, ), ClauseHeader::ElifElse(ElifElseClause { test: None, range, .. }) => find_keyword( StartPosition::clause_start(range), SimpleTokenKind::Else, source, ), ClauseHeader::ElifElse(ElifElseClause { test: Some(_), range, .. }) => find_keyword( StartPosition::clause_start(range), SimpleTokenKind::Elif, source, ), ClauseHeader::Try(header) => find_keyword( StartPosition::clause_start(header), SimpleTokenKind::Try, source, ), ClauseHeader::ExceptHandler(header) => find_keyword( StartPosition::clause_start(header), SimpleTokenKind::Except, source, ), ClauseHeader::TryFinally(header) => { let last_statement = header .orelse .last() .map(AnyNodeRef::from) .or_else(|| header.handlers.last().map(AnyNodeRef::from)) .or_else(|| header.body.last().map(AnyNodeRef::from)) .unwrap(); find_keyword( StartPosition::LastStatement(last_statement.end()), SimpleTokenKind::Finally, source, ) } ClauseHeader::Match(header) => find_keyword( StartPosition::clause_start(header), SimpleTokenKind::Match, source, ), ClauseHeader::MatchCase(header) => find_keyword( StartPosition::clause_start(header), SimpleTokenKind::Case, source, ), ClauseHeader::For(header) => { let keyword = if header.is_async { SimpleTokenKind::Async } else { SimpleTokenKind::For }; find_keyword(StartPosition::clause_start(header), keyword, source) } ClauseHeader::While(header) => find_keyword( StartPosition::clause_start(header), SimpleTokenKind::While, source, ), ClauseHeader::With(header) => { let keyword = if header.is_async { SimpleTokenKind::Async } else { SimpleTokenKind::With }; find_keyword(StartPosition::clause_start(header), keyword, source) } ClauseHeader::OrElse(header) => match header { ElseClause::Try(try_stmt) => { let last_statement = try_stmt .handlers .last() .map(AnyNodeRef::from) .or_else(|| try_stmt.body.last().map(AnyNodeRef::from)) .unwrap(); find_keyword( StartPosition::LastStatement(last_statement.end()), SimpleTokenKind::Else, source, ) } ElseClause::For(StmtFor { body, .. }) | ElseClause::While(StmtWhile { body, .. }) => find_keyword( StartPosition::LastStatement(body.last().unwrap().end()), SimpleTokenKind::Else, source, ), }, } } } impl<'a> From<ClauseHeader<'a>> for AnyNodeRef<'a> { fn from(value: ClauseHeader<'a>) -> Self { match value { ClauseHeader::Class(stmt_class_def) => stmt_class_def.into(), ClauseHeader::Function(stmt_function_def) => stmt_function_def.into(), ClauseHeader::If(stmt_if) => stmt_if.into(), ClauseHeader::ElifElse(elif_else_clause) => elif_else_clause.into(), ClauseHeader::Try(stmt_try) => stmt_try.into(), ClauseHeader::ExceptHandler(except_handler_except_handler) => { except_handler_except_handler.into() } ClauseHeader::TryFinally(stmt_try) => stmt_try.into(), ClauseHeader::Match(stmt_match) => stmt_match.into(), ClauseHeader::MatchCase(match_case) => match_case.into(), ClauseHeader::For(stmt_for) => stmt_for.into(), ClauseHeader::While(stmt_while) => stmt_while.into(), ClauseHeader::With(stmt_with) => stmt_with.into(), ClauseHeader::OrElse(else_clause) => else_clause.into(), } } } #[derive(Copy, Clone)] pub(crate) enum ElseClause<'a> { Try(&'a StmtTry), For(&'a StmtFor), While(&'a StmtWhile), } impl<'a> From<ElseClause<'a>> for AnyNodeRef<'a> { fn from(value: ElseClause<'a>) -> Self { match value { ElseClause::Try(stmt_try) => stmt_try.into(), ElseClause::For(stmt_for) => stmt_for.into(), ElseClause::While(stmt_while) => stmt_while.into(), } } } pub(crate) struct FormatClauseHeader<'a, 'ast> { header: ClauseHeader<'a>, /// How to format the clause header formatter: Argument<'a, PyFormatContext<'ast>>, /// Leading comments coming before the branch, together with the previous node, if any. Only relevant /// for alternate branches. leading_comments: Option<(&'a [SourceComment], Option<AnyNodeRef<'a>>)>, /// The trailing comments coming after the colon. trailing_colon_comment: &'a [SourceComment], } /// Formats a clause header, handling the case where the clause header is suppressed and should not be formatted. /// /// Calls the `formatter` to format the content of the `header`, except if the `trailing_colon_comment` is a `fmt: skip` suppression comment. /// Takes care of formatting the `trailing_colon_comment` and adds the `:` at the end of the header. pub(crate) fn clause_header<'a, 'ast, Content>( header: ClauseHeader<'a>, trailing_colon_comment: &'a [SourceComment], formatter: &'a Content, ) -> FormatClauseHeader<'a, 'ast> where Content: Format<PyFormatContext<'ast>>, { FormatClauseHeader { header, formatter: Argument::new(formatter), leading_comments: None, trailing_colon_comment, } } impl<'ast> Format<PyFormatContext<'ast>> for FormatClauseHeader<'_, 'ast> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> { if let Some((leading_comments, last_node)) = self.leading_comments { leading_alternate_branch_comments(leading_comments, last_node).fmt(f)?; } if has_skip_comment(self.trailing_colon_comment, f.context().source()) { write_suppressed_clause_header(self.header, f)?; } else { // Write a source map entry for the colon for range formatting to support formatting the clause header without // the clause body. Avoid computing `self.header.range()` otherwise because it's somewhat involved. let clause_end = if f.options().source_map_generation().is_enabled() { Some(source_position( self.header.range(f.context().source())?.end(), )) } else { None }; write!( f, [Arguments::from(&self.formatter), token(":"), clause_end] )?; } trailing_comments(self.trailing_colon_comment).fmt(f) } } struct FormatClauseBody<'a> { body: &'a Suite, kind: SuiteKind, trailing_comments: &'a [SourceComment], } fn clause_body<'a>( body: &'a Suite, kind: SuiteKind, trailing_comments: &'a [SourceComment], ) -> FormatClauseBody<'a> { FormatClauseBody { body, kind, trailing_comments, } } impl Format<PyFormatContext<'_>> for FormatClauseBody<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { // In stable, stubs are only collapsed in stub files, in preview stubs in functions // or classes are collapsed too let should_collapse_stub = f.options().source_type().is_stub() || matches!(self.kind, SuiteKind::Function | SuiteKind::Class); if should_collapse_stub && let Some(ellipsis) = as_only_an_ellipsis(self.body, f.context().comments()) && self.trailing_comments.is_empty() { write!(f, [space(), ellipsis.format(), hard_line_break()]) } else { write!( f, [ trailing_comments(self.trailing_comments), block_indent(&self.body.format().with_options(self.kind)) ] ) } } } pub(crate) struct FormatClause<'a, 'ast> { header: ClauseHeader<'a>, /// How to format the clause header header_formatter: Argument<'a, PyFormatContext<'ast>>, /// Leading comments coming before the branch, together with the previous node, if any. Only relevant /// for alternate branches. leading_comments: Option<(&'a [SourceComment], Option<AnyNodeRef<'a>>)>, /// The trailing comments coming after the colon. trailing_colon_comment: &'a [SourceComment], body: &'a Suite, kind: SuiteKind, } impl<'a, 'ast> FormatClause<'a, 'ast> { /// Sets the leading comments that precede an alternate branch. #[must_use] pub(crate) fn with_leading_comments<N>( mut self, comments: &'a [SourceComment], last_node: Option<N>, ) -> Self where N: Into<AnyNodeRef<'a>>, { self.leading_comments = Some((comments, last_node.map(Into::into))); self } fn clause_header(&self) -> FormatClauseHeader<'a, 'ast> { FormatClauseHeader { header: self.header, formatter: self.header_formatter, leading_comments: self.leading_comments, trailing_colon_comment: self.trailing_colon_comment, } } fn clause_body(&self) -> FormatClauseBody<'a> { clause_body(self.body, self.kind, self.trailing_colon_comment) } } /// Formats a clause, handling the case where the compound /// statement lies on a single line with `# fmt: skip` and /// should be suppressed. pub(crate) fn clause<'a, 'ast, Content>( header: ClauseHeader<'a>, header_formatter: &'a Content, trailing_colon_comment: &'a [SourceComment], body: &'a Suite, kind: SuiteKind, ) -> FormatClause<'a, 'ast> where Content: Format<PyFormatContext<'ast>>, { FormatClause { header, header_formatter: Argument::new(header_formatter), leading_comments: None, trailing_colon_comment, body, kind, } } impl<'ast> Format<PyFormatContext<'ast>> for FormatClause<'_, 'ast> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> { match should_suppress_clause(self, f)? { SuppressClauseHeader::Yes { last_child_in_clause, } => write_suppressed_clause(self, f, last_child_in_clause), SuppressClauseHeader::No => { write!(f, [self.clause_header(), self.clause_body()]) } } } } /// Finds the range of `keyword` starting the search at `start_position`. /// /// If the start position is at the end of the previous statement, the /// search will skip the optional semi-colon at the end of that statement. /// Other than this, we expect only trivia between the `start_position` /// and the keyword. fn find_keyword( start_position: StartPosition, keyword: SimpleTokenKind, source: &str, ) -> FormatResult<TextRange> { let next_token = match start_position { StartPosition::ClauseStart(text_size) => SimpleTokenizer::starts_at(text_size, source) .skip_trivia() .next(), StartPosition::LastStatement(text_size) => { let mut tokenizer = SimpleTokenizer::starts_at(text_size, source).skip_trivia(); let mut token = tokenizer.next(); // If the last statement ends with a semi-colon, skip it. if matches!( token, Some(SimpleToken { kind: SimpleTokenKind::Semi, .. }) ) { token = tokenizer.next(); } token } }; match next_token { Some(token) if token.kind() == keyword => Ok(token.range()), Some(other) => { debug_assert!( false, "Expected the keyword token {keyword:?} but found the token {other:?} instead." ); Err(FormatError::syntax_error( "Expected the keyword token but found another token instead.", )) } None => { debug_assert!( false, "Expected the keyword token {keyword:?} but reached the end of the source instead." ); Err(FormatError::syntax_error( "Expected the case header keyword token but reached the end of the source instead.", )) } } } /// Offset directly before clause header. /// /// Can either be the beginning of the clause header /// or the end of the last statement preceding the clause. #[derive(Clone, Copy)] enum StartPosition { /// The beginning of a clause header ClauseStart(TextSize), /// The end of the last statement in the suite preceding a clause. /// /// For example: /// ```python /// if cond: /// a /// b /// c; /// # ...^here /// else: /// d /// ``` LastStatement(TextSize), } impl StartPosition { fn clause_start(ranged: impl Ranged) -> Self { Self::ClauseStart(ranged.start()) } } /// Returns the range of the `:` ending the clause header or `Err` if the colon can't be found. fn colon_range(after_keyword_or_condition: TextSize, source: &str) -> FormatResult<TextRange> { let mut tokenizer = SimpleTokenizer::starts_at(after_keyword_or_condition, source) .skip_trivia() .skip_while(|token| { matches!( token.kind(), SimpleTokenKind::RParen | SimpleTokenKind::Comma ) }); match tokenizer.next() { Some(SimpleToken { kind: SimpleTokenKind::Colon, range, }) => Ok(range), Some(token) => { debug_assert!( false, "Expected the colon marking the end of the case header but found {token:?} instead." ); Err(FormatError::syntax_error( "Expected colon marking the end of the case header but found another token instead.", )) } None => { debug_assert!( false, "Expected the colon marking the end of the case header but found the end of the range." ); Err(FormatError::syntax_error( "Expected the colon marking the end of the case header but found the end of the range.", )) } } } fn should_suppress_clause<'a>( clause: &FormatClause<'a, '_>, f: &mut Formatter<PyFormatContext<'_>>, ) -> FormatResult<SuppressClauseHeader<'a>> { let source = f.context().source(); let Some(last_child_in_clause) = clause.header.last_child_in_clause() else { return Ok(SuppressClauseHeader::No); }; // Early return if we don't have a skip comment // to avoid computing header range in the common case if !has_skip_comment( f.context().comments().trailing(last_child_in_clause), source, ) { return Ok(SuppressClauseHeader::No); } let clause_start = clause.header.range(source)?.end(); let clause_range = TextRange::new(clause_start, last_child_in_clause.end()); // Only applies to clauses on a single line if source.contains_line_break(clause_range) { return Ok(SuppressClauseHeader::No); } Ok(SuppressClauseHeader::Yes { last_child_in_clause, }) } #[cold] fn write_suppressed_clause( clause: &FormatClause, f: &mut Formatter<PyFormatContext<'_>>, last_child_in_clause: AnyNodeRef, ) -> FormatResult<()> { if let Some((leading_comments, last_node)) = clause.leading_comments { leading_alternate_branch_comments(leading_comments, last_node).fmt(f)?; } let header = clause.header; let clause_start = header.first_keyword_range(f.context().source())?.start(); let comments = f.context().comments().clone(); let clause_end = last_child_in_clause.end(); // Write the outer comments and format the node as verbatim write!( f, [ source_position(clause_start), verbatim_text(TextRange::new(clause_start, clause_end)), source_position(clause_end), trailing_comments(comments.trailing(last_child_in_clause)), hard_line_break() ] )?; // We mark comments in the header as formatted as in // the implementation of [`write_suppressed_clause_header`]. // // Note that the header may be multi-line and contain // various comments since we only require that the range // starting at the _colon_ and ending at the `# fmt: skip` // fits on one line. header.visit(&mut |child| { for comment in comments.leading_trailing(child) { comment.mark_formatted(); } comments.mark_verbatim_node_comments_formatted(child); }); // Similarly we mark the comments in the body as formatted. // Note that the trailing comments for the last child in the // body have already been handled above. for stmt in clause.body { comments.mark_verbatim_node_comments_formatted(stmt.into()); } Ok(()) } enum SuppressClauseHeader<'a> { No, Yes { last_child_in_clause: AnyNodeRef<'a>, }, }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_for.rs
crates/ruff_python_formatter/src/statement/stmt_for.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::{Expr, Stmt, StmtFor}; use ruff_text_size::Ranged; use crate::expression::expr_tuple::TupleParentheses; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::prelude::*; use crate::statement::clause::{ClauseHeader, ElseClause, clause}; use crate::statement::suite::SuiteKind; #[derive(Debug)] struct ExprTupleWithoutParentheses<'a>(&'a Expr); impl Format<PyFormatContext<'_>> for ExprTupleWithoutParentheses<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { match self.0 { Expr::Tuple(expr_tuple) => expr_tuple .format() .with_options(TupleParentheses::NeverPreserve) .fmt(f), other => maybe_parenthesize_expression(other, self.0, Parenthesize::IfBreaks).fmt(f), } } } #[derive(Default)] pub struct FormatStmtFor; impl FormatNodeRule<StmtFor> for FormatStmtFor { fn fmt_fields(&self, item: &StmtFor, f: &mut PyFormatter) -> FormatResult<()> { let StmtFor { is_async, target, iter, body, orelse, range: _, node_index: _, } = item; let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(item); let body_start = body.first().map_or(iter.end(), Stmt::start); let or_else_comments_start = dangling_comments.partition_point(|comment| comment.end() < body_start); let (trailing_condition_comments, or_else_comments) = dangling_comments.split_at(or_else_comments_start); write!( f, [clause( ClauseHeader::For(item), &format_args![ is_async.then_some(format_args![token("async"), space()]), token("for"), space(), ExprTupleWithoutParentheses(target), space(), token("in"), space(), maybe_parenthesize_expression(iter, item, Parenthesize::IfBreaks), ], trailing_condition_comments, body, SuiteKind::other(orelse.is_empty()), ),] )?; if orelse.is_empty() { debug_assert!(or_else_comments.is_empty()); } else { // Split between leading comments before the `else` keyword and end of line comments at the end of // the `else:` line. let trailing_start = or_else_comments.partition_point(|comment| comment.line_position().is_own_line()); let (leading, trailing) = or_else_comments.split_at(trailing_start); write!( f, [clause( ClauseHeader::OrElse(ElseClause::For(item)), &token("else"), trailing, orelse, SuiteKind::other(true), ) .with_leading_comments(leading, body.last())] )?; } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_continue.rs
crates/ruff_python_formatter/src/statement/stmt_continue.rs
use ruff_python_ast::StmtContinue; use crate::comments::SourceComment; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtContinue; impl FormatNodeRule<StmtContinue> for FormatStmtContinue { fn fmt_fields(&self, _item: &StmtContinue, f: &mut PyFormatter) -> FormatResult<()> { token("continue").fmt(f) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/mod.rs
crates/ruff_python_formatter/src/statement/mod.rs
use ruff_formatter::{FormatOwnedWithRule, FormatRefWithRule}; use ruff_python_ast::{AnyNodeRef, Stmt}; use ruff_python_trivia::{SimpleToken, SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange}; use crate::prelude::*; pub(super) mod clause; pub(crate) mod stmt_ann_assign; pub(crate) mod stmt_assert; pub(crate) mod stmt_assign; pub(crate) mod stmt_aug_assign; pub(crate) mod stmt_break; pub(crate) mod stmt_class_def; pub(crate) mod stmt_continue; pub(crate) mod stmt_delete; pub(crate) mod stmt_expr; pub(crate) mod stmt_for; pub(crate) mod stmt_function_def; pub(crate) mod stmt_global; pub(crate) mod stmt_if; pub(crate) mod stmt_import; pub(crate) mod stmt_import_from; pub(crate) mod stmt_ipy_escape_command; pub(crate) mod stmt_match; pub(crate) mod stmt_nonlocal; pub(crate) mod stmt_pass; pub(crate) mod stmt_raise; pub(crate) mod stmt_return; pub(crate) mod stmt_try; pub(crate) mod stmt_type_alias; pub(crate) mod stmt_while; pub(crate) mod stmt_with; pub(crate) mod suite; #[derive(Default)] pub struct FormatStmt; impl FormatRule<Stmt, PyFormatContext<'_>> for FormatStmt { fn fmt(&self, item: &Stmt, f: &mut PyFormatter) -> FormatResult<()> { match item { Stmt::FunctionDef(x) => x.format().fmt(f), Stmt::ClassDef(x) => x.format().fmt(f), Stmt::Return(x) => x.format().fmt(f), Stmt::Delete(x) => x.format().fmt(f), Stmt::Assign(x) => x.format().fmt(f), Stmt::AugAssign(x) => x.format().fmt(f), Stmt::AnnAssign(x) => x.format().fmt(f), Stmt::For(x) => x.format().fmt(f), Stmt::While(x) => x.format().fmt(f), Stmt::If(x) => x.format().fmt(f), Stmt::With(x) => x.format().fmt(f), Stmt::Match(x) => x.format().fmt(f), Stmt::Raise(x) => x.format().fmt(f), Stmt::Try(x) => x.format().fmt(f), Stmt::Assert(x) => x.format().fmt(f), Stmt::Import(x) => x.format().fmt(f), Stmt::ImportFrom(x) => x.format().fmt(f), Stmt::Global(x) => x.format().fmt(f), Stmt::Nonlocal(x) => x.format().fmt(f), Stmt::Expr(x) => x.format().fmt(f), Stmt::Pass(x) => x.format().fmt(f), Stmt::Break(x) => x.format().fmt(f), Stmt::Continue(x) => x.format().fmt(f), Stmt::TypeAlias(x) => x.format().fmt(f), Stmt::IpyEscapeCommand(x) => x.format().fmt(f), } } } impl<'ast> AsFormat<PyFormatContext<'ast>> for Stmt { type Format<'a> = FormatRefWithRule<'a, Stmt, FormatStmt, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatStmt) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for Stmt { type Format = FormatOwnedWithRule<Stmt, FormatStmt, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatStmt) } } /// Returns the range of the semicolon terminating the statement or `None` if the statement /// isn't terminated by a semicolon. pub(super) fn trailing_semicolon(node: AnyNodeRef, source: &str) -> Option<TextRange> { debug_assert!(node.is_statement()); let tokenizer = SimpleTokenizer::starts_at(node.end(), source); let next_token = tokenizer .take_while(|token| !token.kind().is_comment()) .find(|token| !token.kind().is_trivia()); if let Some(SimpleToken { kind: SimpleTokenKind::Semi, range, }) = next_token { Some(range) } else { None } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_with.rs
crates/ruff_python_formatter/src/statement/stmt_with.rs
use ruff_formatter::{FormatContext, FormatError, format_args, write}; use ruff_python_ast::PythonVersion; use ruff_python_ast::{StmtWith, WithItem}; use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange}; use crate::builders::parenthesize_if_expands; use crate::comments::SourceComment; use crate::expression::can_omit_optional_parentheses; use crate::expression::parentheses::{ is_expression_parenthesized, optional_parentheses, parenthesized, }; use crate::other::commas; use crate::other::with_item::WithItemLayout; use crate::prelude::*; use crate::statement::clause::{ClauseHeader, clause}; use crate::statement::suite::SuiteKind; #[derive(Default)] pub struct FormatStmtWith; impl FormatNodeRule<StmtWith> for FormatStmtWith { fn fmt_fields(&self, with_stmt: &StmtWith, f: &mut PyFormatter) -> FormatResult<()> { // The `with` statement can have one dangling comment on the open parenthesis, like: // ```python // with ( # comment // CtxManager() as example // ): // ... // ``` // // Any other dangling comments are trailing comments on the colon, like: // ```python // with CtxManager() as example: # comment // ... // ``` let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(with_stmt); let partition_point = dangling_comments.partition_point(|comment| { with_stmt .items .first() .is_some_and(|with_item| with_item.start() > comment.start()) }); let (parenthesized_comments, colon_comments) = dangling_comments.split_at(partition_point); write!( f, [clause( ClauseHeader::With(with_stmt), &format_with(|f| { write!( f, [ with_stmt .is_async .then_some(format_args![token("async"), space()]), token("with"), space() ] )?; let layout = WithItemsLayout::from_statement( with_stmt, f.context(), parenthesized_comments, )?; match layout { WithItemsLayout::SingleWithTarget(single) => { optional_parentheses(&single.format().with_options( WithItemLayout::ParenthesizedContextManagers { single: true }, )) .fmt(f) } WithItemsLayout::SingleWithoutTarget(single) => single .format() .with_options(WithItemLayout::SingleWithoutTarget) .fmt(f), WithItemsLayout::SingleParenthesizedContextManager(single) => single .format() .with_options(WithItemLayout::SingleParenthesizedContextManager) .fmt(f), WithItemsLayout::ParenthesizeIfExpands => { parenthesize_if_expands(&format_with(|f| { let mut joiner = f.join_comma_separated(with_stmt.body.first().unwrap().start()); for item in &with_stmt.items { joiner.entry_with_line_separator( item, &item.format().with_options( WithItemLayout::ParenthesizedContextManagers { single: with_stmt.items.len() == 1, }, ), soft_line_break_or_space(), ); } joiner.finish() })) .fmt(f) } WithItemsLayout::Python38OrOlder => f .join_with(format_args![token(","), space()]) .entries(with_stmt.items.iter().map(|item| { item.format().with_options(WithItemLayout::Python38OrOlder { single: with_stmt.items.len() == 1, }) })) .finish(), WithItemsLayout::Parenthesized => parenthesized( "(", &format_with(|f: &mut PyFormatter| { let mut joiner = f.join_comma_separated(with_stmt.body.first().unwrap().start()); for item in &with_stmt.items { joiner.entry( item, &item.format().with_options( WithItemLayout::ParenthesizedContextManagers { single: with_stmt.items.len() == 1, }, ), ); } joiner.finish() }), ")", ) .with_dangling_comments(parenthesized_comments) .fmt(f), } }), colon_comments, &with_stmt.body, SuiteKind::other(true), )] ) } } #[derive(Clone, Copy, Debug)] enum WithItemsLayout<'a> { /// The with statement's only item has a parenthesized context manager. /// /// ```python /// with ( /// a + b /// ): /// ... /// /// with ( /// a + b /// ) as b: /// ... /// ``` /// /// In this case, prefer keeping the parentheses around the context expression instead of parenthesizing the entire /// with item. /// /// Ensure that this layout is compatible with [`Self::SingleWithoutTarget`] because removing the parentheses /// results in the formatter taking that layout when formatting the file again SingleParenthesizedContextManager(&'a WithItem), /// The with statement's only item has no target. /// /// ```python /// with a + b: /// ... /// ``` /// /// In this case, use /// [`maybe_parenthesize_expression`](crate::expression::maybe_parenthesize_expression) to /// format the context expression to get the exact same formatting as when formatting an /// expression in any other clause header. /// /// Only used for Python 3.9+ /// /// Be careful that [`Self::SingleParenthesizedContextManager`] and this layout are compatible because /// adding parentheses around a [`WithItem`] will result in the context expression being parenthesized in /// the next formatting pass. SingleWithoutTarget(&'a WithItem), /// It's a single with item with a target. Use the optional parentheses layout (see [`optional_parentheses`]) /// to mimic the `maybe_parenthesize_expression` behavior. /// /// ```python /// with ( /// a + b as b /// ): /// ... /// ``` /// /// Only used for Python 3.9+ SingleWithTarget(&'a WithItem), /// The target python version doesn't support parenthesized context managers because it is Python 3.8 or older. /// /// In this case, never add parentheses and join the with items with spaces. /// /// ```python /// with ContextManager1( /// aaaaaaaaaaaaaaa, b /// ), ContextManager2(), ContextManager3(), ContextManager4(): /// pass /// ``` Python38OrOlder, /// Wrap the with items in parentheses if they don't fit on a single line and join them by soft line breaks. /// /// ```python /// with ( /// ContextManager1(aaaaaaaaaaaaaaa, b), /// ContextManager1(), /// ContextManager1(), /// ContextManager1(), /// ): /// pass /// ``` /// /// Only used for Python 3.9+. ParenthesizeIfExpands, /// Always parenthesize because the context managers open-parentheses have a trailing comment: /// /// ```python /// with ( # comment /// CtxManager() as example /// ): /// ... /// ``` /// /// Or because it is a single item with a trailing or leading comment. /// /// ```python /// with ( /// # leading /// CtxManager() /// # trailing /// ): pass /// ``` Parenthesized, } impl<'a> WithItemsLayout<'a> { fn from_statement( with: &'a StmtWith, context: &PyFormatContext, parenthesized_comments: &[SourceComment], ) -> FormatResult<Self> { // The with statement already has parentheses around the entire with items. Guaranteed to be Python 3.9 or newer // ``` // with ( # comment // CtxManager() as example // ): // pass // ``` if !parenthesized_comments.is_empty() { return Ok(Self::Parenthesized); } // A trailing comma at the end guarantees that the context managers are parenthesized and that it is Python 3.9 or newer syntax. // ```python // with ( # comment // CtxManager() as example, // ): // pass // ``` if has_magic_trailing_comma(with, context) { return Ok(Self::ParenthesizeIfExpands); } if let [single] = with.items.as_slice() { // If the with item itself has comments (not the context expression), then keep the parentheses // ```python // with ( // # leading // a // ): pass // ``` if context.comments().has_leading(single) || context.comments().has_trailing(single) { return Ok(Self::Parenthesized); } // Preserve the parentheses around the context expression instead of parenthesizing the entire // with items. if is_expression_parenthesized( (&single.context_expr).into(), context.comments().ranges(), context.source(), ) { return Ok(Self::SingleParenthesizedContextManager(single)); } } let can_parenthesize = context.options().target_version() >= PythonVersion::PY39 || are_with_items_parenthesized(with, context)?; // If the target version doesn't support parenthesized context managers and they aren't // parenthesized by the user, bail out. if !can_parenthesize { return Ok(Self::Python38OrOlder); } Ok(match with.items.as_slice() { [single] => { if single.optional_vars.is_none() { Self::SingleWithoutTarget(single) } else if can_omit_optional_parentheses(&single.context_expr, context) { Self::SingleWithTarget(single) } else { Self::ParenthesizeIfExpands } } // Always parenthesize multiple items [..] => Self::ParenthesizeIfExpands, }) } } fn has_magic_trailing_comma(with: &StmtWith, context: &PyFormatContext) -> bool { let Some(last_item) = with.items.last() else { return false; }; commas::has_magic_trailing_comma(TextRange::new(last_item.end(), with.end()), context) } fn are_with_items_parenthesized(with: &StmtWith, context: &PyFormatContext) -> FormatResult<bool> { let [first_item, _, ..] = with.items.as_slice() else { return Ok(false); }; let before_first_item = TextRange::new(with.start(), first_item.start()); let mut tokenizer = SimpleTokenizer::new(context.source(), before_first_item) .skip_trivia() .skip_while(|t| t.kind() == SimpleTokenKind::Async); let with_keyword = tokenizer.next().ok_or(FormatError::syntax_error( "Expected a with keyword, didn't find any token", ))?; debug_assert_eq!( with_keyword.kind(), SimpleTokenKind::With, "Expected with keyword but at {with_keyword:?}" ); match tokenizer.next() { Some(left_paren) => { debug_assert_eq!(left_paren.kind(), SimpleTokenKind::LParen); Ok(true) } None => Ok(false), } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_import.rs
crates/ruff_python_formatter/src/statement/stmt_import.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::StmtImport; use crate::comments::SourceComment; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtImport; impl FormatNodeRule<StmtImport> for FormatStmtImport { fn fmt_fields(&self, item: &StmtImport, f: &mut PyFormatter) -> FormatResult<()> { let StmtImport { names, range: _, node_index: _, } = item; let names = format_with(|f| { f.join_with(&format_args![token(","), space()]) .entries(names.iter().formatted()) .finish() }); write!(f, [token("import"), space(), names]) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_ipy_escape_command.rs
crates/ruff_python_formatter/src/statement/stmt_ipy_escape_command.rs
use ruff_python_ast::StmtIpyEscapeCommand; use ruff_text_size::Ranged; use crate::comments::SourceComment; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtIpyEscapeCommand; impl FormatNodeRule<StmtIpyEscapeCommand> for FormatStmtIpyEscapeCommand { fn fmt_fields(&self, item: &StmtIpyEscapeCommand, f: &mut PyFormatter) -> FormatResult<()> { source_text_slice(item.range()).fmt(f) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_return.rs
crates/ruff_python_formatter/src/statement/stmt_return.rs
use ruff_formatter::write; use ruff_python_ast::{Expr, StmtReturn}; use crate::comments::SourceComment; use crate::expression::expr_tuple::TupleParentheses; use crate::statement::stmt_assign::FormatStatementsLastExpression; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtReturn; impl FormatNodeRule<StmtReturn> for FormatStmtReturn { fn fmt_fields(&self, item: &StmtReturn, f: &mut PyFormatter) -> FormatResult<()> { let StmtReturn { range: _, node_index: _, value, } = item; token("return").fmt(f)?; match value.as_deref() { Some(Expr::Tuple(tuple)) if !f.context().comments().has_leading(tuple) => { write!( f, [ space(), tuple .format() .with_options(TupleParentheses::OptionalParentheses) ] ) } Some(value) => { write!( f, [ space(), FormatStatementsLastExpression::left_to_right(value, item) ] ) } None => Ok(()), } } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_type_alias.rs
crates/ruff_python_formatter/src/statement/stmt_type_alias.rs
use ruff_formatter::write; use ruff_python_ast::StmtTypeAlias; use crate::comments::SourceComment; use crate::statement::stmt_assign::{ AnyAssignmentOperator, AnyBeforeOperator, FormatStatementsLastExpression, }; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatStmtTypeAlias; impl FormatNodeRule<StmtTypeAlias> for FormatStmtTypeAlias { fn fmt_fields(&self, item: &StmtTypeAlias, f: &mut PyFormatter) -> FormatResult<()> { let StmtTypeAlias { name, type_params, value, range: _, node_index: _, } = item; write!(f, [token("type"), space(), name.as_ref().format()])?; if let Some(type_params) = type_params { return FormatStatementsLastExpression::RightToLeft { before_operator: AnyBeforeOperator::TypeParams(type_params), operator: AnyAssignmentOperator::Assign, value, statement: item.into(), } .fmt(f); } write!( f, [ space(), token("="), space(), FormatStatementsLastExpression::left_to_right(value, item) ] ) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_nonlocal.rs
crates/ruff_python_formatter/src/statement/stmt_nonlocal.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::StmtNonlocal; use crate::comments::SourceComment; use crate::has_skip_comment; use crate::prelude::*; #[derive(Default)] pub struct FormatStmtNonlocal; impl FormatNodeRule<StmtNonlocal> for FormatStmtNonlocal { fn fmt_fields(&self, item: &StmtNonlocal, f: &mut PyFormatter) -> FormatResult<()> { // Join the `nonlocal` names, breaking across continuation lines if necessary, unless the // `nonlocal` statement has a trailing comment, in which case, breaking the names would // move the comment "off" of the `nonlocal` statement. if f.context().comments().has_trailing(item) { let joined = format_with(|f| { f.join_with(format_args![token(","), space()]) .entries(item.names.iter().formatted()) .finish() }); write!(f, [token("nonlocal"), space(), &joined]) } else { let joined = format_with(|f| { f.join_with(&format_args![ token(","), space(), if_group_breaks(&token("\\")), soft_line_break(), ]) .entries(item.names.iter().formatted()) .finish() }); write!( f, [ token("nonlocal"), space(), group(&format_args!( if_group_breaks(&token("\\")), soft_line_break(), soft_block_indent(&joined) )) ] ) } } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/statement/stmt_global.rs
crates/ruff_python_formatter/src/statement/stmt_global.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::StmtGlobal; use crate::comments::SourceComment; use crate::has_skip_comment; use crate::prelude::*; #[derive(Default)] pub struct FormatStmtGlobal; impl FormatNodeRule<StmtGlobal> for FormatStmtGlobal { fn fmt_fields(&self, item: &StmtGlobal, f: &mut PyFormatter) -> FormatResult<()> { // Join the `global` names, breaking across continuation lines if necessary, unless the // `global` statement has a trailing comment, in which case, breaking the names would // move the comment "off" of the `global` statement. if f.context().comments().has_trailing(item) { let joined = format_with(|f| { f.join_with(format_args![token(","), space()]) .entries(item.names.iter().formatted()) .finish() }); write!(f, [token("global"), space(), &joined]) } else { let joined = format_with(|f| { f.join_with(&format_args![ token(","), space(), if_group_breaks(&token("\\")), soft_line_break(), ]) .entries(item.names.iter().formatted()) .finish() }); write!( f, [ token("global"), space(), group(&format_args!( if_group_breaks(&token("\\")), soft_line_break(), soft_block_indent(&joined) )) ] ) } } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_string_literal.rs
crates/ruff_python_formatter/src/expression/expr_string_literal.rs
use crate::builders::parenthesize_if_expands; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, in_parentheses_only_group, }; use crate::other::string_literal::StringLiteralKind; use crate::prelude::*; use crate::string::implicit::{ FormatImplicitConcatenatedStringExpanded, FormatImplicitConcatenatedStringFlat, ImplicitConcatenatedLayout, }; use crate::string::{StringLikeExtensions, implicit::FormatImplicitConcatenatedString}; use ruff_formatter::FormatRuleWithOptions; use ruff_python_ast::{AnyNodeRef, ExprStringLiteral, StringLike}; #[derive(Default)] pub struct FormatExprStringLiteral { kind: StringLiteralKind, } impl FormatRuleWithOptions<ExprStringLiteral, PyFormatContext<'_>> for FormatExprStringLiteral { type Options = StringLiteralKind; fn with_options(mut self, options: Self::Options) -> Self { self.kind = options; self } } impl FormatNodeRule<ExprStringLiteral> for FormatExprStringLiteral { fn fmt_fields(&self, item: &ExprStringLiteral, f: &mut PyFormatter) -> FormatResult<()> { if let Some(string_literal) = item.as_single_part_string() { string_literal.format().with_options(self.kind).fmt(f) } else { // Always join strings that aren't parenthesized and thus, always on a single line. if !f.context().node_level().is_parenthesized() { if let Some(mut format_flat) = FormatImplicitConcatenatedStringFlat::new(item.into(), f.context()) { format_flat.set_docstring(self.kind.is_docstring()); return format_flat.fmt(f); } // ```py // def test(): // ( // r"a" // "b" // ) // ``` if self.kind.is_docstring() { return parenthesize_if_expands( &FormatImplicitConcatenatedStringExpanded::new( item.into(), ImplicitConcatenatedLayout::Multipart, ), ) .fmt(f); } } in_parentheses_only_group(&FormatImplicitConcatenatedString::new(item)).fmt(f) } } } impl NeedsParentheses for ExprStringLiteral { fn needs_parentheses( &self, _parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if self.value.is_implicit_concatenated() { OptionalParentheses::Multiline } else if StringLike::String(self).is_multiline(context) { OptionalParentheses::Never } else { OptionalParentheses::BestFit } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_ipy_escape_command.rs
crates/ruff_python_formatter/src/expression/expr_ipy_escape_command.rs
use ruff_python_ast::ExprIpyEscapeCommand; use ruff_text_size::Ranged; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprIpyEscapeCommand; impl FormatNodeRule<ExprIpyEscapeCommand> for FormatExprIpyEscapeCommand { fn fmt_fields(&self, item: &ExprIpyEscapeCommand, f: &mut PyFormatter) -> FormatResult<()> { source_text_slice(item.range()).fmt(f) } } impl NeedsParentheses for ExprIpyEscapeCommand { fn needs_parentheses( &self, _parent: ruff_python_ast::AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_bytes_literal.rs
crates/ruff_python_formatter/src/expression/expr_bytes_literal.rs
use ruff_python_ast::ExprBytesLiteral; use ruff_python_ast::{AnyNodeRef, StringLike}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, in_parentheses_only_group, }; use crate::prelude::*; use crate::string::implicit::FormatImplicitConcatenatedStringFlat; use crate::string::{StringLikeExtensions, implicit::FormatImplicitConcatenatedString}; #[derive(Default)] pub struct FormatExprBytesLiteral; impl FormatNodeRule<ExprBytesLiteral> for FormatExprBytesLiteral { fn fmt_fields(&self, item: &ExprBytesLiteral, f: &mut PyFormatter) -> FormatResult<()> { if let Some(bytes_literal) = item.as_single_part_bytestring() { bytes_literal.format().fmt(f) } else { // Always join byte literals that aren't parenthesized and thus, always on a single line. if !f.context().node_level().is_parenthesized() { if let Some(format_flat) = FormatImplicitConcatenatedStringFlat::new(item.into(), f.context()) { return format_flat.fmt(f); } } in_parentheses_only_group(&FormatImplicitConcatenatedString::new(item)).fmt(f) } } } impl NeedsParentheses for ExprBytesLiteral { fn needs_parentheses( &self, _parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if self.value.is_implicit_concatenated() { OptionalParentheses::Multiline } else if StringLike::Bytes(self).is_multiline(context) { OptionalParentheses::Never } else { OptionalParentheses::BestFit } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_lambda.rs
crates/ruff_python_formatter/src/expression/expr_lambda.rs
use ruff_formatter::{FormatRuleWithOptions, RemoveSoftLinesBuffer, format_args, write}; use ruff_python_ast::{AnyNodeRef, Expr, ExprLambda}; use ruff_text_size::Ranged; use crate::builders::parenthesize_if_expands; use crate::comments::{SourceComment, dangling_comments, leading_comments, trailing_comments}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parentheses, is_expression_parenthesized, }; use crate::expression::{CallChainLayout, has_own_parentheses}; use crate::other::parameters::ParametersParentheses; use crate::prelude::*; use crate::preview::is_parenthesize_lambda_bodies_enabled; #[derive(Default)] pub struct FormatExprLambda { layout: ExprLambdaLayout, } impl FormatNodeRule<ExprLambda> for FormatExprLambda { fn fmt_fields(&self, item: &ExprLambda, f: &mut PyFormatter) -> FormatResult<()> { let ExprLambda { range: _, node_index: _, parameters, body, } = item; let body = &**body; let parameters = parameters.as_deref(); let comments = f.context().comments().clone(); let dangling = comments.dangling(item); let preview = is_parenthesize_lambda_bodies_enabled(f.context()); write!(f, [token("lambda")])?; // Format any dangling comments before the parameters, but save any dangling comments after // the parameters/after the header to be formatted with the body below. let dangling_header_comments = if let Some(parameters) = parameters { // In this context, a dangling comment can either be a comment between the `lambda` and the // parameters, or a comment between the parameters and the body. let (dangling_before_parameters, dangling_after_parameters) = dangling .split_at(dangling.partition_point(|comment| comment.end() < parameters.start())); if dangling_before_parameters.is_empty() { // If the parameters have a leading comment, insert a hard line break. This // comment is associated as a leading comment on the parameters: // // ```py // ( // lambda // * # comment // x: // x // ) // ``` // // so a hard line break is needed to avoid formatting it like: // // ```py // ( // lambda # comment // *x: x // ) // ``` // // which is unstable because it's missing the second space before the comment. // // Inserting the line break causes it to format like: // // ```py // ( // lambda // # comment // *x :x // ) // ``` // // which is also consistent with the formatting in the presence of an actual // dangling comment on the lambda: // // ```py // ( // lambda # comment 1 // * # comment 2 // x: // x // ) // ``` // // formats to: // // ```py // ( // lambda # comment 1 // # comment 2 // *x: x // ) // ``` if comments.has_leading(parameters) { hard_line_break().fmt(f)?; } else { write!(f, [space()])?; } } else { write!(f, [dangling_comments(dangling_before_parameters)])?; } // Try to keep the parameters on a single line, unless there are intervening comments. if preview && !comments.contains_comments(parameters.into()) { let mut buffer = RemoveSoftLinesBuffer::new(f); write!( buffer, [parameters .format() .with_options(ParametersParentheses::Never)] )?; } else { write!( f, [parameters .format() .with_options(ParametersParentheses::Never)] )?; } dangling_after_parameters } else { dangling }; write!(f, [token(":")])?; if dangling_header_comments.is_empty() { write!(f, [space()])?; } else if !preview { write!(f, [dangling_comments(dangling_header_comments)])?; } if !preview { return body.format().fmt(f); } let fmt_body = FormatBody { body, dangling_header_comments, }; match self.layout { ExprLambdaLayout::Assignment => fits_expanded(&fmt_body).fmt(f), ExprLambdaLayout::Default => fmt_body.fmt(f), } } } #[derive(Debug, Default, Copy, Clone)] pub enum ExprLambdaLayout { #[default] Default, /// The [`ExprLambda`] is the direct child of an assignment expression, so it needs to use /// `fits_expanded` to prefer parenthesizing its own body before the assignment tries to /// parenthesize the whole lambda. For example, we want this formatting: /// /// ```py /// long_assignment_target = lambda x, y, z: ( /// x + y + z /// ) /// ``` /// /// instead of either of these: /// /// ```py /// long_assignment_target = ( /// lambda x, y, z: ( /// x + y + z /// ) /// ) /// /// long_assignment_target = ( /// lambda x, y, z: x + y + z /// ) /// ``` Assignment, } impl FormatRuleWithOptions<ExprLambda, PyFormatContext<'_>> for FormatExprLambda { type Options = ExprLambdaLayout; fn with_options(mut self, options: Self::Options) -> Self { self.layout = options; self } } impl NeedsParentheses for ExprLambda { fn needs_parentheses( &self, parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { if parent.is_expr_await() { OptionalParentheses::Always } else { OptionalParentheses::Multiline } } } struct FormatBody<'a> { body: &'a Expr, /// Dangling comments attached to the lambda header that should be formatted with the body. /// /// These can include both own-line and end-of-line comments. For lambdas with parameters, this /// means comments after the parameters: /// /// ```py /// ( /// lambda x, y # 1 /// # 2 /// : # 3 /// # 4 /// x + y /// ) /// ``` /// /// Or all dangling comments for lambdas without parameters: /// /// ```py /// ( /// lambda # 1 /// # 2 /// : # 3 /// # 4 /// 1 /// ) /// ``` /// /// In most cases these should formatted within the parenthesized body, as in: /// /// ```py /// ( /// lambda: ( # 1 /// # 2 /// # 3 /// # 4 /// 1 /// ) /// ) /// ``` /// /// or without `# 2`: /// /// ```py /// ( /// lambda: ( # 1 # 3 /// # 4 /// 1 /// ) /// ) /// ``` dangling_header_comments: &'a [SourceComment], } impl Format<PyFormatContext<'_>> for FormatBody<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { let FormatBody { dangling_header_comments, body, } = self; let body = *body; let comments = f.context().comments().clone(); let body_comments = comments.leading_dangling_trailing(body); if !dangling_header_comments.is_empty() { // Split the dangling header comments into trailing comments formatted with the lambda // header (1) and leading comments formatted with the body (2, 3, 4). // // ```python // ( // lambda # 1 // # 2 // : # 3 // # 4 // y // ) // ``` // // Note that these are split based on their line position rather than using // `partition_point` based on a range, for example. let (trailing_header_comments, leading_body_comments) = dangling_header_comments .split_at( dangling_header_comments .iter() .position(|comment| comment.line_position().is_own_line()) .unwrap_or(dangling_header_comments.len()), ); // If the body is parenthesized and has its own leading comments, preserve the // separation between the dangling lambda comments and the body comments. For // example, preserve this comment positioning: // // ```python // ( // lambda: # 1 // # 2 // ( # 3 // x // ) // ) // ``` // // 1 and 2 are dangling on the lambda and emitted first, followed by a hard line // break and the parenthesized body with its leading comments. // // However, when removing 2, 1 and 3 can instead be formatted on the same line: // // ```python // ( // lambda: ( # 1 # 3 // x // ) // ) // ``` let comments = f.context().comments(); if is_expression_parenthesized(body.into(), comments.ranges(), f.context().source()) && comments.has_leading(body) { trailing_comments(dangling_header_comments).fmt(f)?; // Note that `leading_body_comments` have already been formatted as part of // `dangling_header_comments` above, but their presence still determines the spacing // here. if leading_body_comments.is_empty() { space().fmt(f)?; } else { hard_line_break().fmt(f)?; } body.format().with_options(Parentheses::Always).fmt(f) } else { write!( f, [ space(), token("("), trailing_comments(trailing_header_comments), block_indent(&format_args!( leading_comments(leading_body_comments), body.format().with_options(Parentheses::Never) )), token(")") ] ) } } // If the body has comments, we always want to preserve the parentheses. This also // ensures that we correctly handle parenthesized comments, and don't need to worry // about them in the implementation below. else if body_comments.has_leading() || body_comments.has_trailing_own_line() { body.format().with_options(Parentheses::Always).fmt(f) } // Calls and subscripts require special formatting because they have their own // parentheses, but they can also have an arbitrary amount of text before the // opening parenthesis. We want to avoid cases where we keep a long callable on the // same line as the lambda parameters. For example, `db_evmtx...` in: // // ```py // transaction_count = self._query_txs_for_range( // get_count_fn=lambda from_ts, to_ts, _chain_id=chain_id: db_evmtx.count_transactions_in_range( // chain_id=_chain_id, // from_ts=from_ts, // to_ts=to_ts, // ), // ) // ``` // // should cause the whole lambda body to be parenthesized instead: // // ```py // transaction_count = self._query_txs_for_range( // get_count_fn=lambda from_ts, to_ts, _chain_id=chain_id: ( // db_evmtx.count_transactions_in_range( // chain_id=_chain_id, // from_ts=from_ts, // to_ts=to_ts, // ) // ), // ) // ``` else if matches!(body, Expr::Call(_) | Expr::Subscript(_)) { let unparenthesized = body.format().with_options(Parentheses::Never); if CallChainLayout::from_expression( body.into(), comments.ranges(), f.context().source(), ) .is_fluent() { parenthesize_if_expands(&unparenthesized).fmt(f) } else { let unparenthesized = unparenthesized.memoized(); if unparenthesized.inspect(f)?.will_break() { expand_parent().fmt(f)?; } best_fitting![ // body all flat unparenthesized, // body expanded group(&unparenthesized).should_expand(true), // parenthesized format_args![token("("), block_indent(&unparenthesized), token(")")] ] .fmt(f) } } // For other cases with their own parentheses, such as lists, sets, dicts, tuples, // etc., we can just format the body directly. Their own formatting results in the // lambda being formatted well too. For example: // // ```py // lambda xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz: [xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz] // ``` // // gets formatted as: // // ```py // lambda xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz: [ // xxxxxxxxxxxxxxxxxxxx, // yyyyyyyyyyyyyyyyyyyy, // zzzzzzzzzzzzzzzzzzzz // ] // ``` else if has_own_parentheses(body, f.context()).is_some() { body.format().fmt(f) } // Finally, for expressions without their own parentheses, use // `parenthesize_if_expands` to add parentheses around the body, only if it expands // across multiple lines. The `Parentheses::Never` here also removes unnecessary // parentheses around lambda bodies that fit on one line. For example: // // ```py // lambda xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz: xxxxxxxxxxxxxxxxxxxx + yyyyyyyyyyyyyyyyyyyy + zzzzzzzzzzzzzzzzzzzz // ``` // // is formatted as: // // ```py // lambda xxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzz: ( // xxxxxxxxxxxxxxxxxxxx + yyyyyyyyyyyyyyyyyyyy + zzzzzzzzzzzzzzzzzzzz // ) // ``` // // while // // ```py // lambda xxxxxxxxxxxxxxxxxxxx: (xxxxxxxxxxxxxxxxxxxx + 1) // ``` // // is formatted as: // // ```py // lambda xxxxxxxxxxxxxxxxxxxx: xxxxxxxxxxxxxxxxxxxx + 1 // ``` else { parenthesize_if_expands(&body.format().with_options(Parentheses::Never)).fmt(f) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_starred.rs
crates/ruff_python_formatter/src/expression/expr_starred.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprStarred; use crate::comments::dangling_comments; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprStarred; impl FormatNodeRule<ExprStarred> for FormatExprStarred { fn fmt_fields(&self, item: &ExprStarred, f: &mut PyFormatter) -> FormatResult<()> { let ExprStarred { range: _, node_index: _, value, ctx: _, } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); write!(f, [token("*"), dangling_comments(dangling), value.format()]) } } impl NeedsParentheses for ExprStarred { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Multiline } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_dict.rs
crates/ruff_python_formatter/src/expression/expr_dict.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::{AnyNodeRef, DictItem, Expr, ExprDict}; use ruff_text_size::{Ranged, TextRange}; use crate::comments::{SourceComment, dangling_comments, leading_comments}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, empty_parenthesized, parenthesized, }; use crate::prelude::*; #[derive(Default)] pub struct FormatExprDict; impl FormatNodeRule<ExprDict> for FormatExprDict { fn fmt_fields(&self, item: &ExprDict, f: &mut PyFormatter) -> FormatResult<()> { let ExprDict { range: _, node_index: _, items, } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); let Some(first_dict_item) = items.first() else { return empty_parenthesized("{", dangling, "}").fmt(f); }; // Dangling comments can either appear after the open bracket, or around the key-value // pairs: // ```python // { # open_parenthesis_comments // x: # key_value_comments // y // } // ``` let (open_parenthesis_comments, key_value_comments) = dangling.split_at(dangling.partition_point(|comment| { comment.end() < KeyValuePair::new(first_dict_item).start() })); let format_pairs = format_with(|f| { let mut joiner = f.join_comma_separated(item.end()); let mut key_value_comments = key_value_comments; for dict_item in items { let mut key_value_pair = KeyValuePair::new(dict_item); let partition = key_value_comments .partition_point(|comment| comment.start() < key_value_pair.end()); key_value_pair = key_value_pair.with_comments(&key_value_comments[..partition]); key_value_comments = &key_value_comments[partition..]; joiner.entry(&key_value_pair, &key_value_pair); } joiner.finish() }); parenthesized("{", &format_pairs, "}") .with_dangling_comments(open_parenthesis_comments) .fmt(f) } } impl NeedsParentheses for ExprDict { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } } #[derive(Debug)] struct KeyValuePair<'a> { key: &'a Option<Expr>, value: &'a Expr, comments: &'a [SourceComment], } impl<'a> KeyValuePair<'a> { fn new(item: &'a DictItem) -> Self { Self { key: &item.key, value: &item.value, comments: &[], } } fn with_comments(self, comments: &'a [SourceComment]) -> Self { Self { comments, ..self } } } impl Ranged for KeyValuePair<'_> { fn range(&self) -> TextRange { if let Some(key) = self.key { TextRange::new(key.start(), self.value.end()) } else { self.value.range() } } } impl Format<PyFormatContext<'_>> for KeyValuePair<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { if let Some(key) = self.key { write!( f, [group(&format_with(|f| { key.format().fmt(f)?; token(":").fmt(f)?; if self.comments.is_empty() { space().fmt(f)?; } else { dangling_comments(self.comments).fmt(f)?; } self.value.format().fmt(f) }))] ) } else { // TODO(charlie): Make these dangling comments on the `ExprDict`, and identify them // dynamically, so as to avoid the parent rendering its child's comments. let comments = f.context().comments().clone(); let leading_value_comments = comments.leading(self.value); write!( f, [ // make sure the leading comments are hoisted past the `**` leading_comments(leading_value_comments), group(&format_args![token("**"), self.value.format()]) ] ) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_t_string.rs
crates/ruff_python_formatter/src/expression/expr_t_string.rs
use ruff_python_ast::{AnyNodeRef, ExprTString, StringLike}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, in_parentheses_only_group, }; use crate::other::interpolated_string::InterpolatedStringLayout; use crate::prelude::*; use crate::string::StringLikeExtensions; use crate::string::implicit::{ FormatImplicitConcatenatedString, FormatImplicitConcatenatedStringFlat, }; #[derive(Default)] pub struct FormatExprTString; impl FormatNodeRule<ExprTString> for FormatExprTString { fn fmt_fields(&self, item: &ExprTString, f: &mut PyFormatter) -> FormatResult<()> { if let Some(t_string) = item.as_single_part_tstring() { t_string.format().fmt(f) } else { // Always join tstrings that aren't parenthesized and thus, are always on a single line. if !f.context().node_level().is_parenthesized() { if let Some(format_flat) = FormatImplicitConcatenatedStringFlat::new(item.into(), f.context()) { return format_flat.fmt(f); } } in_parentheses_only_group(&FormatImplicitConcatenatedString::new(item)).fmt(f) } } } impl NeedsParentheses for ExprTString { fn needs_parentheses( &self, _parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if let Some(tstring_part) = self.as_single_part_tstring() { // The t-string is not implicitly concatenated if StringLike::TString(self).is_multiline(context) || InterpolatedStringLayout::from_interpolated_string_elements( &tstring_part.elements, context.source(), ) .is_multiline() { OptionalParentheses::Never } else { OptionalParentheses::BestFit } } else { // The t-string is implicitly concatenated OptionalParentheses::Multiline } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_unary_op.rs
crates/ruff_python_formatter/src/expression/expr_unary_op.rs
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprUnaryOp; use ruff_python_ast::UnaryOp; use ruff_python_ast::parenthesize::parenthesized_range; use ruff_text_size::Ranged; use crate::comments::trailing_comments; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parentheses, is_expression_parenthesized, }; use crate::prelude::*; #[derive(Default)] pub struct FormatExprUnaryOp; impl FormatNodeRule<ExprUnaryOp> for FormatExprUnaryOp { fn fmt_fields(&self, item: &ExprUnaryOp, f: &mut PyFormatter) -> FormatResult<()> { let ExprUnaryOp { range: _, node_index: _, op, operand, } = item; let operator = match op { UnaryOp::Invert => "~", UnaryOp::Not => "not", UnaryOp::UAdd => "+", UnaryOp::USub => "-", }; token(operator).fmt(f)?; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); // Split off the comments that follow after the operator and format them as trailing comments. // ```python // (not # comment // a) // ``` trailing_comments(dangling).fmt(f)?; // Insert a line break if the operand has comments but itself is not parenthesized or if the // operand is parenthesized but has a leading comment before the parentheses. // ```python // if ( // not // # comment // a): // pass // // if 1 and ( // not // # comment // ( // a // ) // ): // pass // ``` if needs_line_break(item, f.context()) { hard_line_break().fmt(f)?; } else if op.is_not() { space().fmt(f)?; } if operand .as_bin_op_expr() .is_some_and(|bin_op| bin_op.op.is_pow()) { operand.format().with_options(Parentheses::Always).fmt(f) } else { operand.format().fmt(f) } } } impl NeedsParentheses for ExprUnaryOp { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if parent.is_expr_await() { return OptionalParentheses::Always; } if needs_line_break(self, context) { return OptionalParentheses::Always; } if is_expression_parenthesized( self.operand.as_ref().into(), context.comments().ranges(), context.source(), ) { return OptionalParentheses::Never; } if context.comments().has(self.operand.as_ref()) { return OptionalParentheses::Always; } self.operand.needs_parentheses(self.into(), context) } } /// Returns `true` if the unary operator will have a hard line break between the operator and its /// operand and thus requires parentheses. fn needs_line_break(item: &ExprUnaryOp, context: &PyFormatContext) -> bool { let comments = context.comments(); let parenthesized_operand_range = parenthesized_range( item.operand.as_ref().into(), item.into(), comments.ranges(), context.source(), ); let leading_operand_comments = comments.leading(item.operand.as_ref()); let has_leading_comments_before_parens = parenthesized_operand_range.is_some_and(|range| { leading_operand_comments .iter() .any(|comment| comment.start() < range.start()) }); !leading_operand_comments.is_empty() && !is_expression_parenthesized( item.operand.as_ref().into(), context.comments().ranges(), context.source(), ) || has_leading_comments_before_parens }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_set_comp.rs
crates/ruff_python_formatter/src/expression/expr_set_comp.rs
use ruff_formatter::{Buffer, FormatResult, format_args, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprSetComp; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses, parenthesized}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprSetComp; impl FormatNodeRule<ExprSetComp> for FormatExprSetComp { fn fmt_fields(&self, item: &ExprSetComp, f: &mut PyFormatter) -> FormatResult<()> { let ExprSetComp { range: _, node_index: _, elt, generators, } = item; let joined = format_with(|f| { f.join_with(soft_line_break_or_space()) .entries(generators.iter().formatted()) .finish() }); let comments = f.context().comments().clone(); let dangling = comments.dangling(item); write!( f, [parenthesized( "{", &group(&format_args!( group(&elt.format()), soft_line_break_or_space(), joined )), "}" ) .with_dangling_comments(dangling)] ) } } impl NeedsParentheses for ExprSetComp { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_bin_op.rs
crates/ruff_python_formatter/src/expression/expr_bin_op.rs
use ruff_python_ast::ExprBinOp; use ruff_python_ast::{AnyNodeRef, StringLike}; use crate::expression::binary_like::BinaryLike; use crate::expression::has_parentheses; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; use crate::string::StringLikeExtensions; #[derive(Default)] pub struct FormatExprBinOp; impl FormatNodeRule<ExprBinOp> for FormatExprBinOp { #[inline] fn fmt_fields(&self, item: &ExprBinOp, f: &mut PyFormatter) -> FormatResult<()> { BinaryLike::Binary(item).fmt(f) } } impl NeedsParentheses for ExprBinOp { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if parent.is_expr_await() { OptionalParentheses::Always } else if let Ok(string) = StringLike::try_from(&*self.left) { // Multiline strings are guaranteed to never fit, avoid adding unnecessary parentheses if !string.is_implicit_concatenated() && string.is_multiline(context) && has_parentheses(&self.right, context).is_some() && !context.comments().has_dangling(self) && !context.comments().has(string) && !context.comments().has(self.right.as_ref()) { OptionalParentheses::Never } else { OptionalParentheses::Multiline } } else { OptionalParentheses::Multiline } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_list_comp.rs
crates/ruff_python_formatter/src/expression/expr_list_comp.rs
use ruff_formatter::{FormatResult, format_args, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprListComp; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses, parenthesized}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprListComp; impl FormatNodeRule<ExprListComp> for FormatExprListComp { fn fmt_fields(&self, item: &ExprListComp, f: &mut PyFormatter) -> FormatResult<()> { let ExprListComp { range: _, node_index: _, elt, generators, } = item; let joined = format_with(|f| { f.join_with(soft_line_break_or_space()) .entries(generators.iter().formatted()) .finish() }); let comments = f.context().comments().clone(); let dangling = comments.dangling(item); write!( f, [parenthesized( "[", &group(&format_args![ group(&elt.format()), soft_line_break_or_space(), joined ]), "]" ) .with_dangling_comments(dangling)] ) } } impl NeedsParentheses for ExprListComp { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_ellipsis_literal.rs
crates/ruff_python_formatter/src/expression/expr_ellipsis_literal.rs
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprEllipsisLiteral; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprEllipsisLiteral; impl FormatNodeRule<ExprEllipsisLiteral> for FormatExprEllipsisLiteral { fn fmt_fields(&self, _item: &ExprEllipsisLiteral, f: &mut PyFormatter) -> FormatResult<()> { token("...").fmt(f) } } impl NeedsParentheses for ExprEllipsisLiteral { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::BestFit } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/binary_like.rs
crates/ruff_python_formatter/src/expression/binary_like.rs
use std::num::NonZeroUsize; use std::ops::{Deref, Index}; use smallvec::SmallVec; use ruff_formatter::write; use ruff_python_ast::{ Expr, ExprAttribute, ExprBinOp, ExprBoolOp, ExprCompare, ExprUnaryOp, StringLike, UnaryOp, }; use ruff_python_trivia::CommentRanges; use ruff_python_trivia::{SimpleToken, SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange}; use crate::comments::{Comments, SourceComment, leading_comments, trailing_comments}; use crate::expression::OperatorPrecedence; use crate::expression::parentheses::{ Parentheses, in_parentheses_only_group, in_parentheses_only_if_group_breaks, in_parentheses_only_soft_line_break, in_parentheses_only_soft_line_break_or_space, is_expression_parenthesized, write_in_parentheses_only_group_end_tag, write_in_parentheses_only_group_start_tag, }; use crate::prelude::*; use crate::string::implicit::FormatImplicitConcatenatedString; #[derive(Copy, Clone, Debug)] pub(super) enum BinaryLike<'a> { Binary(&'a ExprBinOp), Compare(&'a ExprCompare), Bool(&'a ExprBoolOp), } impl<'a> BinaryLike<'a> { /// Flattens the hierarchical binary expression into a flat operand, operator, operand... sequence. /// /// See [`FlatBinaryExpressionSlice`] for an in depth explanation. fn flatten(self, comments: &'a Comments<'a>, source: &str) -> FlatBinaryExpression<'a> { fn recurse_compare<'a>( compare: &'a ExprCompare, leading_comments: &'a [SourceComment], trailing_comments: &'a [SourceComment], comments: &'a Comments, source: &str, parts: &mut SmallVec<[OperandOrOperator<'a>; 8]>, ) { parts.reserve(compare.comparators.len() * 2 + 1); rec( Operand::Left { expression: &compare.left, leading_comments, }, comments, source, parts, ); assert_eq!( compare.comparators.len(), compare.ops.len(), "Compare expression with an unbalanced number of comparators and operations." ); if let Some((last_expression, middle_expressions)) = compare.comparators.split_last() { let (last_operator, middle_operators) = compare.ops.split_last().unwrap(); for (operator, expression) in middle_operators.iter().zip(middle_expressions) { parts.push(OperandOrOperator::Operator(Operator { symbol: OperatorSymbol::Comparator(*operator), trailing_comments: &[], })); rec(Operand::Middle { expression }, comments, source, parts); } parts.push(OperandOrOperator::Operator(Operator { symbol: OperatorSymbol::Comparator(*last_operator), trailing_comments: &[], })); rec( Operand::Right { expression: last_expression, trailing_comments, }, comments, source, parts, ); } } fn recurse_bool<'a>( bool_expression: &'a ExprBoolOp, leading_comments: &'a [SourceComment], trailing_comments: &'a [SourceComment], comments: &'a Comments, source: &str, parts: &mut SmallVec<[OperandOrOperator<'a>; 8]>, ) { parts.reserve(bool_expression.values.len() * 2 - 1); if let Some((left, rest)) = bool_expression.values.split_first() { rec( Operand::Left { expression: left, leading_comments, }, comments, source, parts, ); parts.push(OperandOrOperator::Operator(Operator { symbol: OperatorSymbol::Bool(bool_expression.op), trailing_comments: &[], })); if let Some((right, middle)) = rest.split_last() { for expression in middle { rec(Operand::Middle { expression }, comments, source, parts); parts.push(OperandOrOperator::Operator(Operator { symbol: OperatorSymbol::Bool(bool_expression.op), trailing_comments: &[], })); } rec( Operand::Right { expression: right, trailing_comments, }, comments, source, parts, ); } } } fn recurse_binary<'a>( binary: &'a ExprBinOp, leading_comments: &'a [SourceComment], trailing_comments: &'a [SourceComment], comments: &'a Comments, source: &str, parts: &mut SmallVec<[OperandOrOperator<'a>; 8]>, ) { rec( Operand::Left { leading_comments, expression: &binary.left, }, comments, source, parts, ); parts.push(OperandOrOperator::Operator(Operator { symbol: OperatorSymbol::Binary(binary.op), trailing_comments: comments.dangling(binary), })); rec( Operand::Right { expression: binary.right.as_ref(), trailing_comments, }, comments, source, parts, ); } fn rec<'a>( operand: Operand<'a>, comments: &'a Comments, source: &str, parts: &mut SmallVec<[OperandOrOperator<'a>; 8]>, ) { let expression = operand.expression(); match expression { Expr::BinOp(binary) if !is_expression_parenthesized( expression.into(), comments.ranges(), source, ) => { let leading_comments = operand .leading_binary_comments() .unwrap_or_else(|| comments.leading(binary)); let trailing_comments = operand .trailing_binary_comments() .unwrap_or_else(|| comments.trailing(binary)); recurse_binary( binary, leading_comments, trailing_comments, comments, source, parts, ); } Expr::Compare(compare) if !is_expression_parenthesized( expression.into(), comments.ranges(), source, ) => { let leading_comments = operand .leading_binary_comments() .unwrap_or_else(|| comments.leading(compare)); let trailing_comments = operand .trailing_binary_comments() .unwrap_or_else(|| comments.trailing(compare)); recurse_compare( compare, leading_comments, trailing_comments, comments, source, parts, ); } Expr::BoolOp(bool_op) if !is_expression_parenthesized( expression.into(), comments.ranges(), source, ) => { let leading_comments = operand .leading_binary_comments() .unwrap_or_else(|| comments.leading(bool_op)); let trailing_comments = operand .trailing_binary_comments() .unwrap_or_else(|| comments.trailing(bool_op)); recurse_bool( bool_op, leading_comments, trailing_comments, comments, source, parts, ); } _ => { parts.push(OperandOrOperator::Operand(operand)); } } } let mut parts = SmallVec::new(); match self { BinaryLike::Binary(binary) => { // Leading and trailing comments are handled by the binary's ``FormatNodeRule` implementation. recurse_binary(binary, &[], &[], comments, source, &mut parts); } BinaryLike::Compare(compare) => { // Leading and trailing comments are handled by the compare's ``FormatNodeRule` implementation. recurse_compare(compare, &[], &[], comments, source, &mut parts); } BinaryLike::Bool(bool) => { recurse_bool(bool, &[], &[], comments, source, &mut parts); } } FlatBinaryExpression(parts) } const fn is_bool_op(self) -> bool { matches!(self, BinaryLike::Bool(_)) } } impl Format<PyFormatContext<'_>> for BinaryLike<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { let comments = f.context().comments().clone(); let flat_binary = self.flatten(&comments, f.context().source()); if self.is_bool_op() { return in_parentheses_only_group(&&*flat_binary).fmt(f); } let source = f.context().source(); let mut string_operands = flat_binary .operands() .filter_map(|(index, operand)| { StringLike::try_from(operand.expression()) .ok() .filter(|string| { string.is_implicit_concatenated() && !is_expression_parenthesized( string.into(), comments.ranges(), source, ) }) .map(|string| (index, string, operand)) }) .peekable(); // Split the binary expressions by implicit concatenated strings first by creating: // * One group that encloses the whole binary expression and ensures that all implicit concatenated strings // break together or fit on the same line // * Group the left operand and left operator as well as the right operator and right operand // to give them a lower precedence than the implicit concatenated string parts (the implicit strings should break first) if let Some((first_index, _, _)) = string_operands.peek() { // Group all strings in a single group so that they all break together or none of them. write_in_parentheses_only_group_start_tag(f); // Start the group for the left side coming before an implicit concatenated string if it isn't the first // ```python // a + "b" "c" // ^^^- start this group // ``` if *first_index != OperandIndex::new(0) { write_in_parentheses_only_group_start_tag(f); } // The index of the last formatted operator let mut last_operator_index = None; loop { if let Some((index, string_constant, operand)) = string_operands.next() { // An implicit concatenated string that isn't the first operand in a binary expression // ```python // a + "b" "c" + ddddddd + "e" "d" // ^^^^^^ this part or ^^^^^^^ this part // ``` if let Some(left_operator_index) = index.left_operator() { // Handles the case where the left and right side of a binary expression are both // implicit concatenated strings. In this case, the left operator has already been written // by the preceding implicit concatenated string. It is only necessary to finish the group, // wrapping the soft line break and operator. // // ```python // "a" "b" + "c" "d" // ``` if last_operator_index == Some(left_operator_index) { write_in_parentheses_only_group_end_tag(f); } else { // Everything between the last implicit concatenated string and the left operator // right before the implicit concatenated string: // ```python // a + b + "c" "d" // ^--- left_operator // ^^^^^-- left // ``` let left = flat_binary .between_operators(last_operator_index, left_operator_index); let left_operator = &flat_binary[left_operator_index]; if let Some(leading) = left.first_operand().leading_binary_comments() { leading_comments(leading).fmt(f)?; } // Write the left, the left operator, and the space before the right side write!( f, [ left, left.last_operand() .trailing_binary_comments() .map(trailing_comments), in_parentheses_only_soft_line_break_or_space(), left_operator, ] )?; // Finish the left-side group (the group was started before the loop or by the // previous iteration) write_in_parentheses_only_group_end_tag(f); if operand.has_unparenthesized_leading_comments( f.context().comments(), f.context().source(), ) || left_operator.has_trailing_comments() { hard_line_break().fmt(f)?; } else { space().fmt(f)?; } } write!( f, [ operand.leading_binary_comments().map(leading_comments), leading_comments(comments.leading(string_constant)), // Call `FormatImplicitConcatenatedString` directly to avoid formatting // the implicitly concatenated string with the enclosing group // because the group is added by the binary like formatting. FormatImplicitConcatenatedString::new(string_constant), trailing_comments(comments.trailing(string_constant)), operand.trailing_binary_comments().map(trailing_comments), line_suffix_boundary(), ] )?; } else { // Binary expression that starts with an implicit concatenated string: // ```python // "a" "b" + c // ^^^^^^^-- format the first operand of a binary expression // ``` write!( f, [ leading_comments(comments.leading(string_constant)), // Call `FormatImplicitConcatenatedString` directly to avoid formatting // the implicitly concatenated string with the enclosing group // because the group is added by the binary like formatting. FormatImplicitConcatenatedString::new(string_constant), trailing_comments(comments.trailing(string_constant)), ] )?; } // Write the right operator and start the group for the right side (if any) // ```python // a + "b" "c" + ddddddd + "e" "d" // ^^--- write this // ^^^^^^^^^^^-- start this group // ``` let right_operator_index = index.right_operator(); if let Some(right_operator) = flat_binary.get_operator(index.right_operator()) { write_in_parentheses_only_group_start_tag(f); let right_operand = &flat_binary[right_operator_index.right_operand()]; let right_operand_has_leading_comments = right_operand .has_unparenthesized_leading_comments( f.context().comments(), f.context().source(), ); // Keep the operator on the same line if the right side has leading comments (and thus, breaks) if right_operand_has_leading_comments { space().fmt(f)?; } else { in_parentheses_only_soft_line_break_or_space().fmt(f)?; } right_operator.fmt(f)?; if (right_operand_has_leading_comments && !is_expression_parenthesized( right_operand.expression().into(), f.context().comments().ranges(), f.context().source(), )) || right_operator.has_trailing_comments() { hard_line_break().fmt(f)?; } else { space().fmt(f)?; } last_operator_index = Some(right_operator_index); } else { break; } } else { if let Some(last_operator_index) = last_operator_index { let end = flat_binary.after_operator(last_operator_index); end.fmt(f)?; write_in_parentheses_only_group_end_tag(f); } break; } } // Finish the group that wraps all implicit concatenated strings write_in_parentheses_only_group_end_tag(f); } else { in_parentheses_only_group(&&*flat_binary).fmt(f)?; } Ok(()) } } fn is_simple_power_expression( left: &Expr, right: &Expr, comment_range: &CommentRanges, source: &str, ) -> bool { is_simple_power_operand(left) && is_simple_power_operand(right) && !is_expression_parenthesized(left.into(), comment_range, source) && !is_expression_parenthesized(right.into(), comment_range, source) } /// Return `true` if an [`Expr`] adheres to [Black's definition](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#line-breaks-binary-operators) /// of a non-complex expression, in the context of a power operation. const fn is_simple_power_operand(expr: &Expr) -> bool { match expr { Expr::UnaryOp(ExprUnaryOp { op: UnaryOp::Not, .. }) => false, Expr::NumberLiteral(_) | Expr::NoneLiteral(_) | Expr::BooleanLiteral(_) => true, Expr::Name(_) => true, Expr::UnaryOp(ExprUnaryOp { operand, .. }) => is_simple_power_operand(operand), Expr::Attribute(ExprAttribute { value, .. }) => is_simple_power_operand(value), _ => false, } } /// Owned [`FlatBinaryExpressionSlice`]. Read the [`FlatBinaryExpressionSlice`] documentation for more details about the data structure. #[derive(Debug)] struct FlatBinaryExpression<'a>(SmallVec<[OperandOrOperator<'a>; 8]>); impl<'a> Deref for FlatBinaryExpression<'a> { type Target = FlatBinaryExpressionSlice<'a>; fn deref(&self) -> &Self::Target { FlatBinaryExpressionSlice::from_slice(&self.0) } } /// Binary chain represented as a flat vector where operands are stored at even indices and operators /// add odd indices. /// /// ```python /// a + 5 * 3 + 2 /// ``` /// /// Gets parsed as: /// /// ```text /// graph /// + /// ├──a /// ├──* /// │ ├──b /// │ └──c /// └──d /// ``` /// /// The slice representation of the above is closer to what you have in source. It's a simple sequence of operands and operators, /// entirely ignoring operator precedence (doesn't flatten parenthesized expressions): /// /// ```text /// ----------------------------- /// | a | + | 5 | * | 3 | + | 2 | /// ----------------------------- /// ``` /// /// The advantage of a flat structure are: /// * It becomes possible to adjust the operator / operand precedence. E.g splitting implicit concatenated strings before `+` operations. /// * It allows arbitrary slicing of binary expressions for as long as a slice always starts and ends with an operand. /// /// A slice is guaranteed to always start and end with an operand. The smallest valid slice is a slice containing a single operand. /// Operands in multi-operand slices are separated by operators. #[repr(transparent)] struct FlatBinaryExpressionSlice<'a>([OperandOrOperator<'a>]); impl<'a> FlatBinaryExpressionSlice<'a> { fn from_slice<'slice>(slice: &'slice [OperandOrOperator<'a>]) -> &'slice Self { debug_assert!( !slice.is_empty(), "Operand slice must contain at least one operand" ); #[expect(unsafe_code)] unsafe { // SAFETY: `BinaryChainSlice` has the same layout as a slice because it uses `repr(transparent)` &*(std::ptr::from_ref::<[OperandOrOperator<'a>]>(slice) as *const FlatBinaryExpressionSlice<'a>) } } fn operators(&self) -> impl Iterator<Item = (OperatorIndex, &Operator<'a>)> { self.0.iter().enumerate().filter_map(|(index, part)| { if let OperandOrOperator::Operator(operator) = part { Some((OperatorIndex::new(index), operator)) } else { None } }) } fn operands(&self) -> impl Iterator<Item = (OperandIndex, &Operand<'a>)> { self.0.iter().enumerate().filter_map(|(index, part)| { if let OperandOrOperator::Operand(operand) = part { Some((OperandIndex::new(index), operand)) } else { None } }) } /// Creates a subslice that contains the operands coming after `last_operator` and up to, but not including the `end` operator. fn between_operators(&self, last_operator: Option<OperatorIndex>, end: OperatorIndex) -> &Self { let start = last_operator.map_or(0usize, |operator| operator.right_operand().0); Self::from_slice(&self.0[start..end.value()]) } /// Creates a slice starting at the right operand of `index`. fn after_operator(&self, index: OperatorIndex) -> &Self { Self::from_slice(&self.0[index.right_operand().0..]) } /// Returns the lowest precedence of any operator in this binary chain. fn lowest_precedence(&self) -> OperatorPrecedence { self.operators() .map(|(_, operator)| operator.precedence()) .max() .unwrap_or(OperatorPrecedence::None) } /// Returns the first operand in the slice. fn first_operand(&self) -> &Operand<'a> { match self.0.first() { Some(OperandOrOperator::Operand(operand)) => operand, _ => unreachable!("Expected an operand"), } } /// Returns the last operand (the right most operand). fn last_operand(&self) -> &Operand<'a> { match self.0.last() { Some(OperandOrOperator::Operand(operand)) => operand, _ => unreachable!("Expected an operand"), } } /// Returns the operator at the given index or `None` if it is out of bounds. fn get_operator(&self, index: OperatorIndex) -> Option<&Operator<'a>> { self.0 .get(index.value()) .map(OperandOrOperator::unwrap_operator) } } /// Formats a binary chain slice by inserting soft line breaks before the lowest-precedence operators. /// In other words: It splits the line before by the lowest precedence operators (and it either splits /// all of them or none). For example, the lowest precedence operator for `a + b * c + d` is the `+` operator. /// The expression either gets formatted as `a + b * c + d` if it fits on the line or as /// ```python /// a /// + b * c /// + d /// ``` /// /// Notice how the formatting first splits by the lower precedence operator `+` but tries to keep the `*` operation /// on a single line. /// /// The formatting is recursive (with a depth of `O(operators)` where `operators` are operators with different precedences). /// /// Comments before or after the first operand must be formatted by the caller because they shouldn't be part of the group /// wrapping the whole binary chain. This is to avoid that `b * c` expands in the following example because of its trailing comment: /// /// ```python /// /// ( a /// + b * c # comment /// + d /// ) /// ``` /// /// impl Format<PyFormatContext<'_>> for FlatBinaryExpressionSlice<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> { // Single operand slice if let [OperandOrOperator::Operand(operand)] = &self.0 { return operand.fmt(f); } let mut last_operator: Option<OperatorIndex> = None; let lowest_precedence = self.lowest_precedence(); for (index, operator_part) in self.operators() { if operator_part.precedence() == lowest_precedence { let left = self.between_operators(last_operator, index); let right = self.after_operator(index); let is_pow = operator_part.symbol.is_pow() && is_simple_power_expression( left.last_operand().expression(), right.first_operand().expression(), f.context().comments().ranges(), f.context().source(), ); if let Some(leading) = left.first_operand().leading_binary_comments() { leading_comments(leading).fmt(f)?; } match &left.0 { [OperandOrOperator::Operand(operand)] => operand.fmt(f)?, _ => in_parentheses_only_group(&left).fmt(f)?, } if let Some(trailing) = left.last_operand().trailing_binary_comments() { trailing_comments(trailing).fmt(f)?; } if is_pow { in_parentheses_only_soft_line_break().fmt(f)?; } else { in_parentheses_only_soft_line_break_or_space().fmt(f)?; } operator_part.fmt(f)?; // Format the operator on its own line if the right side has any leading comments. if operator_part.has_trailing_comments() || right.first_operand().has_unparenthesized_leading_comments( f.context().comments(), f.context().source(), ) { hard_line_break().fmt(f)?; } else if is_pow { in_parentheses_only_if_group_breaks(&space()).fmt(f)?; } else { space().fmt(f)?; } last_operator = Some(index); } } // Format the last right side // SAFETY: It is guaranteed that the slice contains at least a operand, operator, operand sequence or: // * the slice contains only a single operand in which case the function exits early above. // * the slice is empty, which isn't a valid slice // * the slice violates the operand, operator, operand constraint, in which case the error already happened earlier. let right = self.after_operator(last_operator.unwrap()); if let Some(leading) = right.first_operand().leading_binary_comments() { leading_comments(leading).fmt(f)?; } match &right.0 { [OperandOrOperator::Operand(operand)] => operand.fmt(f), _ => in_parentheses_only_group(&right).fmt(f), } } } /// Either an [`Operand`] or [`Operator`] #[derive(Debug)] enum OperandOrOperator<'a> { Operand(Operand<'a>), Operator(Operator<'a>), } impl<'a> OperandOrOperator<'a> { fn unwrap_operand(&self) -> &Operand<'a> { match self { OperandOrOperator::Operand(operand) => operand, OperandOrOperator::Operator(operator) => { panic!("Expected operand but found operator {operator:?}.") } } } fn unwrap_operator(&self) -> &Operator<'a> { match self { OperandOrOperator::Operator(operator) => operator, OperandOrOperator::Operand(operand) => { panic!("Expected operator but found operand {operand:?}.") } } } } #[derive(Debug)] enum Operand<'a> { /// Operand that used to be on the left side of a binary operation. /// /// For example `a` in the following code /// /// ```python /// a + b + c /// ``` Left { expression: &'a Expr, /// Leading comments of the outer most binary expression that starts at this node. leading_comments: &'a [SourceComment], }, /// Operand that is neither at the start nor the end of a binary like expression. /// Only applies to compare expression. /// /// `b` and `c` are *middle* operands whereas `a` is a left and `d` a right operand. /// /// ```python /// a > b > c > d /// ``` /// /// Middle have no leading or trailing comments from the enclosing binary like expression. Middle { expression: &'a Expr }, /// Operand that is on the right side of a binary operation. /// /// For example `b` and `c` are right sides of the binary expressions. /// /// ```python /// a + b + c /// ``` Right { expression: &'a Expr, /// Trailing comments of the outer most binary expression that ends at this operand. trailing_comments: &'a [SourceComment], }, } impl<'a> Operand<'a> { fn expression(&self) -> &'a Expr { match self { Operand::Left { expression, .. } => expression, Operand::Right { expression, .. } => expression, Operand::Middle { expression } => expression, } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_bool_op.rs
crates/ruff_python_formatter/src/expression/expr_bool_op.rs
use ruff_formatter::{FormatOwnedWithRule, FormatRefWithRule}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{BoolOp, ExprBoolOp}; use crate::expression::binary_like::BinaryLike; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprBoolOp; impl FormatNodeRule<ExprBoolOp> for FormatExprBoolOp { #[inline] fn fmt_fields(&self, item: &ExprBoolOp, f: &mut PyFormatter) -> FormatResult<()> { BinaryLike::Bool(item).fmt(f) } } impl NeedsParentheses for ExprBoolOp { fn needs_parentheses( &self, parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { if parent.is_expr_await() { OptionalParentheses::Always } else { OptionalParentheses::Multiline } } } #[derive(Copy, Clone)] pub struct FormatBoolOp; impl<'ast> AsFormat<PyFormatContext<'ast>> for BoolOp { type Format<'a> = FormatRefWithRule<'a, BoolOp, FormatBoolOp, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatBoolOp) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for BoolOp { type Format = FormatOwnedWithRule<BoolOp, FormatBoolOp, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatBoolOp) } } impl FormatRule<BoolOp, PyFormatContext<'_>> for FormatBoolOp { fn fmt(&self, item: &BoolOp, f: &mut PyFormatter) -> FormatResult<()> { let operator = match item { BoolOp::And => "and", BoolOp::Or => "or", }; token(operator).fmt(f) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_yield_from.rs
crates/ruff_python_formatter/src/expression/expr_yield_from.rs
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprYieldFrom; use crate::expression::expr_yield::AnyExpressionYield; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprYieldFrom; impl FormatNodeRule<ExprYieldFrom> for FormatExprYieldFrom { fn fmt_fields(&self, item: &ExprYieldFrom, f: &mut PyFormatter) -> FormatResult<()> { AnyExpressionYield::from(item).fmt(f) } } impl NeedsParentheses for ExprYieldFrom { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { AnyExpressionYield::from(self).needs_parentheses(parent, context) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_f_string.rs
crates/ruff_python_formatter/src/expression/expr_f_string.rs
use ruff_python_ast::{AnyNodeRef, ExprFString, StringLike}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, in_parentheses_only_group, }; use crate::other::interpolated_string::InterpolatedStringLayout; use crate::prelude::*; use crate::string::StringLikeExtensions; use crate::string::implicit::{ FormatImplicitConcatenatedString, FormatImplicitConcatenatedStringFlat, }; #[derive(Default)] pub struct FormatExprFString; impl FormatNodeRule<ExprFString> for FormatExprFString { fn fmt_fields(&self, item: &ExprFString, f: &mut PyFormatter) -> FormatResult<()> { if let Some(f_string) = item.as_single_part_fstring() { f_string.format().fmt(f) } else { // Always join fstrings that aren't parenthesized and thus, are always on a single line. if !f.context().node_level().is_parenthesized() { if let Some(format_flat) = FormatImplicitConcatenatedStringFlat::new(item.into(), f.context()) { return format_flat.fmt(f); } } in_parentheses_only_group(&FormatImplicitConcatenatedString::new(item)).fmt(f) } } } impl NeedsParentheses for ExprFString { fn needs_parentheses( &self, _parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if let Some(fstring_part) = self.as_single_part_fstring() { // The f-string is not implicitly concatenated if StringLike::FString(self).is_multiline(context) || InterpolatedStringLayout::from_interpolated_string_elements( &fstring_part.elements, context.source(), ) .is_multiline() { OptionalParentheses::Never } else { OptionalParentheses::BestFit } } else { // The f-string is implicitly concatenated OptionalParentheses::Multiline } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_set.rs
crates/ruff_python_formatter/src/expression/expr_set.rs
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprSet; use ruff_text_size::Ranged; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses, parenthesized}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprSet; impl FormatNodeRule<ExprSet> for FormatExprSet { fn fmt_fields(&self, item: &ExprSet, f: &mut PyFormatter) -> FormatResult<()> { let ExprSet { range: _, node_index: _, elts, } = item; // That would be a dict expression assert!(!elts.is_empty()); // Avoid second mutable borrow of f let joined = format_with(|f: &mut PyFormatter| { f.join_comma_separated(item.end()) .nodes(elts.iter()) .finish() }); let comments = f.context().comments().clone(); let dangling = comments.dangling(item); parenthesized("{", &joined, "}") .with_dangling_comments(dangling) .fmt(f) } } impl NeedsParentheses for ExprSet { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/parentheses.rs
crates/ruff_python_formatter/src/expression/parentheses.rs
use ruff_formatter::prelude::tag::Condition; use ruff_formatter::{Argument, Arguments, format_args, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprRef; use ruff_python_trivia::CommentRanges; use ruff_python_trivia::{ BackwardsTokenizer, SimpleToken, SimpleTokenKind, first_non_trivia_token, }; use ruff_text_size::Ranged; use crate::comments::{ SourceComment, dangling_comments, dangling_open_parenthesis_comments, trailing_comments, }; use crate::context::{NodeLevel, WithNodeLevel}; use crate::prelude::*; /// From the perspective of the expression, under which circumstances does it need parentheses #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum OptionalParentheses { /// Add parentheses if the expression expands over multiple lines Multiline, /// Always set parentheses regardless if the expression breaks or if they are /// present in the source. Always, /// Add parentheses if it helps to make this expression fit. Otherwise never add parentheses. /// This mode should only be used for expressions that don't have their own split points to the left, e.g. identifiers, /// or constants, calls starting with an identifier, etc. BestFit, /// Never add parentheses. Use it for expressions that have their own parentheses or if the expression body always spans multiple lines (multiline strings). Never, } pub(crate) trait NeedsParentheses { /// Determines if this object needs optional parentheses or if it is safe to omit the parentheses. fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses; } /// From the perspective of the parent statement or expression, when should the child expression /// get parentheses? #[derive(Copy, Clone, Debug, PartialEq)] pub(crate) enum Parenthesize { /// Parenthesizes the expression if it doesn't fit on a line OR if the expression is parenthesized in the source code. Optional, /// Parenthesizes the expression only if it doesn't fit on a line. IfBreaks, /// Only adds parentheses if the expression has leading or trailing comments. /// Adding parentheses is desired to prevent the comments from wandering. IfRequired, /// Same as [`Self::IfBreaks`] except that it uses /// [`parenthesize_if_expands`](crate::builders::parenthesize_if_expands) for expressions with /// the layout [`OptionalParentheses::BestFit`] which is used by non-splittable expressions like /// literals, name, and strings. /// /// Use this layout over `IfBreaks` when there's a sequence of `maybe_parenthesize_expression` /// in a single logical-line and you want to break from right-to-left. Use `IfBreaks` for the /// first expression and `IfBreaksParenthesized` for the rest. IfBreaksParenthesized, /// Same as [`Self::IfBreaksParenthesized`] but uses /// [`parenthesize_if_expands`](crate::builders::parenthesize_if_expands) for nested /// [`maybe_parenthesized_expression`](crate::expression::maybe_parenthesize_expression) calls /// unlike other layouts that always omit parentheses when outer parentheses are present. IfBreaksParenthesizedNested, } impl Parenthesize { pub(crate) const fn is_optional(self) -> bool { matches!(self, Parenthesize::Optional) } } /// Whether it is necessary to add parentheses around an expression. /// This is different from [`Parenthesize`] in that it is the resolved representation: It takes into account /// whether there are parentheses in the source code or not. #[derive(Copy, Clone, Debug, Eq, PartialEq, Default)] pub enum Parentheses { #[default] Preserve, /// Always set parentheses regardless if the expression breaks or if they were /// present in the source. Always, /// Never add parentheses Never, } /// Returns `true` if the [`ExprRef`] is enclosed by parentheses in the source code. pub(crate) fn is_expression_parenthesized( expr: ExprRef, comment_ranges: &CommentRanges, contents: &str, ) -> bool { // First test if there's a closing parentheses because it tends to be cheaper. if matches!( first_non_trivia_token(expr.end(), contents), Some(SimpleToken { kind: SimpleTokenKind::RParen, .. }) ) { matches!( BackwardsTokenizer::up_to(expr.start(), contents, comment_ranges) .skip_trivia() .next(), Some(SimpleToken { kind: SimpleTokenKind::LParen, .. }) ) } else { false } } /// Formats `content` enclosed by the `left` and `right` parentheses. The implementation also ensures /// that expanding the parenthesized expression (or any of its children) doesn't enforce the /// optional parentheses around the outer-most expression to materialize. pub(crate) fn parenthesized<'content, 'ast, Content>( left: &'static str, content: &'content Content, right: &'static str, ) -> FormatParenthesized<'content, 'ast> where Content: Format<PyFormatContext<'ast>>, { FormatParenthesized { left, comments: &[], hug: false, content: Argument::new(content), right, } } pub(crate) struct FormatParenthesized<'content, 'ast> { left: &'static str, comments: &'content [SourceComment], hug: bool, content: Argument<'content, PyFormatContext<'ast>>, right: &'static str, } impl<'content, 'ast> FormatParenthesized<'content, 'ast> { /// Inserts any dangling comments that should be placed immediately after the open parenthesis. /// For example: /// ```python /// [ # comment /// 1, /// 2, /// 3, /// ] /// ``` pub(crate) fn with_dangling_comments( self, comments: &'content [SourceComment], ) -> FormatParenthesized<'content, 'ast> { FormatParenthesized { comments, ..self } } /// Whether to indent the content within the parentheses. pub(crate) fn with_hugging(self, hug: bool) -> FormatParenthesized<'content, 'ast> { FormatParenthesized { hug, ..self } } } impl<'ast> Format<PyFormatContext<'ast>> for FormatParenthesized<'_, 'ast> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> { let current_level = f.context().node_level(); let indented = format_with(|f| { let content = Arguments::from(&self.content); if self.comments.is_empty() { if self.hug { content.fmt(f) } else { group(&soft_block_indent(&content)).fmt(f) } } else { group(&format_args![ dangling_open_parenthesis_comments(self.comments), soft_block_indent(&content), ]) .fmt(f) } }); let inner = format_with(|f| { if let NodeLevel::Expression(Some(group_id)) = current_level { // Use fits expanded if there's an enclosing group that adds the optional parentheses. // This ensures that expanding this parenthesized expression does not expand the optional parentheses group. write!( f, [fits_expanded(&indented) .with_condition(Some(Condition::if_group_fits_on_line(group_id)))] ) } else { // It's not necessary to wrap the content if it is not inside of an optional_parentheses group. indented.fmt(f) } }); let mut f = WithNodeLevel::new(NodeLevel::ParenthesizedExpression, f); write!(f, [token(self.left), inner, token(self.right)]) } } /// Wraps an expression in parentheses only if it still does not fit after expanding all expressions that start or end with /// a parentheses (`()`, `[]`, `{}`). pub(crate) fn optional_parentheses<'content, 'ast, Content>( content: &'content Content, ) -> FormatOptionalParentheses<'content, 'ast> where Content: Format<PyFormatContext<'ast>>, { FormatOptionalParentheses { content: Argument::new(content), } } pub(crate) struct FormatOptionalParentheses<'content, 'ast> { content: Argument<'content, PyFormatContext<'ast>>, } impl<'ast> Format<PyFormatContext<'ast>> for FormatOptionalParentheses<'_, 'ast> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> { // The group id is used as a condition in [`in_parentheses_only_group`] to create a // conditional group that is only active if the optional parentheses group expands. let parens_id = f.group_id("optional_parentheses"); let mut f = WithNodeLevel::new(NodeLevel::Expression(Some(parens_id)), f); // We can't use `soft_block_indent` here because that would always increment the indent, // even if the group does not break (the indent is not soft). This would result in // too deep indentations if a `parenthesized` group expands. Using `indent_if_group_breaks` // gives us the desired *soft* indentation that is only present if the optional parentheses // are shown. write!( f, [group(&format_args![ if_group_breaks(&token("(")), indent_if_group_breaks( &format_args![soft_line_break(), Arguments::from(&self.content)], parens_id ), soft_line_break(), if_group_breaks(&token(")")) ]) .with_id(Some(parens_id))] ) } } /// Creates a [`soft_line_break`] if the expression is enclosed by (optional) parentheses (`()`, `[]`, or `{}`). /// Prints nothing if the expression is not parenthesized. pub(crate) const fn in_parentheses_only_soft_line_break() -> InParenthesesOnlyLineBreak { InParenthesesOnlyLineBreak::SoftLineBreak } /// Creates a [`soft_line_break_or_space`] if the expression is enclosed by (optional) parentheses (`()`, `[]`, or `{}`). /// Prints a [`space`] if the expression is not parenthesized. pub(crate) const fn in_parentheses_only_soft_line_break_or_space() -> InParenthesesOnlyLineBreak { InParenthesesOnlyLineBreak::SoftLineBreakOrSpace } pub(crate) enum InParenthesesOnlyLineBreak { SoftLineBreak, SoftLineBreakOrSpace, } impl<'ast> Format<PyFormatContext<'ast>> for InParenthesesOnlyLineBreak { fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> { match f.context().node_level() { NodeLevel::TopLevel(_) | NodeLevel::CompoundStatement | NodeLevel::Expression(None) => { match self { InParenthesesOnlyLineBreak::SoftLineBreak => Ok(()), InParenthesesOnlyLineBreak::SoftLineBreakOrSpace => space().fmt(f), } } NodeLevel::Expression(Some(parentheses_id)) => match self { InParenthesesOnlyLineBreak::SoftLineBreak => if_group_breaks(&soft_line_break()) .with_group_id(Some(parentheses_id)) .fmt(f), InParenthesesOnlyLineBreak::SoftLineBreakOrSpace => write!( f, [ if_group_breaks(&soft_line_break_or_space()) .with_group_id(Some(parentheses_id)), if_group_fits_on_line(&space()).with_group_id(Some(parentheses_id)) ] ), }, NodeLevel::ParenthesizedExpression => { f.write_element(FormatElement::Line(match self { InParenthesesOnlyLineBreak::SoftLineBreak => LineMode::Soft, InParenthesesOnlyLineBreak::SoftLineBreakOrSpace => LineMode::SoftOrSpace, })); Ok(()) } } } } /// Makes `content` a group, but only if the outer expression is parenthesized (a list, parenthesized expression, dict, ...) /// or if the expression gets parenthesized because it expands over multiple lines. pub(crate) fn in_parentheses_only_group<'content, 'ast, Content>( content: &'content Content, ) -> FormatInParenthesesOnlyGroup<'content, 'ast> where Content: Format<PyFormatContext<'ast>>, { FormatInParenthesesOnlyGroup { content: Argument::new(content), } } pub(crate) struct FormatInParenthesesOnlyGroup<'content, 'ast> { content: Argument<'content, PyFormatContext<'ast>>, } impl<'ast> Format<PyFormatContext<'ast>> for FormatInParenthesesOnlyGroup<'_, 'ast> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> { write_in_parentheses_only_group_start_tag(f); Arguments::from(&self.content).fmt(f)?; write_in_parentheses_only_group_end_tag(f); Ok(()) } } pub(super) fn write_in_parentheses_only_group_start_tag(f: &mut PyFormatter) { match f.context().node_level() { NodeLevel::Expression(Some(parentheses_id)) => { f.write_element(FormatElement::Tag(tag::Tag::StartConditionalGroup( tag::ConditionalGroup::new(Condition::if_group_breaks(parentheses_id)), ))); } NodeLevel::ParenthesizedExpression => { // Unconditionally group the content if it is not enclosed by an optional parentheses group. f.write_element(FormatElement::Tag(tag::Tag::StartGroup(tag::Group::new()))); } NodeLevel::Expression(None) | NodeLevel::TopLevel(_) | NodeLevel::CompoundStatement => { // No group } } } pub(super) fn write_in_parentheses_only_group_end_tag(f: &mut PyFormatter) { match f.context().node_level() { NodeLevel::Expression(Some(_)) => { f.write_element(FormatElement::Tag(tag::Tag::EndConditionalGroup)); } NodeLevel::ParenthesizedExpression => { // Unconditionally group the content if it is not enclosed by an optional parentheses group. f.write_element(FormatElement::Tag(tag::Tag::EndGroup)); } NodeLevel::Expression(None) | NodeLevel::TopLevel(_) | NodeLevel::CompoundStatement => { // No group } } } /// Shows prints `content` only if the expression is enclosed by (optional) parentheses (`()`, `[]`, or `{}`) /// and splits across multiple lines. pub(super) fn in_parentheses_only_if_group_breaks<'a, T>( content: T, ) -> impl Format<PyFormatContext<'a>> where T: Format<PyFormatContext<'a>>, { format_with(move |f: &mut PyFormatter| match f.context().node_level() { NodeLevel::TopLevel(_) | NodeLevel::CompoundStatement | NodeLevel::Expression(None) => { // no-op, not parenthesized Ok(()) } NodeLevel::Expression(Some(parentheses_id)) => if_group_breaks(&content) .with_group_id(Some(parentheses_id)) .fmt(f), NodeLevel::ParenthesizedExpression => if_group_breaks(&content).fmt(f), }) } /// Format comments inside empty parentheses, brackets or curly braces. /// /// Empty `()`, `[]` and `{}` are special because there can be dangling comments, and they can be in /// two positions: /// ```python /// x = [ # end-of-line /// # own line /// ] /// ``` /// These comments are dangling because they can't be assigned to any element inside as they would /// in all other cases. pub(crate) fn empty_parenthesized<'content>( left: &'static str, comments: &'content [SourceComment], right: &'static str, ) -> FormatEmptyParenthesized<'content> { FormatEmptyParenthesized { left, comments, right, } } pub(crate) struct FormatEmptyParenthesized<'content> { left: &'static str, comments: &'content [SourceComment], right: &'static str, } impl Format<PyFormatContext<'_>> for FormatEmptyParenthesized<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> { let end_of_line_split = self .comments .partition_point(|comment| comment.line_position().is_end_of_line()); debug_assert!( self.comments[end_of_line_split..] .iter() .all(|comment| comment.line_position().is_own_line()) ); group(&format_args![ token(self.left), // end-of-line comments trailing_comments(&self.comments[..end_of_line_split]), // Avoid unstable formatting with // ```python // x = () - (# // ) // ``` // Without this the comment would go after the empty tuple first, but still expand // the bin op. In the second formatting pass they are trailing bin op comments // so the bin op collapse. Suboptimally we keep parentheses around the bin op in // either case. (!self.comments[..end_of_line_split].is_empty()).then_some(hard_line_break()), // own line comments, which need to be indented soft_block_indent(&dangling_comments(&self.comments[end_of_line_split..])), token(self.right) ]) .fmt(f) } } #[cfg(test)] mod tests { use ruff_python_ast::ExprRef; use ruff_python_parser::parse_expression; use ruff_python_trivia::CommentRanges; use crate::expression::parentheses::is_expression_parenthesized; #[test] fn test_has_parentheses() { let expression = r#"(b().c("")).d()"#; let parsed = parse_expression(expression).unwrap(); assert!(!is_expression_parenthesized( ExprRef::from(parsed.expr()), &CommentRanges::default(), expression )); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_yield.rs
crates/ruff_python_formatter/src/expression/expr_yield.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{Expr, ExprYield, ExprYieldFrom}; use ruff_text_size::{Ranged, TextRange}; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parenthesize, is_expression_parenthesized, }; use crate::prelude::*; pub(super) enum AnyExpressionYield<'a> { Yield(&'a ExprYield), YieldFrom(&'a ExprYieldFrom), } impl AnyExpressionYield<'_> { const fn is_yield_from(&self) -> bool { matches!(self, AnyExpressionYield::YieldFrom(_)) } fn value(&self) -> Option<&Expr> { match self { AnyExpressionYield::Yield(yld) => yld.value.as_deref(), AnyExpressionYield::YieldFrom(yld) => Some(&yld.value), } } } impl Ranged for AnyExpressionYield<'_> { fn range(&self) -> TextRange { match self { AnyExpressionYield::Yield(yld) => yld.range(), AnyExpressionYield::YieldFrom(yld) => yld.range(), } } } impl NeedsParentheses for AnyExpressionYield<'_> { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { // According to https://docs.python.org/3/reference/grammar.html There are two situations // where we do not want to always parenthesize a yield expression: // 1. Right hand side of an assignment, e.g. `x = yield y` // 2. Yield statement, e.g. `def foo(): yield y` // We catch situation 1 below. Situation 2 does not need to be handled here as // FormatStmtExpr, does not add parenthesis if parent.is_stmt_assign() || parent.is_stmt_ann_assign() || parent.is_stmt_aug_assign() { if let Some(value) = self.value() { if is_expression_parenthesized( value.into(), context.comments().ranges(), context.source(), ) { // Ex) `x = yield (1)` OptionalParentheses::Never } else { // Ex) `x = yield f(1, 2, 3)` match value.needs_parentheses(self.into(), context) { OptionalParentheses::BestFit => OptionalParentheses::Never, parentheses => parentheses, } } } else { // Ex) `x = yield` OptionalParentheses::Never } } else { // Ex) `print((yield))` OptionalParentheses::Always } } } impl<'a> From<&'a ExprYield> for AnyExpressionYield<'a> { fn from(value: &'a ExprYield) -> Self { AnyExpressionYield::Yield(value) } } impl<'a> From<&'a ExprYieldFrom> for AnyExpressionYield<'a> { fn from(value: &'a ExprYieldFrom) -> Self { AnyExpressionYield::YieldFrom(value) } } impl<'a> From<&AnyExpressionYield<'a>> for AnyNodeRef<'a> { fn from(value: &AnyExpressionYield<'a>) -> Self { match value { AnyExpressionYield::Yield(yld) => AnyNodeRef::ExprYield(yld), AnyExpressionYield::YieldFrom(yld) => AnyNodeRef::ExprYieldFrom(yld), } } } impl Format<PyFormatContext<'_>> for AnyExpressionYield<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { let keyword = if self.is_yield_from() { "yield from" } else { "yield" }; if let Some(val) = self.value() { write!( f, [ token(keyword), space(), maybe_parenthesize_expression(val, self, Parenthesize::Optional) ] )?; } else { // ExprYieldFrom always has Some(value) so we should never get a bare `yield from` write!(f, [token(keyword)])?; } Ok(()) } } #[derive(Default)] pub struct FormatExprYield; impl FormatNodeRule<ExprYield> for FormatExprYield { fn fmt_fields(&self, item: &ExprYield, f: &mut PyFormatter) -> FormatResult<()> { AnyExpressionYield::from(item).fmt(f) } } impl NeedsParentheses for ExprYield { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { AnyExpressionYield::from(self).needs_parentheses(parent, context) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_number_literal.rs
crates/ruff_python_formatter/src/expression/expr_number_literal.rs
use std::borrow::Cow; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{ExprNumberLiteral, Number}; use ruff_text_size::{Ranged, TextSize, TextSlice}; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprNumberLiteral; impl FormatNodeRule<ExprNumberLiteral> for FormatExprNumberLiteral { fn fmt_fields(&self, item: &ExprNumberLiteral, f: &mut PyFormatter) -> FormatResult<()> { match item.value { Number::Int(_) => { let content = f.context().source().slice(item); let normalized = normalize_integer(content); match normalized { Cow::Borrowed(_) => source_text_slice(item.range()).fmt(f), Cow::Owned(normalized) => text(&normalized).fmt(f), } } Number::Float(_) => { let content = f.context().source().slice(item); let normalized = normalize_floating_number(content); match normalized { Cow::Borrowed(_) => source_text_slice(item.range()).fmt(f), Cow::Owned(normalized) => text(&normalized).fmt(f), } } Number::Complex { .. } => { let range = item.range(); let content = f.context().source().slice(item); let normalized = normalize_floating_number(content.trim_end_matches(['j', 'J'])); match normalized { Cow::Borrowed(_) => { source_text_slice(range.sub_end(TextSize::from(1))).fmt(f)?; } Cow::Owned(normalized) => { text(&normalized).fmt(f)?; } } token("j").fmt(f) } } } } impl NeedsParentheses for ExprNumberLiteral { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::BestFit } } /// Returns the normalized integer string. fn normalize_integer(input: &str) -> Cow<'_, str> { // The normalized string if `input` is not yet normalized. // `output` must remain empty if `input` is already normalized. let mut output = String::new(); // Tracks the last index of `input` that has been written to `output`. // If `last_index` is `0` at the end, then the input is already normalized and can be returned as is. let mut last_index = 0; let mut is_hex = false; let mut chars = input.char_indices(); if let Some((_, '0')) = chars.next() { if let Some((index, c)) = chars.next() { is_hex = matches!(c, 'x' | 'X'); if matches!(c, 'B' | 'O' | 'X') { // Lowercase the prefix. output.push('0'); output.push(c.to_ascii_lowercase()); last_index = index + c.len_utf8(); } } } // Skip the rest if `input` is not a hexinteger because there are only digits. if is_hex { for (index, c) in chars { if matches!(c, 'a'..='f') { // Uppercase hexdigits. output.push_str(&input[last_index..index]); output.push(c.to_ascii_uppercase()); last_index = index + c.len_utf8(); } } } if last_index == 0 { Cow::Borrowed(input) } else { output.push_str(&input[last_index..]); Cow::Owned(output) } } /// Returns the normalized floating number string. fn normalize_floating_number(input: &str) -> Cow<'_, str> { // The normalized string if `input` is not yet normalized. // `output` must remain empty if `input` is already normalized. let mut output = String::new(); // Tracks the last index of `input` that has been written to `output`. // If `last_index` is `0` at the end, then the input is already normalized and can be returned as is. let mut last_index = 0; let mut chars = input.char_indices(); let mut prev_char_is_dot = if let Some((index, '.')) = chars.next() { // Add a leading `0` if `input` starts with `.`. output.push('0'); output.push('.'); last_index = index + '.'.len_utf8(); true } else { false }; loop { match chars.next() { Some((index, c @ ('e' | 'E'))) => { if prev_char_is_dot { // Add `0` if the `e` immediately follows a `.` (e.g., `1.e1`). output.push_str(&input[last_index..index]); output.push('0'); last_index = index; } if c == 'E' { // Lowercase exponent part. output.push_str(&input[last_index..index]); output.push('e'); last_index = index + 'E'.len_utf8(); } if let Some((index, '+')) = chars.next() { // Remove `+` in exponent part. output.push_str(&input[last_index..index]); last_index = index + '+'.len_utf8(); } break; } Some((_index, c)) => { prev_char_is_dot = c == '.'; continue; } None => { if prev_char_is_dot { // Add `0` if fraction part ends with `.`. output.push_str(&input[last_index..]); output.push('0'); last_index = input.len(); } break; } } } if last_index == 0 { Cow::Borrowed(input) } else { output.push_str(&input[last_index..]); Cow::Owned(output) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/operator.rs
crates/ruff_python_formatter/src/expression/operator.rs
use crate::prelude::*; use ruff_formatter::{FormatOwnedWithRule, FormatRefWithRule}; use ruff_python_ast::Operator; #[derive(Copy, Clone)] pub struct FormatOperator; impl<'ast> AsFormat<PyFormatContext<'ast>> for Operator { type Format<'a> = FormatRefWithRule<'a, Operator, FormatOperator, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatOperator) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for Operator { type Format = FormatOwnedWithRule<Operator, FormatOperator, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatOperator) } } impl FormatRule<Operator, PyFormatContext<'_>> for FormatOperator { fn fmt(&self, item: &Operator, f: &mut PyFormatter) -> FormatResult<()> { let operator = match item { Operator::Add => "+", Operator::Sub => "-", Operator::Mult => "*", Operator::MatMult => "@", Operator::Div => "/", Operator::Mod => "%", Operator::Pow => "**", Operator::LShift => "<<", Operator::RShift => ">>", Operator::BitOr => "|", Operator::BitXor => "^", Operator::BitAnd => "&", Operator::FloorDiv => "//", }; token(operator).fmt(f) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_slice.rs
crates/ruff_python_formatter/src/expression/expr_slice.rs
use ruff_formatter::{FormatError, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{Expr, ExprSlice, ExprUnaryOp, UnaryOp}; use ruff_python_trivia::{SimpleToken, SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange}; use crate::comments::{SourceComment, dangling_comments}; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprSlice; impl FormatNodeRule<ExprSlice> for FormatExprSlice { /// This implementation deviates from black in that comments are attached to the section of the /// slice they originate in fn fmt_fields(&self, item: &ExprSlice, f: &mut PyFormatter) -> FormatResult<()> { // `[lower:upper:step]` let ExprSlice { lower, upper, step, range, node_index: _, } = item; let (first_colon, second_colon) = find_colons( f.context().source(), *range, lower.as_deref(), upper.as_deref(), )?; // Handle comment placement // In placements.rs, we marked comment for None nodes a dangling and associated all others // as leading or dangling wrt to a node. That means we either format a node and only have // to handle newlines and spacing, or the node is None and we insert the corresponding // slice of dangling comments let comments = f.context().comments().clone(); let slice_dangling_comments = comments.dangling(item); // Put the dangling comments (where the nodes are missing) into buckets let first_colon_partition_index = slice_dangling_comments.partition_point(|x| x.start() < first_colon.start()); let (dangling_lower_comments, dangling_upper_step_comments) = slice_dangling_comments.split_at(first_colon_partition_index); let (dangling_upper_comments, dangling_step_comments) = if let Some(second_colon) = &second_colon { let second_colon_partition_index = dangling_upper_step_comments .partition_point(|x| x.start() < second_colon.start()); dangling_upper_step_comments.split_at(second_colon_partition_index) } else { // Without a second colon they remaining dangling comments belong between the first // colon and the closing parentheses (dangling_upper_step_comments, [].as_slice()) }; // Ensure there a no dangling comments for a node if the node is present debug_assert!(lower.is_none() || dangling_lower_comments.is_empty()); debug_assert!(upper.is_none() || dangling_upper_comments.is_empty()); debug_assert!(step.is_none() || dangling_step_comments.is_empty()); // Handle spacing around the colon(s) // https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#slices let lower_simple = lower.as_ref().is_none_or(|expr| is_simple_expr(expr)); let upper_simple = upper.as_ref().is_none_or(|expr| is_simple_expr(expr)); let step_simple = step.as_ref().is_none_or(|expr| is_simple_expr(expr)); let all_simple = lower_simple && upper_simple && step_simple; // lower if let Some(lower) = lower { write!(f, [lower.format(), line_suffix_boundary()])?; } else { dangling_comments(dangling_lower_comments).fmt(f)?; } // First colon // The spacing after the colon depends on both the lhs and the rhs: // ``` // e00 = x[:] // e01 = x[:1] // e02 = x[: a()] // e10 = x[1:] // e11 = x[1:1] // e12 = x[1 : a()] // e20 = x[a() :] // e21 = x[a() : 1] // e22 = x[a() : a()] // e200 = "e"[a() : :] // e201 = "e"[a() :: 1] // e202 = "e"[a() :: a()] // ``` if !all_simple && lower.is_some() { space().fmt(f)?; } token(":").fmt(f)?; // No upper node, no need for a space, e.g. `x[a() :]` if !all_simple && upper.is_some() { space().fmt(f)?; } // Upper if let Some(upper) = upper { let upper_leading_comments = comments.leading(upper.as_ref()); leading_comments_spacing(f, upper_leading_comments)?; write!(f, [upper.format(), line_suffix_boundary()])?; } else { if let Some(first) = dangling_upper_comments.first() { // Here the spacing for end-of-line comments works but own line comments need // explicit spacing if first.line_position().is_own_line() { hard_line_break().fmt(f)?; } } dangling_comments(dangling_upper_comments).fmt(f)?; } // (optionally) step if second_colon.is_some() { // Same spacing rules as for the first colon, except for the strange case when the // second colon exists, but neither upper nor step // ``` // e200 = "e"[a() : :] // e201 = "e"[a() :: 1] // e202 = "e"[a() :: a()] // ``` if !all_simple && (upper.is_some() || step.is_none()) { space().fmt(f)?; } token(":").fmt(f)?; // No step node, no need for a space if !all_simple && step.is_some() { space().fmt(f)?; } if let Some(step) = step { let step_leading_comments = comments.leading(step.as_ref()); leading_comments_spacing(f, step_leading_comments)?; step.format().fmt(f)?; } else if !dangling_step_comments.is_empty() { // Put the colon and comments on their own lines write!( f, [hard_line_break(), dangling_comments(dangling_step_comments)] )?; } } else { debug_assert!(step.is_none(), "step can't exist without a second colon"); } Ok(()) } } /// We're in a slice, so we know there's a first colon, but with have to look into the source /// to find out whether there is a second one, too, e.g. `[1:2]` and `[1:10:2]`. /// /// Returns the first and optionally the second colon. pub(crate) fn find_colons( contents: &str, range: TextRange, lower: Option<&Expr>, upper: Option<&Expr>, ) -> FormatResult<(SimpleToken, Option<SimpleToken>)> { let after_lower = lower.as_ref().map_or(range.start(), Ranged::end); let mut tokens = SimpleTokenizer::new(contents, TextRange::new(after_lower, range.end())) .skip_trivia() .skip_while(|token| token.kind == SimpleTokenKind::RParen); let first_colon = tokens.next().ok_or(FormatError::syntax_error( "Didn't find any token for slice first colon", ))?; if first_colon.kind != SimpleTokenKind::Colon { return Err(FormatError::syntax_error( "Slice first colon token was not a colon", )); } let after_upper = upper.as_ref().map_or(first_colon.end(), Ranged::end); let mut tokens = SimpleTokenizer::new(contents, TextRange::new(after_upper, range.end())) .skip_trivia() .skip_while(|token| token.kind == SimpleTokenKind::RParen); let second_colon = if let Some(token) = tokens.next() { if token.kind != SimpleTokenKind::Colon { return Err(FormatError::syntax_error( "Expected a colon for the second colon token", )); } Some(token) } else { None }; Ok((first_colon, second_colon)) } /// Determines whether this expression needs a space around the colon /// <https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#slices> fn is_simple_expr(expr: &Expr) -> bool { // Unary op expressions except `not` can be simple. if let Some(ExprUnaryOp { op: UnaryOp::UAdd | UnaryOp::USub | UnaryOp::Invert, operand, .. }) = expr.as_unary_op_expr() { is_simple_expr(operand) } else { expr.is_literal_expr() || expr.is_name_expr() } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum ExprSliceCommentSection { Lower, Upper, Step, } /// Assigns a comment to lower/upper/step in `[lower:upper:step]`. /// /// ```python /// "sliceable"[ /// # lower comment /// : /// # upper comment /// : /// # step comment /// ] /// ``` pub(crate) fn assign_comment_in_slice( comment: TextRange, contents: &str, expr_slice: &ExprSlice, ) -> ExprSliceCommentSection { let ExprSlice { lower, upper, step: _, range, node_index: _, } = expr_slice; let (first_colon, second_colon) = find_colons(contents, *range, lower.as_deref(), upper.as_deref()) .expect("SyntaxError when trying to parse slice"); if comment.start() < first_colon.start() { ExprSliceCommentSection::Lower } else { // We are to the right of the first colon if let Some(second_colon) = second_colon { if comment.start() < second_colon.start() { ExprSliceCommentSection::Upper } else { ExprSliceCommentSection::Step } } else { // No second colon means there is no step ExprSliceCommentSection::Upper } } } /// Manual spacing for the leading comments of upper and step fn leading_comments_spacing( f: &mut PyFormatter, leading_comments: &[SourceComment], ) -> FormatResult<()> { if let Some(first) = leading_comments.first() { if first.line_position().is_own_line() { // Insert a newline after the colon so the comment ends up on its own line hard_line_break().fmt(f)?; } else { // Insert the two spaces between the colon and the end-of-line comment after the colon write!(f, [space(), space()])?; } } Ok(()) } impl NeedsParentheses for ExprSlice { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Multiline } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_tuple.rs
crates/ruff_python_formatter/src/expression/expr_tuple.rs
use ruff_formatter::{FormatRuleWithOptions, format_args}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprTuple; use ruff_text_size::{Ranged, TextRange}; use crate::builders::parenthesize_if_expands; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, empty_parenthesized, optional_parentheses, parenthesized, }; use crate::other::commas::has_trailing_comma; use crate::prelude::*; #[derive(Debug, Clone, Copy, Eq, PartialEq, Default)] pub enum TupleParentheses { /// By default tuples with a single element will include parentheses. Tuples with multiple elements /// will parenthesize if the expression expands. This means that tuples will often *preserve* /// their parentheses, but this differs from `Preserve` in that we may also *introduce* /// parentheses as well. #[default] Default, /// Handle special cases where parentheses are to be preserved. /// /// Black omits parentheses for tuples inside subscripts except if the tuple is already /// parenthesized in the source code. /// ```python /// x[a, :] /// x[a, b:] /// x[(a, b):] /// ``` Preserve, /// The same as [`Self::Default`] except that it uses [`optional_parentheses`] rather than /// [`parenthesize_if_expands`]. This avoids adding parentheses if breaking any containing parenthesized /// expression makes the tuple fit. /// /// Avoids adding parentheses around the tuple because breaking the `sum` call expression is sufficient /// to make it fit. /// /// ```python /// return len(self.nodeseeeeeeeee), sum( /// len(node.parents) for node in self.node_map.values() /// ) /// ``` OptionalParentheses, /// Handle the special cases where we don't include parentheses at all. /// /// Black never formats tuple targets of for loops with parentheses if inside a comprehension. /// For example, tuple targets will always be formatted on the same line, except when an element supports /// line-breaking in an un-parenthesized context. /// ```python /// # Input /// {k: v for x, (k, v) in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension} /// /// # Black /// { /// k: v /// for x, ( /// k, /// v, /// ) in this_is_a_very_long_variable_which_will_cause_a_trailing_comma_which_breaks_the_comprehension /// } /// ``` Never, /// Handle the special cases where we don't include parentheses if they are not required. /// /// Normally, black keeps parentheses, but in the case of for loops it formats /// ```python /// for (a, b) in x: /// pass /// ``` /// to /// ```python /// for a, b in x: /// pass /// ``` /// Black still does use parentheses in these positions if the group breaks or magic trailing /// comma is used. /// /// Additional examples: /// ```python /// for (a,) in []: /// pass /// for a, b in []: /// pass /// for a, b in []: # Strips parentheses /// pass /// for ( /// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, /// b, /// ) in []: /// pass /// ``` NeverPreserve, } #[derive(Default)] pub struct FormatExprTuple { parentheses: TupleParentheses, } impl FormatRuleWithOptions<ExprTuple, PyFormatContext<'_>> for FormatExprTuple { type Options = TupleParentheses; fn with_options(mut self, options: Self::Options) -> Self { self.parentheses = options; self } } impl FormatNodeRule<ExprTuple> for FormatExprTuple { fn fmt_fields(&self, item: &ExprTuple, f: &mut PyFormatter) -> FormatResult<()> { let ExprTuple { elts, ctx: _, range: _, node_index: _, parenthesized: is_parenthesized, } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); // Handle the edge cases of an empty tuple and a tuple with one element // // there can be dangling comments, and they can be in two // positions: // ```python // a3 = ( # end-of-line // # own line // ) // ``` // In all other cases comments get assigned to a list element match elts.as_slice() { [] => empty_parenthesized("(", dangling, ")").fmt(f), [single] => match self.parentheses { TupleParentheses::Preserve if !is_parenthesized => { single.format().fmt(f)?; // The `TupleParentheses::Preserve` is only set by subscript expression // formatting. With PEP 646, a single element starred expression in the slice // position of a subscript expression is actually a tuple expression. For // example: // // ```python // data[*x] // # ^^ single element tuple expression without a trailing comma // // data[*x,] // # ^^^ single element tuple expression with a trailing comma // ``` // // // This means that the formatter should only add a trailing comma if there is // one already. if has_trailing_comma(TextRange::new(single.end(), item.end()), f.context()) { token(",").fmt(f)?; } Ok(()) } _ => // A single element tuple always needs parentheses and a trailing comma, except when inside of a subscript { parenthesized("(", &format_args![single.format(), token(",")], ")") .with_dangling_comments(dangling) .fmt(f) } }, // If the tuple has parentheses, we generally want to keep them. The exception are for // loops, see `TupleParentheses::NeverPreserve` doc comment. // // Unlike other expression parentheses, tuple parentheses are part of the range of the // tuple itself. _ if *is_parenthesized && !(self.parentheses == TupleParentheses::NeverPreserve && dangling.is_empty()) => { parenthesized("(", &ExprSequence::new(item), ")") .with_dangling_comments(dangling) .fmt(f) } _ => match self.parentheses { TupleParentheses::Never => { let separator = format_with(|f| group(&format_args![token(","), space()]).fmt(f)); f.join_with(separator) .entries(elts.iter().formatted()) .finish() } TupleParentheses::Preserve => group(&ExprSequence::new(item)).fmt(f), TupleParentheses::NeverPreserve => { optional_parentheses(&ExprSequence::new(item)).fmt(f) } TupleParentheses::OptionalParentheses if item.len() == 2 => { optional_parentheses(&ExprSequence::new(item)).fmt(f) } TupleParentheses::Default | TupleParentheses::OptionalParentheses => { parenthesize_if_expands(&ExprSequence::new(item)).fmt(f) } }, } } } #[derive(Debug)] struct ExprSequence<'a> { tuple: &'a ExprTuple, } impl<'a> ExprSequence<'a> { const fn new(expr: &'a ExprTuple) -> Self { Self { tuple: expr } } } impl Format<PyFormatContext<'_>> for ExprSequence<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { f.join_comma_separated(self.tuple.end()) .nodes(&self.tuple.elts) .finish() } } impl NeedsParentheses for ExprTuple { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/mod.rs
crates/ruff_python_formatter/src/expression/mod.rs
use std::cmp::Ordering; use std::slice; use ruff_formatter::{ FormatOwnedWithRule, FormatRefWithRule, FormatRule, FormatRuleWithOptions, write, }; use ruff_python_ast::parenthesize::parentheses_iterator; use ruff_python_ast::visitor::source_order::{SourceOrderVisitor, walk_expr}; use ruff_python_ast::{self as ast}; use ruff_python_ast::{AnyNodeRef, Expr, ExprRef, Operator}; use ruff_python_trivia::CommentRanges; use ruff_text_size::Ranged; use crate::builders::parenthesize_if_expands; use crate::comments::{LeadingDanglingTrailingComments, leading_comments, trailing_comments}; use crate::context::{NodeLevel, WithNodeLevel}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parentheses, Parenthesize, is_expression_parenthesized, optional_parentheses, parenthesized, }; use crate::prelude::*; use crate::preview::is_hug_parens_with_braces_and_square_brackets_enabled; mod binary_like; pub(crate) mod expr_attribute; pub(crate) mod expr_await; pub(crate) mod expr_bin_op; pub(crate) mod expr_bool_op; pub(crate) mod expr_boolean_literal; pub(crate) mod expr_bytes_literal; pub(crate) mod expr_call; pub(crate) mod expr_compare; pub(crate) mod expr_dict; pub(crate) mod expr_dict_comp; pub(crate) mod expr_ellipsis_literal; pub(crate) mod expr_f_string; pub(crate) mod expr_generator; pub(crate) mod expr_if; pub(crate) mod expr_ipy_escape_command; pub(crate) mod expr_lambda; pub(crate) mod expr_list; pub(crate) mod expr_list_comp; pub(crate) mod expr_name; pub(crate) mod expr_named; pub(crate) mod expr_none_literal; pub(crate) mod expr_number_literal; pub(crate) mod expr_set; pub(crate) mod expr_set_comp; pub(crate) mod expr_slice; pub(crate) mod expr_starred; pub(crate) mod expr_string_literal; pub(crate) mod expr_subscript; pub(crate) mod expr_t_string; pub(crate) mod expr_tuple; pub(crate) mod expr_unary_op; pub(crate) mod expr_yield; pub(crate) mod expr_yield_from; mod operator; pub(crate) mod parentheses; #[derive(Copy, Clone, PartialEq, Eq, Default)] pub struct FormatExpr { parentheses: Parentheses, } impl FormatRuleWithOptions<Expr, PyFormatContext<'_>> for FormatExpr { type Options = Parentheses; fn with_options(mut self, options: Self::Options) -> Self { self.parentheses = options; self } } impl FormatRule<Expr, PyFormatContext<'_>> for FormatExpr { fn fmt(&self, expression: &Expr, f: &mut PyFormatter) -> FormatResult<()> { let parentheses = self.parentheses; let format_expr = format_with(|f| match expression { Expr::BoolOp(expr) => expr.format().fmt(f), Expr::Named(expr) => expr.format().fmt(f), Expr::BinOp(expr) => expr.format().fmt(f), Expr::UnaryOp(expr) => expr.format().fmt(f), Expr::Lambda(expr) => expr.format().fmt(f), Expr::If(expr) => expr.format().fmt(f), Expr::Dict(expr) => expr.format().fmt(f), Expr::Set(expr) => expr.format().fmt(f), Expr::ListComp(expr) => expr.format().fmt(f), Expr::SetComp(expr) => expr.format().fmt(f), Expr::DictComp(expr) => expr.format().fmt(f), Expr::Generator(expr) => expr.format().fmt(f), Expr::Await(expr) => expr.format().fmt(f), Expr::Yield(expr) => expr.format().fmt(f), Expr::YieldFrom(expr) => expr.format().fmt(f), Expr::Compare(expr) => expr.format().fmt(f), Expr::Call(expr) => expr.format().fmt(f), Expr::FString(expr) => expr.format().fmt(f), Expr::TString(expr) => expr.format().fmt(f), Expr::StringLiteral(expr) => expr.format().fmt(f), Expr::BytesLiteral(expr) => expr.format().fmt(f), Expr::NumberLiteral(expr) => expr.format().fmt(f), Expr::BooleanLiteral(expr) => expr.format().fmt(f), Expr::NoneLiteral(expr) => expr.format().fmt(f), Expr::EllipsisLiteral(expr) => expr.format().fmt(f), Expr::Attribute(expr) => expr.format().fmt(f), Expr::Subscript(expr) => expr.format().fmt(f), Expr::Starred(expr) => expr.format().fmt(f), Expr::Name(expr) => expr.format().fmt(f), Expr::List(expr) => expr.format().fmt(f), Expr::Tuple(expr) => expr.format().fmt(f), Expr::Slice(expr) => expr.format().fmt(f), Expr::IpyEscapeCommand(expr) => expr.format().fmt(f), }); let parenthesize = match parentheses { Parentheses::Preserve => is_expression_parenthesized( expression.into(), f.context().comments().ranges(), f.context().source(), ), Parentheses::Always => true, // Fluent style means we already have parentheses Parentheses::Never => false, }; if parenthesize { let comments = f.context().comments().clone(); let node_comments = comments.leading_dangling_trailing(expression); if !node_comments.has_leading() && !node_comments.has_trailing() { parenthesized("(", &format_expr, ")") .with_hugging(is_expression_huggable(expression, f.context())) .fmt(f) } else { format_with_parentheses_comments(expression, &node_comments, f) } } else { let level = match f.context().node_level() { NodeLevel::TopLevel(_) | NodeLevel::CompoundStatement => { NodeLevel::Expression(None) } saved_level @ (NodeLevel::Expression(_) | NodeLevel::ParenthesizedExpression) => { saved_level } }; let mut f = WithNodeLevel::new(level, f); write!(f, [format_expr]) } } } /// The comments below are trailing on the addition, but it's also outside the /// parentheses /// ```python /// x = [ /// # comment leading /// (1 + 2) # comment trailing /// ] /// ``` /// as opposed to /// ```python /// x = [( /// # comment leading /// 1 + 2 # comment trailing /// )] /// ``` /// , where the comments are inside the parentheses. That is also affects list /// formatting, where we want to avoid moving the comments after the comma inside /// the parentheses: /// ```python /// data = [ /// ( /// b"\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00" /// b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" /// ), # Point (0 0) /// ] /// ``` /// We could mark those comments as trailing in list but it's easier to handle /// them here too. /// /// So given /// ```python /// x = [ /// # comment leading outer /// ( /// # comment leading inner /// 1 + 2 # comment trailing inner /// ) # comment trailing outer /// ] /// ``` /// we want to keep the inner an outer comments outside the parentheses and the inner ones inside. /// This is independent of whether they are own line or end-of-line comments, though end-of-line /// comments can become own line comments when we discard nested parentheses. /// /// Style decision: When there are multiple nested parentheses around an expression, we consider the /// outermost parentheses the relevant ones and discard the others. fn format_with_parentheses_comments( expression: &Expr, node_comments: &LeadingDanglingTrailingComments, f: &mut PyFormatter, ) -> FormatResult<()> { // First part: Split the comments // TODO(konstin): We don't have the parent, which is a problem: // ```python // f( // # a // (a) // ) // ``` // gets formatted as // ```python // f( // ( // # a // a // ) // ) // ``` let range_with_parens = parentheses_iterator( expression.into(), None, f.context().comments().ranges(), f.context().source(), ) .last(); let (leading_split, trailing_split) = if let Some(range_with_parens) = range_with_parens { let leading_split = node_comments .leading .partition_point(|comment| comment.start() < range_with_parens.start()); let trailing_split = node_comments .trailing .partition_point(|comment| comment.start() < range_with_parens.end()); (leading_split, trailing_split) } else { (0, node_comments.trailing.len()) }; let (leading_outer, leading_inner) = node_comments.leading.split_at(leading_split); let (trailing_inner, trailing_outer) = node_comments.trailing.split_at(trailing_split); // Preserve an opening parentheses comment // ```python // a = ( # opening parentheses comment // # leading inner // 1 // ) // ``` let (parentheses_comment, leading_inner) = match leading_inner.split_first() { Some((first, rest)) if first.line_position().is_end_of_line() => { (slice::from_ref(first), rest) } _ => (Default::default(), node_comments.leading), }; // Second Part: Format // The code order is a bit strange here, we format: // * outer leading comment // * opening parenthesis // * opening parenthesis comment // * inner leading comments // * the expression itself // * inner trailing comments // * the closing parenthesis // * outer trailing comments let fmt_fields = format_with(|f| match expression { Expr::BoolOp(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Named(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::BinOp(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::UnaryOp(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Lambda(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::If(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Dict(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Set(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::ListComp(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::SetComp(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::DictComp(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Generator(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Await(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Yield(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::YieldFrom(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Compare(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Call(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::FString(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::TString(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::StringLiteral(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::BytesLiteral(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::NumberLiteral(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::BooleanLiteral(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::NoneLiteral(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::EllipsisLiteral(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Attribute(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Subscript(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Starred(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Name(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::List(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Tuple(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::Slice(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), Expr::IpyEscapeCommand(expr) => FormatNodeRule::fmt_fields(expr.format().rule(), expr, f), }); leading_comments(leading_outer).fmt(f)?; // Custom FormatNodeRule::fmt variant that only formats the inner comments let format_node_rule_fmt = format_with(|f| { // No need to handle suppression comments, those are statement only write!( f, [ leading_comments(leading_inner), fmt_fields, trailing_comments(trailing_inner) ] ) }); // The actual parenthesized formatting write!( f, [ parenthesized("(", &format_node_rule_fmt, ")") .with_dangling_comments(parentheses_comment), trailing_comments(trailing_outer) ] ) } /// Wraps an expression in optional parentheses except if its [`NeedsParentheses::needs_parentheses`] implementation /// indicates that it is okay to omit the parentheses. For example, parentheses can always be omitted for lists, /// because they already bring their own parentheses. pub(crate) fn maybe_parenthesize_expression<'a, T>( expression: &'a Expr, parent: T, parenthesize: Parenthesize, ) -> MaybeParenthesizeExpression<'a> where T: Into<AnyNodeRef<'a>>, { MaybeParenthesizeExpression { expression, parent: parent.into(), parenthesize, } } pub(crate) struct MaybeParenthesizeExpression<'a> { expression: &'a Expr, parent: AnyNodeRef<'a>, parenthesize: Parenthesize, } impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { let MaybeParenthesizeExpression { expression, parent, parenthesize, } = self; let preserve_parentheses = parenthesize.is_optional() && is_expression_parenthesized( (*expression).into(), f.context().comments().ranges(), f.context().source(), ); // If we want to preserve parentheses, short-circuit. if preserve_parentheses { return expression.format().with_options(Parentheses::Always).fmt(f); } let comments = f.context().comments().clone(); let node_comments = comments.leading_dangling_trailing(*expression); // If the expression has comments, we always want to preserve the parentheses. This also // ensures that we correctly handle parenthesized comments, and don't need to worry about // them in the implementation below. if node_comments.has_leading() || node_comments.has_trailing_own_line() { return expression.format().with_options(Parentheses::Always).fmt(f); } let needs_parentheses = match expression.needs_parentheses(*parent, f.context()) { OptionalParentheses::Always => OptionalParentheses::Always, // The reason to add parentheses is to avoid a syntax error when breaking an expression over multiple lines. // Therefore, it is unnecessary to add an additional pair of parentheses if an outer expression // is parenthesized. Unless, it's the `Parenthesize::IfBreaksParenthesizedNested` layout // where parenthesizing nested `maybe_parenthesized_expression` is explicitly desired. _ if f.context().node_level().is_parenthesized() => { return if matches!(parenthesize, Parenthesize::IfBreaksParenthesizedNested) { parenthesize_if_expands(&expression.format().with_options(Parentheses::Never)) .with_indent(!is_expression_huggable(expression, f.context())) .fmt(f) } else { expression.format().with_options(Parentheses::Never).fmt(f) }; } needs_parentheses => needs_parentheses, }; let unparenthesized = expression.format().with_options(Parentheses::Never); match needs_parentheses { OptionalParentheses::Multiline => match parenthesize { Parenthesize::IfRequired => unparenthesized.fmt(f), Parenthesize::Optional | Parenthesize::IfBreaks | Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested => { if can_omit_optional_parentheses(expression, f.context()) { optional_parentheses(&unparenthesized).fmt(f) } else { parenthesize_if_expands(&unparenthesized).fmt(f) } } }, OptionalParentheses::BestFit => match parenthesize { Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested => { // Can-omit layout is relevant for `"abcd".call`. We don't want to add unnecessary // parentheses in this case. if can_omit_optional_parentheses(expression, f.context()) { optional_parentheses(&unparenthesized).fmt(f) } else { parenthesize_if_expands(&unparenthesized).fmt(f) } } Parenthesize::Optional | Parenthesize::IfRequired => unparenthesized.fmt(f), Parenthesize::IfBreaks => { if node_comments.has_trailing() { expression.format().with_options(Parentheses::Always).fmt(f) } else { // The group id is necessary because the nested expressions may reference it. let group_id = f.group_id("optional_parentheses"); let f = &mut WithNodeLevel::new(NodeLevel::Expression(Some(group_id)), f); best_fit_parenthesize(&unparenthesized) .with_group_id(Some(group_id)) .fmt(f) } } }, OptionalParentheses::Never => match parenthesize { Parenthesize::Optional | Parenthesize::IfBreaks | Parenthesize::IfRequired | Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested => unparenthesized.fmt(f), }, OptionalParentheses::Always => { expression.format().with_options(Parentheses::Always).fmt(f) } } } } impl NeedsParentheses for Expr { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { match self { Expr::BoolOp(expr) => expr.needs_parentheses(parent, context), Expr::Named(expr) => expr.needs_parentheses(parent, context), Expr::BinOp(expr) => expr.needs_parentheses(parent, context), Expr::UnaryOp(expr) => expr.needs_parentheses(parent, context), Expr::Lambda(expr) => expr.needs_parentheses(parent, context), Expr::If(expr) => expr.needs_parentheses(parent, context), Expr::Dict(expr) => expr.needs_parentheses(parent, context), Expr::Set(expr) => expr.needs_parentheses(parent, context), Expr::ListComp(expr) => expr.needs_parentheses(parent, context), Expr::SetComp(expr) => expr.needs_parentheses(parent, context), Expr::DictComp(expr) => expr.needs_parentheses(parent, context), Expr::Generator(expr) => expr.needs_parentheses(parent, context), Expr::Await(expr) => expr.needs_parentheses(parent, context), Expr::Yield(expr) => expr.needs_parentheses(parent, context), Expr::YieldFrom(expr) => expr.needs_parentheses(parent, context), Expr::Compare(expr) => expr.needs_parentheses(parent, context), Expr::Call(expr) => expr.needs_parentheses(parent, context), Expr::FString(expr) => expr.needs_parentheses(parent, context), Expr::TString(expr) => expr.needs_parentheses(parent, context), Expr::StringLiteral(expr) => expr.needs_parentheses(parent, context), Expr::BytesLiteral(expr) => expr.needs_parentheses(parent, context), Expr::NumberLiteral(expr) => expr.needs_parentheses(parent, context), Expr::BooleanLiteral(expr) => expr.needs_parentheses(parent, context), Expr::NoneLiteral(expr) => expr.needs_parentheses(parent, context), Expr::EllipsisLiteral(expr) => expr.needs_parentheses(parent, context), Expr::Attribute(expr) => expr.needs_parentheses(parent, context), Expr::Subscript(expr) => expr.needs_parentheses(parent, context), Expr::Starred(expr) => expr.needs_parentheses(parent, context), Expr::Name(expr) => expr.needs_parentheses(parent, context), Expr::List(expr) => expr.needs_parentheses(parent, context), Expr::Tuple(expr) => expr.needs_parentheses(parent, context), Expr::Slice(expr) => expr.needs_parentheses(parent, context), Expr::IpyEscapeCommand(expr) => expr.needs_parentheses(parent, context), } } } impl<'ast> AsFormat<PyFormatContext<'ast>> for Expr { type Format<'a> = FormatRefWithRule<'a, Expr, FormatExpr, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatExpr::default()) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for Expr { type Format = FormatOwnedWithRule<Expr, FormatExpr, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatExpr::default()) } } /// Tests if it is safe to omit the optional parentheses. /// /// We prefer parentheses at least in the following cases: /// * The expression contains more than one unparenthesized expression with the same precedence. For example, /// the expression `a * b * c` contains two multiply operations. We prefer parentheses in that case. /// `(a * b) * c` or `a * b + c` are okay, because the subexpression is parenthesized, or the expression uses operands with a lower precedence /// * The expression contains at least one parenthesized sub expression (optimization to avoid unnecessary work) /// /// This mimics Black's [`_maybe_split_omitting_optional_parens`](https://github.com/psf/black/blob/d1248ca9beaf0ba526d265f4108836d89cf551b7/src/black/linegen.py#L746-L820) pub(crate) fn can_omit_optional_parentheses(expr: &Expr, context: &PyFormatContext) -> bool { let mut visitor = CanOmitOptionalParenthesesVisitor::new(context); visitor.visit_subexpression(expr); if !visitor.any_parenthesized_expressions { // Only use the more complex IR when there is any expression that we can possibly split by false } else if visitor.max_precedence_count > 1 { false } else if visitor.max_precedence == OperatorPrecedence::None { // Micha: This seems to apply for lambda expressions where the body ends in a subscript. // Subscripts are excluded by default because breaking them looks odd, but it seems to be fine for lambda expression. // // ```python // mapper = lambda x: dict_with_default[ // np.nan if isinstance(x, float) and np.isnan(x) else x // ] // ``` // // to prevent that it gets formatted as: // // ```python // mapper = ( // lambda x: dict_with_default[ // np.nan if isinstance(x, float) and np.isnan(x) else x // ] // ) // ``` // I think we should remove this check in the future and instead parenthesize the body of the lambda expression: // // ```python // mapper = lambda x: ( // dict_with_default[ // np.nan if isinstance(x, float) and np.isnan(x) else x // ] // ) // ``` // // Another case are method chains: // ```python // xxxxxxxx.some_kind_of_method( // some_argument=[ // "first", // "second", // "third", // ] // ).another_method(a) // ``` true } else if visitor.max_precedence == OperatorPrecedence::Attribute { // A single method call inside a named expression (`:=`) or as the body of a lambda function: // ```python // kwargs["open_with"] = lambda path, _: fsspec.open( // path, "wb", **(storage_options or {}) // ).open() // // if ret := subprocess.run( // ["git", "rev-parse", "--short", "HEAD"], // cwd=package_dir, // capture_output=True, // encoding="ascii", // errors="surrogateescape", // ).stdout: // ``` true } else { fn is_parenthesized(expr: &Expr, context: &PyFormatContext) -> bool { // Don't break subscripts except in parenthesized context. It looks weird. !expr.is_subscript_expr() && has_parentheses(expr, context).is_some_and(OwnParentheses::is_non_empty) } // Only use the layout if the first expression starts with parentheses // or the last expression ends with parentheses of some sort, and // those parentheses are non-empty. visitor .last .is_some_and(|last| is_parenthesized(last, context)) || visitor .first .expression() .is_some_and(|first| is_parenthesized(first, context)) } } #[derive(Clone, Debug)] struct CanOmitOptionalParenthesesVisitor<'input> { max_precedence: OperatorPrecedence, max_precedence_count: u32, any_parenthesized_expressions: bool, last: Option<&'input Expr>, first: First<'input>, context: &'input PyFormatContext<'input>, } impl<'input> CanOmitOptionalParenthesesVisitor<'input> { fn new(context: &'input PyFormatContext) -> Self { Self { context, max_precedence: OperatorPrecedence::None, max_precedence_count: 0, any_parenthesized_expressions: false, last: None, first: First::None, } } fn update_max_precedence(&mut self, precedence: OperatorPrecedence) { self.update_max_precedence_with_count(precedence, 1); } fn update_max_precedence_with_count(&mut self, precedence: OperatorPrecedence, count: u32) { match self.max_precedence.cmp(&precedence) { Ordering::Less => { self.max_precedence_count = count; self.max_precedence = precedence; } Ordering::Equal => { self.max_precedence_count += count; } Ordering::Greater => {} } } // Visits a subexpression, ignoring whether it is parenthesized or not fn visit_subexpression(&mut self, expr: &'input Expr) { match expr { Expr::Dict(_) | Expr::List(_) | Expr::Set(_) | Expr::ListComp(_) | Expr::SetComp(_) | Expr::DictComp(_) => { self.any_parenthesized_expressions = true; // The values are always parenthesized, don't visit. return; } Expr::Tuple(ast::ExprTuple { parenthesized: true, .. }) => { self.any_parenthesized_expressions = true; // The values are always parenthesized, don't visit. return; } Expr::Generator(generator) if generator.parenthesized => { self.any_parenthesized_expressions = true; // The values are always parenthesized, don't visit. return; } // It's impossible for a file smaller or equal to 4GB to contain more than 2^32 comparisons // because each comparison requires a left operand, and `n` `operands` and right sides. #[expect(clippy::cast_possible_truncation)] Expr::BoolOp(ast::ExprBoolOp { range: _, node_index: _, op: _, values, }) => self.update_max_precedence_with_count( OperatorPrecedence::BooleanOperation, values.len().saturating_sub(1) as u32, ), Expr::BinOp(ast::ExprBinOp { op, left: _, right: _, range: _, node_index: _, }) => self.update_max_precedence(OperatorPrecedence::from(*op)), Expr::If(_) => { // + 1 for the if and one for the else self.update_max_precedence_with_count(OperatorPrecedence::Conditional, 2); } // It's impossible for a file smaller or equal to 4GB to contain more than 2^32 comparisons // because each comparison requires a left operand, and `n` `operands` and right sides. #[expect(clippy::cast_possible_truncation)] Expr::Compare(ast::ExprCompare { range: _, node_index: _, left: _, ops, comparators: _, }) => { self.update_max_precedence_with_count( OperatorPrecedence::Comparator, ops.len() as u32, ); } Expr::Call(ast::ExprCall { range: _, node_index: _, func, arguments: _, }) => { self.any_parenthesized_expressions = true; // Only walk the function, the arguments are always parenthesized self.visit_expr(func); self.last = Some(expr); return; } Expr::Subscript(ast::ExprSubscript { value, .. }) => { self.any_parenthesized_expressions = true; // Only walk the function, the subscript is always parenthesized self.visit_expr(value); self.last = Some(expr); // Don't walk the slice, because the slice is always parenthesized. return; } // `[a, b].test.test[300].dot` Expr::Attribute(ast::ExprAttribute { range: _, node_index: _, value, attr: _, ctx: _, }) => { self.visit_expr(value); if has_parentheses(value, self.context).is_some() { self.update_max_precedence(OperatorPrecedence::Attribute); } self.last = Some(expr); return; } // Non terminal nodes that don't have a termination token. Expr::Named(_) | Expr::Generator(_) | Expr::Tuple(_) => {} // Expressions with sub expressions but a preceding token // Mark this expression as first expression and not the sub expression. // Visit the sub-expressions because the sub expressions may be the end of the entire expression. Expr::UnaryOp(ast::ExprUnaryOp { range: _, node_index: _, op, operand: _, }) => { if op.is_invert() { self.update_max_precedence(OperatorPrecedence::BitwiseInversion); } self.first.set_if_none(First::Token); } Expr::Lambda(_) | Expr::Await(_) | Expr::Yield(_) | Expr::YieldFrom(_) | Expr::Starred(_) => { self.first.set_if_none(First::Token); } // Terminal nodes or nodes that wrap a sub-expression (where the sub expression can never be at the end). Expr::FString(_) | Expr::TString(_)
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_dict_comp.rs
crates/ruff_python_formatter/src/expression/expr_dict_comp.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprDictComp; use ruff_text_size::Ranged; use crate::comments::dangling_comments; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses, parenthesized}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprDictComp; impl FormatNodeRule<ExprDictComp> for FormatExprDictComp { fn fmt_fields(&self, item: &ExprDictComp, f: &mut PyFormatter) -> FormatResult<()> { let ExprDictComp { range: _, node_index: _, key, value, generators, } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); // Dangling comments can either appear after the open bracket, or around the key-value // pairs: // ```python // { # open_parenthesis_comments // x: # key_value_comments // y // for (x, y) in z // } // ``` let (open_parenthesis_comments, key_value_comments) = dangling.split_at(dangling.partition_point(|comment| comment.end() < key.start())); write!( f, [parenthesized( "{", &group(&format_with(|f| { write!(f, [group(&key.format()), token(":")])?; if key_value_comments.is_empty() { space().fmt(f)?; } else { dangling_comments(key_value_comments).fmt(f)?; } write!(f, [value.format(), soft_line_break_or_space()])?; f.join_with(soft_line_break_or_space()) .entries(generators.iter().formatted()) .finish() })), "}" ) .with_dangling_comments(open_parenthesis_comments)] ) } } impl NeedsParentheses for ExprDictComp { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_compare.rs
crates/ruff_python_formatter/src/expression/expr_compare.rs
use ruff_formatter::{FormatOwnedWithRule, FormatRefWithRule}; use ruff_python_ast::{AnyNodeRef, StringLike}; use ruff_python_ast::{CmpOp, ExprCompare}; use crate::expression::binary_like::BinaryLike; use crate::expression::has_parentheses; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; use crate::string::StringLikeExtensions; #[derive(Default)] pub struct FormatExprCompare; impl FormatNodeRule<ExprCompare> for FormatExprCompare { #[inline] fn fmt_fields(&self, item: &ExprCompare, f: &mut PyFormatter) -> FormatResult<()> { BinaryLike::Compare(item).fmt(f) } } impl NeedsParentheses for ExprCompare { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if parent.is_expr_await() { OptionalParentheses::Always } else if let Ok(string) = StringLike::try_from(&*self.left) { // Multiline strings are guaranteed to never fit, avoid adding unnecessary parentheses if !string.is_implicit_concatenated() && string.is_multiline(context) && !context.comments().has(string) && self.comparators.first().is_some_and(|right| { has_parentheses(right, context).is_some() && !context.comments().has(right) }) { OptionalParentheses::Never } else { OptionalParentheses::Multiline } } else { OptionalParentheses::Multiline } } } #[derive(Copy, Clone)] pub struct FormatCmpOp; impl<'ast> AsFormat<PyFormatContext<'ast>> for CmpOp { type Format<'a> = FormatRefWithRule<'a, CmpOp, FormatCmpOp, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatCmpOp) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for CmpOp { type Format = FormatOwnedWithRule<CmpOp, FormatCmpOp, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatCmpOp) } } impl FormatRule<CmpOp, PyFormatContext<'_>> for FormatCmpOp { fn fmt(&self, item: &CmpOp, f: &mut PyFormatter) -> FormatResult<()> { let operator = match item { CmpOp::Eq => "==", CmpOp::NotEq => "!=", CmpOp::Lt => "<", CmpOp::LtE => "<=", CmpOp::Gt => ">", CmpOp::GtE => ">=", CmpOp::Is => "is", CmpOp::IsNot => "is not", CmpOp::In => "in", CmpOp::NotIn => "not in", }; token(operator).fmt(f) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_boolean_literal.rs
crates/ruff_python_formatter/src/expression/expr_boolean_literal.rs
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprBooleanLiteral; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprBooleanLiteral; impl FormatNodeRule<ExprBooleanLiteral> for FormatExprBooleanLiteral { fn fmt_fields(&self, item: &ExprBooleanLiteral, f: &mut PyFormatter) -> FormatResult<()> { if item.value { token("True").fmt(f) } else { token("False").fmt(f) } } } impl NeedsParentheses for ExprBooleanLiteral { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::BestFit } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_name.rs
crates/ruff_python_formatter/src/expression/expr_name.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprName; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprName; impl FormatNodeRule<ExprName> for FormatExprName { fn fmt_fields(&self, item: &ExprName, f: &mut PyFormatter) -> FormatResult<()> { let ExprName { id: _, range, ctx: _, node_index: _, } = item; write!(f, [source_text_slice(*range)]) } } impl NeedsParentheses for ExprName { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::BestFit } } #[cfg(test)] mod tests { use ruff_python_parser::parse_module; use ruff_text_size::{Ranged, TextRange, TextSize}; #[test] fn name_range_with_comments() { let module = parse_module("a # comment").unwrap(); let expression_statement = module .suite() .first() .expect("Expected non-empty body") .as_expr_stmt() .unwrap(); let name = expression_statement .value .as_name_expr() .expect("Expected name expression"); assert_eq!( name.range(), TextRange::at(TextSize::new(0), TextSize::new(1)) ); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_attribute.rs
crates/ruff_python_formatter/src/expression/expr_attribute.rs
use ruff_formatter::{FormatRuleWithOptions, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{Expr, ExprAttribute, ExprNumberLiteral, Number}; use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer, find_only_token_in_range}; use ruff_text_size::{Ranged, TextRange}; use crate::comments::dangling_comments; use crate::expression::CallChainLayout; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parentheses, is_expression_parenthesized, }; use crate::prelude::*; use crate::preview::is_fluent_layout_split_first_call_enabled; #[derive(Default)] pub struct FormatExprAttribute { call_chain_layout: CallChainLayout, } impl FormatRuleWithOptions<ExprAttribute, PyFormatContext<'_>> for FormatExprAttribute { type Options = CallChainLayout; fn with_options(mut self, options: Self::Options) -> Self { self.call_chain_layout = options; self } } impl FormatNodeRule<ExprAttribute> for FormatExprAttribute { fn fmt_fields(&self, item: &ExprAttribute, f: &mut PyFormatter) -> FormatResult<()> { let ExprAttribute { value, range: _, node_index: _, attr, ctx: _, } = item; let call_chain_layout = self.call_chain_layout.apply_in_node(item, f); let format_inner = format_with(|f: &mut PyFormatter| { let parenthesize_value = is_base_ten_number_literal(value.as_ref(), f.context().source()) || { is_expression_parenthesized( value.into(), f.context().comments().ranges(), f.context().source(), ) }; if call_chain_layout.is_fluent() { if parenthesize_value { // Don't propagate the call chain layout. value.format().with_options(Parentheses::Always).fmt(f)?; } else { match value.as_ref() { Expr::Attribute(expr) => { expr.format() .with_options(call_chain_layout.transition_after_attribute()) .fmt(f)?; } Expr::Call(expr) => { expr.format() .with_options(call_chain_layout.transition_after_attribute()) .fmt(f)?; } Expr::Subscript(expr) => { expr.format() .with_options(call_chain_layout.transition_after_attribute()) .fmt(f)?; } _ => { value.format().with_options(Parentheses::Never).fmt(f)?; } } } } else if parenthesize_value { value.format().with_options(Parentheses::Always).fmt(f)?; } else { value.format().with_options(Parentheses::Never).fmt(f)?; } let comments = f.context().comments().clone(); // Always add a line break if the value is parenthesized and there's an // end of line comment on the same line as the closing parenthesis. // ```python // ( // ( // a // ) # `end_of_line_comment` // . // b // ) // ``` let has_trailing_end_of_line_comment = SimpleTokenizer::starts_at(value.end(), f.context().source()) .skip_trivia() .take_while(|token| token.kind == SimpleTokenKind::RParen) .last() .is_some_and(|right_paren| { let trailing_value_comments = comments.trailing(&**value); trailing_value_comments.iter().any(|comment| { comment.line_position().is_end_of_line() && comment.start() > right_paren.end() }) }); if has_trailing_end_of_line_comment { hard_line_break().fmt(f)?; } // Allow the `.` on its own line if this is a fluent call chain // and the value either requires parenthesizing or is a call or subscript expression // (it's a fluent chain but not the first element). // // In preview we also break _at_ the first call in the chain. // For example: // // ```diff // # stable formatting vs. preview // x = ( // - df.merge() // + df // + .merge() // .groupby() // .agg() // .filter() // ) // ``` else if call_chain_layout.is_fluent() { if parenthesize_value || value.is_call_expr() || value.is_subscript_expr() // Remember to update the doc-comment above when // stabilizing this behavior. || (is_fluent_layout_split_first_call_enabled(f.context()) && call_chain_layout.is_first_call_like()) { soft_line_break().fmt(f)?; } } // Identify dangling comments before and after the dot: // ```python // ( // ( // a // ) // # `before_dot` // . # `after_dot` // # `after_dot` // b // ) // ``` let dangling = comments.dangling(item); let (before_dot, after_dot) = if dangling.is_empty() { (dangling, dangling) } else { let dot_token = find_only_token_in_range( TextRange::new(item.value.end(), item.attr.start()), SimpleTokenKind::Dot, f.context().source(), ); dangling.split_at( dangling.partition_point(|comment| comment.start() < dot_token.start()), ) }; write!( f, [ dangling_comments(before_dot), token("."), dangling_comments(after_dot), attr.format() ] ) }); let is_call_chain_root = self.call_chain_layout == CallChainLayout::Default && call_chain_layout.is_fluent(); if is_call_chain_root { write!(f, [group(&format_inner)]) } else { write!(f, [format_inner]) } } } impl NeedsParentheses for ExprAttribute { fn needs_parentheses( &self, _parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { // Checks if there are any own line comments in an attribute chain (a.b.c). if CallChainLayout::from_expression( self.into(), context.comments().ranges(), context.source(), ) .is_fluent() { OptionalParentheses::Multiline } else if context.comments().has_dangling(self) { OptionalParentheses::Always } else if is_expression_parenthesized( self.value.as_ref().into(), context.comments().ranges(), context.source(), ) { // We have to avoid creating syntax errors like // ```python // variable = (something) # trailing // .my_attribute // ``` // See https://github.com/astral-sh/ruff/issues/19350 if context .comments() .trailing(self.value.as_ref()) .iter() .any(|comment| comment.line_position().is_end_of_line()) { OptionalParentheses::Multiline } else { OptionalParentheses::Never } } else { self.value.needs_parentheses(self.into(), context) } } } // Non Hex, octal or binary number literals need parentheses to disambiguate the attribute `.` from // a decimal point. Floating point numbers don't strictly need parentheses but it reads better (rather than 0.0.test()). fn is_base_ten_number_literal(expr: &Expr, source: &str) -> bool { if let Some(ExprNumberLiteral { value, range, node_index: _, }) = expr.as_number_literal_expr() { match value { Number::Float(_) => true, Number::Int(_) => { let text = &source[*range]; !matches!( text.as_bytes().get(0..2), Some([b'0', b'x' | b'X' | b'o' | b'O' | b'b' | b'B']) ) } Number::Complex { .. } => false, } } else { false } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_generator.rs
crates/ruff_python_formatter/src/expression/expr_generator.rs
use ruff_formatter::{FormatRuleWithOptions, format_args, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprGenerator; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses, parenthesized}; use crate::prelude::*; #[derive(Eq, PartialEq, Debug, Default)] pub enum GeneratorExpParentheses { #[default] Default, /// Skips the parentheses if they aren't present in the source code. Used when formatting call expressions /// because the parentheses are optional if the generator is the **only** argument: /// /// ```python /// all(x for y in z)` /// ``` Preserve, } impl FormatRuleWithOptions<ExprGenerator, PyFormatContext<'_>> for FormatExprGenerator { type Options = GeneratorExpParentheses; fn with_options(mut self, options: Self::Options) -> Self { self.parentheses = options; self } } #[derive(Default)] pub struct FormatExprGenerator { parentheses: GeneratorExpParentheses, } impl FormatNodeRule<ExprGenerator> for FormatExprGenerator { fn fmt_fields(&self, item: &ExprGenerator, f: &mut PyFormatter) -> FormatResult<()> { let ExprGenerator { range: _, node_index: _, elt, generators, parenthesized: is_parenthesized, } = item; let joined = format_with(|f| { f.join_with(soft_line_break_or_space()) .entries(generators.iter().formatted()) .finish() }); let comments = f.context().comments().clone(); let dangling = comments.dangling(item); if self.parentheses == GeneratorExpParentheses::Preserve && dangling.is_empty() && !is_parenthesized { write!( f, [group(&elt.format()), soft_line_break_or_space(), &joined] ) } else { write!( f, [parenthesized( "(", &group(&format_args!( group(&elt.format()), soft_line_break_or_space(), joined )), ")" ) .with_dangling_comments(dangling)] ) } } } impl NeedsParentheses for ExprGenerator { fn needs_parentheses( &self, parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { if parent.is_expr_await() { OptionalParentheses::Always } else { OptionalParentheses::Never } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_if.rs
crates/ruff_python_formatter/src/expression/expr_if.rs
use ruff_formatter::{FormatRuleWithOptions, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{Expr, ExprIf}; use crate::comments::leading_comments; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, in_parentheses_only_group, in_parentheses_only_soft_line_break_or_space, is_expression_parenthesized, }; use crate::prelude::*; #[derive(Default, Copy, Clone)] pub enum ExprIfLayout { #[default] Default, /// The [`ExprIf`] is nested inside another [`ExprIf`], so it should not be given a new /// group. For example, avoid grouping the `else` clause in: /// ```python /// clone._iterable_class = ( /// NamedValuesListIterable /// if named /// else FlatValuesListIterable /// if flat /// else ValuesListIterable /// ) /// ``` Nested, } #[derive(Default)] pub struct FormatExprIf { layout: ExprIfLayout, } impl FormatRuleWithOptions<ExprIf, PyFormatContext<'_>> for FormatExprIf { type Options = ExprIfLayout; fn with_options(mut self, options: Self::Options) -> Self { self.layout = options; self } } impl FormatNodeRule<ExprIf> for FormatExprIf { fn fmt_fields(&self, item: &ExprIf, f: &mut PyFormatter) -> FormatResult<()> { let ExprIf { range: _, node_index: _, test, body, orelse, } = item; let comments = f.context().comments().clone(); let inner = format_with(|f: &mut PyFormatter| { // We place `if test` and `else orelse` on a single line, so the `test` and `orelse` leading // comments go on the line before the `if` or `else` instead of directly ahead `test` or // `orelse` write!( f, [ body.format(), in_parentheses_only_soft_line_break_or_space(), leading_comments(comments.leading(test.as_ref())), token("if"), space(), test.format(), in_parentheses_only_soft_line_break_or_space(), leading_comments(comments.leading(orelse.as_ref())), token("else"), space(), ] )?; FormatOrElse { orelse }.fmt(f) }); match self.layout { ExprIfLayout::Default => in_parentheses_only_group(&inner).fmt(f), ExprIfLayout::Nested => inner.fmt(f), } } } impl NeedsParentheses for ExprIf { fn needs_parentheses( &self, parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { if parent.is_expr_await() { OptionalParentheses::Always } else { OptionalParentheses::Multiline } } } #[derive(Debug)] struct FormatOrElse<'a> { orelse: &'a Expr, } impl Format<PyFormatContext<'_>> for FormatOrElse<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { match self.orelse { Expr::If(expr) if !is_expression_parenthesized( expr.into(), f.context().comments().ranges(), f.context().source(), ) => { write!(f, [expr.format().with_options(ExprIfLayout::Nested)]) } _ => write!(f, [in_parentheses_only_group(&self.orelse.format())]), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_await.rs
crates/ruff_python_formatter/src/expression/expr_await.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprAwait; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parenthesize, is_expression_parenthesized, }; use crate::prelude::*; #[derive(Default)] pub struct FormatExprAwait; impl FormatNodeRule<ExprAwait> for FormatExprAwait { fn fmt_fields(&self, item: &ExprAwait, f: &mut PyFormatter) -> FormatResult<()> { let ExprAwait { range: _, node_index: _, value, } = item; write!( f, [ token("await"), space(), maybe_parenthesize_expression(value, item, Parenthesize::IfBreaks) ] ) } } impl NeedsParentheses for ExprAwait { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if parent.is_expr_await() { OptionalParentheses::Always } else if is_expression_parenthesized( self.value.as_ref().into(), context.comments().ranges(), context.source(), ) { // Prefer splitting the value if it is parenthesized. OptionalParentheses::Never } else { self.value.needs_parentheses(self.into(), context) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_none_literal.rs
crates/ruff_python_formatter/src/expression/expr_none_literal.rs
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprNoneLiteral; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatExprNoneLiteral; impl FormatNodeRule<ExprNoneLiteral> for FormatExprNoneLiteral { fn fmt_fields(&self, _item: &ExprNoneLiteral, f: &mut PyFormatter) -> FormatResult<()> { token("None").fmt(f) } } impl NeedsParentheses for ExprNoneLiteral { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::BestFit } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_call.rs
crates/ruff_python_formatter/src/expression/expr_call.rs
use ruff_formatter::FormatRuleWithOptions; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{Expr, ExprCall}; use crate::comments::dangling_comments; use crate::expression::CallChainLayout; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parentheses, is_expression_parenthesized, }; use crate::prelude::*; #[derive(Default)] pub struct FormatExprCall { call_chain_layout: CallChainLayout, } impl FormatRuleWithOptions<ExprCall, PyFormatContext<'_>> for FormatExprCall { type Options = CallChainLayout; fn with_options(mut self, options: Self::Options) -> Self { self.call_chain_layout = options; self } } impl FormatNodeRule<ExprCall> for FormatExprCall { fn fmt_fields(&self, item: &ExprCall, f: &mut PyFormatter) -> FormatResult<()> { let ExprCall { range: _, node_index: _, func, arguments, } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); let call_chain_layout = self.call_chain_layout.apply_in_node(item, f); let fmt_func = format_with(|f: &mut PyFormatter| { // Format the function expression. if is_expression_parenthesized( func.into(), f.context().comments().ranges(), f.context().source(), ) { func.format().with_options(Parentheses::Always).fmt(f) } else { match func.as_ref() { Expr::Attribute(expr) => expr .format() .with_options(call_chain_layout.decrement_call_like_count()) .fmt(f), Expr::Call(expr) => expr.format().with_options(call_chain_layout).fmt(f), Expr::Subscript(expr) => expr.format().with_options(call_chain_layout).fmt(f), _ => func.format().with_options(Parentheses::Never).fmt(f), } }?; // Format comments between the function and its arguments. dangling_comments(dangling).fmt(f)?; // Format the arguments. arguments.format().fmt(f) }); // Allow to indent the parentheses while // ```python // g1 = ( // queryset.distinct().order_by(field.name).values_list(field_name_flat_long_long=True) // ) // ``` if call_chain_layout.is_fluent() && self.call_chain_layout == CallChainLayout::Default { group(&fmt_func).fmt(f) } else { fmt_func.fmt(f) } } } impl NeedsParentheses for ExprCall { fn needs_parentheses( &self, _parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { if CallChainLayout::from_expression( self.into(), context.comments().ranges(), context.source(), ) .is_fluent() { OptionalParentheses::Multiline } else if context.comments().has_dangling(self) { OptionalParentheses::Always } else if is_expression_parenthesized( self.func.as_ref().into(), context.comments().ranges(), context.source(), ) { OptionalParentheses::Never } else { self.func.needs_parentheses(self.into(), context) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_named.rs
crates/ruff_python_formatter/src/expression/expr_named.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprNamed; use crate::comments::dangling_comments; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, in_parentheses_only_soft_line_break_or_space, }; use crate::prelude::*; #[derive(Default)] pub struct FormatExprNamed; impl FormatNodeRule<ExprNamed> for FormatExprNamed { fn fmt_fields(&self, item: &ExprNamed, f: &mut PyFormatter) -> FormatResult<()> { let ExprNamed { target, value, range: _, node_index: _, } = item; // This context, a dangling comment is a comment between the `:=` and the value. let comments = f.context().comments().clone(); let dangling = comments.dangling(item); write!( f, [ group(&format_args![ target.format(), in_parentheses_only_soft_line_break_or_space() ]), token(":=") ] )?; if dangling.is_empty() { write!(f, [space()])?; } else { write!(f, [dangling_comments(dangling), hard_line_break()])?; } write!(f, [value.format()]) } } impl NeedsParentheses for ExprNamed { fn needs_parentheses( &self, parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { // Unlike tuples, named expression parentheses are not part of the range even when // mandatory. See [PEP 572](https://peps.python.org/pep-0572/) for details. if parent.is_stmt_ann_assign() || parent.is_stmt_assign() || parent.is_stmt_aug_assign() || parent.is_stmt_assert() || parent.is_stmt_return() || parent.is_except_handler_except_handler() || parent.is_with_item() || parent.is_expr_yield() || parent.is_expr_yield_from() || parent.is_expr_await() || parent.is_stmt_delete() || parent.is_stmt_for() || parent.is_stmt_function_def() { OptionalParentheses::Always } else { OptionalParentheses::Multiline } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_subscript.rs
crates/ruff_python_formatter/src/expression/expr_subscript.rs
use ruff_formatter::{FormatRuleWithOptions, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{Expr, ExprSubscript}; use crate::expression::CallChainLayout; use crate::expression::expr_tuple::TupleParentheses; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parentheses, is_expression_parenthesized, parenthesized, }; use crate::prelude::*; #[derive(Default)] pub struct FormatExprSubscript { call_chain_layout: CallChainLayout, } impl FormatRuleWithOptions<ExprSubscript, PyFormatContext<'_>> for FormatExprSubscript { type Options = CallChainLayout; fn with_options(mut self, options: Self::Options) -> Self { self.call_chain_layout = options; self } } impl FormatNodeRule<ExprSubscript> for FormatExprSubscript { fn fmt_fields(&self, item: &ExprSubscript, f: &mut PyFormatter) -> FormatResult<()> { let ExprSubscript { range: _, node_index: _, value, slice, ctx: _, } = item; let call_chain_layout = self.call_chain_layout.apply_in_node(item, f); let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(item); debug_assert!( dangling_comments.len() <= 1, "A subscript expression can only have a single dangling comment, the one after the bracket" ); let format_inner = format_with(|f: &mut PyFormatter| { if is_expression_parenthesized( value.into(), f.context().comments().ranges(), f.context().source(), ) { value.format().with_options(Parentheses::Always).fmt(f) } else { match value.as_ref() { Expr::Attribute(expr) => expr .format() .with_options(call_chain_layout.decrement_call_like_count()) .fmt(f), Expr::Call(expr) => expr.format().with_options(call_chain_layout).fmt(f), Expr::Subscript(expr) => expr.format().with_options(call_chain_layout).fmt(f), _ => value.format().with_options(Parentheses::Never).fmt(f), } }?; let format_slice = format_with(|f: &mut PyFormatter| { if let Expr::Tuple(tuple) = slice.as_ref() { write!(f, [tuple.format().with_options(TupleParentheses::Preserve)]) } else { write!(f, [slice.format()]) } }); parenthesized("[", &format_slice, "]") .with_dangling_comments(dangling_comments) .fmt(f) }); let is_call_chain_root = self.call_chain_layout == CallChainLayout::Default && call_chain_layout.is_fluent(); if is_call_chain_root { write!(f, [group(&format_inner)]) } else { write!(f, [format_inner]) } } } impl NeedsParentheses for ExprSubscript { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { { if CallChainLayout::from_expression( self.into(), context.comments().ranges(), context.source(), ) .is_fluent() { OptionalParentheses::Multiline } else if is_expression_parenthesized( self.value.as_ref().into(), context.comments().ranges(), context.source(), ) { OptionalParentheses::Never } else { match self.value.needs_parentheses(self.into(), context) { OptionalParentheses::BestFit => { if let Some(function) = parent.as_stmt_function_def() { if function.returns.as_deref().is_some_and(|returns| { AnyNodeRef::ptr_eq(returns.into(), self.into()) }) { if function.parameters.is_empty() && !context.comments().has(&*function.parameters) { // Apply the `optional_parentheses` layout when the subscript // is in a return type position of a function without parameters. // This ensures the subscript is parenthesized if it has a very // long name that goes over the line length limit. return OptionalParentheses::Multiline; } // Don't use the best fitting layout for return type annotation because it results in the // return type expanding before the parameters. return OptionalParentheses::Never; } } OptionalParentheses::BestFit } parentheses => parentheses, } } } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/expression/expr_list.rs
crates/ruff_python_formatter/src/expression/expr_list.rs
use ruff_formatter::prelude::format_with; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::ExprList; use ruff_text_size::Ranged; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, empty_parenthesized, parenthesized, }; use crate::prelude::*; #[derive(Default)] pub struct FormatExprList; impl FormatNodeRule<ExprList> for FormatExprList { fn fmt_fields(&self, item: &ExprList, f: &mut PyFormatter) -> FormatResult<()> { let ExprList { range: _, node_index: _, elts, ctx: _, } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); if elts.is_empty() { return empty_parenthesized("[", dangling, "]").fmt(f); } let items = format_with(|f| { f.join_comma_separated(item.end()) .nodes(elts.iter()) .finish() }); parenthesized("[", &items, "]") .with_dangling_comments(dangling) .fmt(f) } } impl NeedsParentheses for ExprList { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/comments/visitor.rs
crates/ruff_python_formatter/src/comments/visitor.rs
use std::fmt::Debug; use std::iter::Peekable; use ruff_formatter::{SourceCode, SourceCodeSlice}; use ruff_python_ast::{AnyNodeRef, Identifier}; use ruff_python_ast::{Mod, Stmt}; // The interface is designed to only export the members relevant for iterating nodes in // pre-order. #[allow(clippy::wildcard_imports)] use ruff_python_ast::visitor::source_order::*; use ruff_python_trivia::{CommentLinePosition, CommentRanges}; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::comments::node_key::NodeRefEqualityKey; use crate::comments::placement::place_comment; use crate::comments::{CommentsMap, SourceComment}; /// Collect the preceding, following and enclosing node for each comment without applying /// [`place_comment`] for debugging. pub(crate) fn collect_comments<'a>( root: &'a Mod, source_code: SourceCode<'a>, comment_ranges: &'a CommentRanges, ) -> Vec<DecoratedComment<'a>> { let mut collector = CommentsVecBuilder::default(); CommentsVisitor::new(source_code, comment_ranges, &mut collector).visit(AnyNodeRef::from(root)); collector.comments } /// Visitor extracting the comments from an AST. pub(super) struct CommentsVisitor<'a, 'builder> { builder: &'builder mut (dyn PushComment<'a> + 'a), source_code: SourceCode<'a>, parents: Vec<AnyNodeRef<'a>>, preceding_node: Option<AnyNodeRef<'a>>, comment_ranges: Peekable<std::slice::Iter<'a, TextRange>>, } impl<'a, 'builder> CommentsVisitor<'a, 'builder> { pub(super) fn new( source_code: SourceCode<'a>, comment_ranges: &'a CommentRanges, builder: &'builder mut (dyn PushComment<'a> + 'a), ) -> Self { Self { builder, source_code, parents: Vec::new(), preceding_node: None, comment_ranges: comment_ranges.iter().peekable(), } } pub(super) fn visit(mut self, root: AnyNodeRef<'a>) { if self.enter_node(root).is_traverse() { root.visit_source_order(&mut self); } self.leave_node(root); } // Try to skip the subtree if // * there are no comments // * if the next comment comes after this node (meaning, this nodes subtree contains no comments) fn can_skip(&mut self, node_end: TextSize) -> bool { self.comment_ranges .peek() .is_none_or(|next_comment| next_comment.start() >= node_end) } } impl<'ast> SourceOrderVisitor<'ast> for CommentsVisitor<'ast, '_> { fn enter_node(&mut self, node: AnyNodeRef<'ast>) -> TraversalSignal { let node_range = node.range(); let enclosing_node = self.parents.last().copied().unwrap_or(node); // Process all remaining comments that end before this node's start position. // If the `preceding` node is set, then it process all comments ending after the `preceding` node // and ending before this node's start position while let Some(comment_range) = self.comment_ranges.peek().copied() { // Exit if the comment is enclosed by this node or comes after it if comment_range.end() > node_range.start() { break; } let comment = DecoratedComment { enclosing: enclosing_node, preceding: self.preceding_node, following: Some(node), parent: self.parents.iter().rev().nth(1).copied(), line_position: CommentLinePosition::for_range( *comment_range, self.source_code.as_str(), ), slice: self.source_code.slice(*comment_range), }; self.builder.push_comment(comment); self.comment_ranges.next(); } // From here on, we're inside of `node`, meaning, we're passed the preceding node. self.preceding_node = None; self.parents.push(node); if self.can_skip(node_range.end()) { TraversalSignal::Skip } else { TraversalSignal::Traverse } } fn leave_node(&mut self, node: AnyNodeRef<'ast>) { // We are leaving this node, pop it from the parent stack. self.parents.pop(); let node_end = node.end(); let is_root = self.parents.is_empty(); // Process all comments that start after the `preceding` node and end before this node's end. while let Some(comment_range) = self.comment_ranges.peek().copied() { // If the comment starts after this node, break. // If this is the root node and there are comments after the node, attach them to the root node // anyway because there's no other node we can attach the comments to (RustPython should include the comments in the node's range) if comment_range.start() >= node_end && !is_root { break; } let comment = DecoratedComment { enclosing: node, parent: self.parents.last().copied(), preceding: self.preceding_node, following: None, line_position: CommentLinePosition::for_range( *comment_range, self.source_code.as_str(), ), slice: self.source_code.slice(*comment_range), }; self.builder.push_comment(comment); self.comment_ranges.next(); } self.preceding_node = Some(node); } fn visit_body(&mut self, body: &'ast [Stmt]) { match body { [] => { // no-op } [only] => self.visit_stmt(only), [first, .., last] => { if self.can_skip(last.end()) { // Skip traversing the body when there's no comment between the first and last statement. // It is still necessary to visit the first statement to process all comments between // the previous node and the first statement. self.visit_stmt(first); self.preceding_node = Some(last.into()); } else { walk_body(self, body); } } } } fn visit_identifier(&mut self, _identifier: &'ast Identifier) { // TODO: Visit and associate comments with identifiers } } /// A comment decorated with additional information about its surrounding context in the source document. /// /// Used by [`place_comment`] to determine if this should become a [leading](self#leading-comments), /// [dangling](self#dangling-comments), or [trailing](self#trailing-comments) comment. #[derive(Debug, Clone)] pub(crate) struct DecoratedComment<'a> { enclosing: AnyNodeRef<'a>, preceding: Option<AnyNodeRef<'a>>, following: Option<AnyNodeRef<'a>>, parent: Option<AnyNodeRef<'a>>, line_position: CommentLinePosition, slice: SourceCodeSlice, } impl<'a> DecoratedComment<'a> { /// The closest parent node that fully encloses the comment. /// /// A node encloses a comment when the comment is between two of its direct children (ignoring lists). /// /// # Examples /// /// ```python /// [ /// a, /// # comment /// b /// ] /// ``` /// /// The enclosing node is the list expression and not the name `b` because /// `a` and `b` are children of the list expression and `comment` is between the two nodes. pub(crate) fn enclosing_node(&self) -> AnyNodeRef<'a> { self.enclosing } /// Returns the parent of the enclosing node, if any pub(super) fn enclosing_parent(&self) -> Option<AnyNodeRef<'a>> { self.parent } /// Returns the comment's preceding node. /// /// The direct child node (ignoring lists) of the [`enclosing_node`](DecoratedComment::enclosing_node) that precedes this comment. /// /// Returns [None] if the [`enclosing_node`](DecoratedComment::enclosing_node) only consists of tokens or if /// all preceding children of the [`enclosing_node`](DecoratedComment::enclosing_node) have been tokens. /// /// The Preceding node is guaranteed to be a sibling of [`following_node`](DecoratedComment::following_node). /// /// # Examples /// /// ## Preceding tokens only /// /// ```python /// [ /// # comment /// ] /// ``` /// Returns [None] because the comment has no preceding node, only a preceding `[` token. /// /// ## Preceding node /// /// ```python /// a # comment /// b /// ``` /// /// Returns `Some(a)` because `a` directly precedes the comment. /// /// ## Preceding token and node /// /// ```python /// [ /// a, # comment /// b /// ] /// ``` /// /// Returns `Some(a)` because `a` is the preceding node of `comment`. The presence of the `,` token /// doesn't change that. pub(crate) fn preceding_node(&self) -> Option<AnyNodeRef<'a>> { self.preceding } /// Returns the node following the comment. /// /// The direct child node (ignoring lists) of the [`enclosing_node`](DecoratedComment::enclosing_node) that follows this comment. /// /// Returns [None] if the [`enclosing_node`](DecoratedComment::enclosing_node) only consists of tokens or if /// all children children of the [`enclosing_node`](DecoratedComment::enclosing_node) following this comment are tokens. /// /// The following node is guaranteed to be a sibling of [`preceding_node`](DecoratedComment::preceding_node). /// /// # Examples /// /// ## Following tokens only /// /// ```python /// [ /// # comment /// ] /// ``` /// /// Returns [None] because there's no node following the comment, only the `]` token. /// /// ## Following node /// /// ```python /// [ # comment /// a /// ] /// ``` /// /// Returns `Some(a)` because `a` is the node directly following the comment. /// /// ## Following token and node /// /// ```python /// [ /// a # comment /// , b /// ] /// ``` /// /// Returns `Some(b)` because the `b` identifier is the first node following `comment`. /// /// ## Following parenthesized expression /// /// ```python /// ( /// a /// # comment /// ) /// b /// ``` /// /// Returns `None` because `comment` is enclosed inside the parenthesized expression and it has no children /// following `# comment`. pub(crate) fn following_node(&self) -> Option<AnyNodeRef<'a>> { self.following } /// The position of the comment in the text. pub(super) fn line_position(&self) -> CommentLinePosition { self.line_position } /// Returns the slice into the source code. pub(crate) fn slice(&self) -> &SourceCodeSlice { &self.slice } } impl Ranged for DecoratedComment<'_> { #[inline] fn range(&self) -> TextRange { self.slice.range() } } impl From<DecoratedComment<'_>> for SourceComment { fn from(decorated: DecoratedComment) -> Self { Self::new(decorated.slice, decorated.line_position) } } #[derive(Debug)] pub(super) enum CommentPlacement<'a> { /// Makes `comment` a [leading comment](self#leading-comments) of `node`. Leading { node: AnyNodeRef<'a>, comment: SourceComment, }, /// Makes `comment` a [trailing comment](self#trailing-comments) of `node`. Trailing { node: AnyNodeRef<'a>, comment: SourceComment, }, /// Makes `comment` a [dangling comment](self#dangling-comments) of `node`. Dangling { node: AnyNodeRef<'a>, comment: SourceComment, }, /// Uses the default heuristic to determine the placement of the comment. /// /// # End of line comments /// /// Makes the comment a... /// /// * [trailing comment] of the [`preceding_node`] if both the [`following_node`] and [`preceding_node`] are not [None] /// and the comment and [`preceding_node`] are only separated by a space (there's no token between the comment and [`preceding_node`]). /// * [leading comment] of the [`following_node`] if the [`following_node`] is not [None] /// * [trailing comment] of the [`preceding_node`] if the [`preceding_node`] is not [None] /// * [dangling comment] of the [`enclosing_node`]. /// /// ## Examples /// ### Comment with preceding and following nodes /// /// ```python /// [ /// a, # comment /// b /// ] /// ``` /// /// The comment becomes a [trailing comment] of the node `a`. /// /// ### Comment with preceding node only /// /// ```python /// [ /// a # comment /// ] /// ``` /// /// The comment becomes a [trailing comment] of the node `a`. /// /// ### Comment with following node only /// /// ```python /// [ # comment /// b /// ] /// ``` /// /// The comment becomes a [leading comment] of the node `b`. /// /// ### Dangling comment /// /// ```python /// [ # comment /// ] /// ``` /// /// The comment becomes a [dangling comment] of the enclosing list expression because both the [`preceding_node`] and [`following_node`] are [None]. /// /// # Own line comments /// /// Makes the comment a... /// /// * [leading comment] of the [`following_node`] if the [`following_node`] is not [None] /// * or a [trailing comment] of the [`preceding_node`] if the [`preceding_node`] is not [None] /// * or a [dangling comment] of the [`enclosing_node`]. /// /// ## Examples /// /// ### Comment with leading and preceding nodes /// /// ```python /// [ /// a, /// # comment /// b /// ] /// ``` /// /// The comment becomes a [leading comment] of the node `b`. /// /// ### Comment with preceding node only /// /// ```python /// [ /// a /// # comment /// ] /// ``` /// /// The comment becomes a [trailing comment] of the node `a`. /// /// ### Comment with following node only /// /// ```python /// [ /// # comment /// b /// ] /// ``` /// /// The comment becomes a [leading comment] of the node `b`. /// /// ### Dangling comment /// /// ```python /// [ /// # comment /// ] /// ``` /// /// The comment becomes a [dangling comment] of the list expression because both [`preceding_node`] and [`following_node`] are [None]. /// /// [`preceding_node`]: DecoratedComment::preceding_node /// [`following_node`]: DecoratedComment::following_node /// [`enclosing_node`]: DecoratedComment::enclosing_node /// [trailing comment]: self#trailing-comments /// [leading comment]: self#leading-comments /// [dangling comment]: self#dangling-comments Default(DecoratedComment<'a>), } impl<'a> CommentPlacement<'a> { /// Makes `comment` a [leading comment](self#leading-comments) of `node`. #[inline] pub(super) fn leading(node: impl Into<AnyNodeRef<'a>>, comment: DecoratedComment) -> Self { Self::Leading { node: node.into(), comment: comment.into(), } } /// Makes `comment` a [dangling comment](self::dangling-comments) of `node`. pub(super) fn dangling(node: impl Into<AnyNodeRef<'a>>, comment: DecoratedComment) -> Self { Self::Dangling { node: node.into(), comment: comment.into(), } } /// Makes `comment` a [trailing comment](self::trailing-comments) of `node`. #[inline] pub(super) fn trailing(node: impl Into<AnyNodeRef<'a>>, comment: DecoratedComment) -> Self { Self::Trailing { node: node.into(), comment: comment.into(), } } /// Chains the placement with the given function. /// /// Returns `self` when the placement is non-[`CommentPlacement::Default`]. Otherwise, calls the /// function with the comment and returns the result. pub(super) fn or_else<F: FnOnce(DecoratedComment<'a>) -> Self>(self, f: F) -> Self { match self { Self::Default(comment) => f(comment), _ => self, } } } pub(super) trait PushComment<'a> { fn push_comment(&mut self, placement: DecoratedComment<'a>); } /// A storage for the [`CommentsVisitor`] that just pushes the decorated comments to a [`Vec`] for /// debugging purposes. #[derive(Debug, Default)] struct CommentsVecBuilder<'a> { comments: Vec<DecoratedComment<'a>>, } impl<'a> PushComment<'a> for CommentsVecBuilder<'a> { fn push_comment(&mut self, placement: DecoratedComment<'a>) { self.comments.push(placement); } } /// A storage for the [`CommentsVisitor`] that fixes the placement and stores the comments in a /// [`CommentsMap`]. pub(super) struct CommentsMapBuilder<'a> { comments: CommentsMap<'a>, /// We need those for backwards lexing comment_ranges: &'a CommentRanges, source: &'a str, } impl<'a> PushComment<'a> for CommentsMapBuilder<'a> { fn push_comment(&mut self, placement: DecoratedComment<'a>) { let placement = place_comment(placement, self.comment_ranges, self.source); match placement { CommentPlacement::Leading { node, comment } => { self.push_leading_comment(node, comment); } CommentPlacement::Trailing { node, comment } => { self.push_trailing_comment(node, comment); } CommentPlacement::Dangling { node, comment } => { self.push_dangling_comment(node, comment); } CommentPlacement::Default(comment) => { match comment.line_position() { CommentLinePosition::EndOfLine => { match (comment.preceding_node(), comment.following_node()) { (Some(preceding), Some(_)) => { // Attach comments with both preceding and following node to the preceding // because there's a line break separating it from the following node. // ```python // a; # comment // b // ``` self.push_trailing_comment(preceding, comment); } (Some(preceding), None) => { self.push_trailing_comment(preceding, comment); } (None, Some(following)) => { self.push_leading_comment(following, comment); } (None, None) => { self.push_dangling_comment(comment.enclosing_node(), comment); } } } CommentLinePosition::OwnLine => { match (comment.preceding_node(), comment.following_node()) { // Following always wins for a leading comment // ```python // a // // python // b // ``` // attach the comment to the `b` expression statement (_, Some(following)) => { self.push_leading_comment(following, comment); } (Some(preceding), None) => { self.push_trailing_comment(preceding, comment); } (None, None) => { self.push_dangling_comment(comment.enclosing_node(), comment); } } } } } } } } impl<'a> CommentsMapBuilder<'a> { pub(crate) fn new(source: &'a str, comment_ranges: &'a CommentRanges) -> Self { Self { comments: CommentsMap::default(), comment_ranges, source, } } pub(crate) fn finish(self) -> CommentsMap<'a> { self.comments } fn push_leading_comment(&mut self, node: AnyNodeRef<'a>, comment: impl Into<SourceComment>) { self.comments .push_leading(NodeRefEqualityKey::from_ref(node), comment.into()); } fn push_dangling_comment(&mut self, node: AnyNodeRef<'a>, comment: impl Into<SourceComment>) { self.comments .push_dangling(NodeRefEqualityKey::from_ref(node), comment.into()); } fn push_trailing_comment(&mut self, node: AnyNodeRef<'a>, comment: impl Into<SourceComment>) { self.comments .push_trailing(NodeRefEqualityKey::from_ref(node), comment.into()); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/comments/debug.rs
crates/ruff_python_formatter/src/comments/debug.rs
use std::fmt::{Debug, Formatter, Write}; use itertools::Itertools; use ruff_formatter::SourceCode; use ruff_text_size::Ranged; use crate::comments::node_key::NodeRefEqualityKey; use crate::comments::{CommentsMap, SourceComment}; /// Prints a debug representation of [`SourceComment`] that includes the comment's text pub(crate) struct DebugComment<'a> { comment: &'a SourceComment, source_code: SourceCode<'a>, } impl<'a> DebugComment<'a> { pub(super) fn new(comment: &'a SourceComment, source_code: SourceCode<'a>) -> Self { Self { comment, source_code, } } } impl Debug for DebugComment<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut strut = f.debug_struct("SourceComment"); strut .field("text", &self.comment.slice.text(self.source_code)) .field("position", &self.comment.line_position) .field("formatted", &self.comment.formatted.get()); strut.finish() } } /// Pretty-printed debug representation of [`Comments`](super::Comments). pub(crate) struct DebugComments<'a> { comments: &'a CommentsMap<'a>, source_code: SourceCode<'a>, } impl<'a> DebugComments<'a> { pub(super) fn new(comments: &'a CommentsMap, source_code: SourceCode<'a>) -> Self { Self { comments, source_code, } } } impl Debug for DebugComments<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut map = f.debug_map(); for node in self .comments .keys() .sorted_by_key(|key| (key.node().start(), key.node().end())) { map.entry( &NodeKindWithSource { key: *node, source: self.source_code, }, &DebugNodeComments { comments: self.comments, source_code: self.source_code, key: *node, }, ); } map.finish() } } /// Prints the source code up to the first new line character. Truncates the text if it exceeds 40 characters. struct NodeKindWithSource<'a> { key: NodeRefEqualityKey<'a>, source: SourceCode<'a>, } impl Debug for NodeKindWithSource<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { struct TruncatedSource<'a>(&'a str); impl Debug for TruncatedSource<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_char('`')?; let first_line = if let Some(line_end_pos) = self.0.find(['\n', '\r']) { &self.0[..line_end_pos] } else { self.0 }; if first_line.len() > 40 { let (head, rest) = first_line.split_at(27); f.write_str(head)?; f.write_str("...")?; // Take the last 10 characters let tail = &rest[rest.len().saturating_sub(10)..]; f.write_str(tail)?; } else { f.write_str(first_line)?; } if first_line.len() < self.0.len() { f.write_str("\u{23ce}")?; } f.write_char('`') } } let kind = self.key.node().kind(); let source = self.source.slice(self.key.node().range()).text(self.source); f.debug_struct("Node") .field("kind", &kind) .field("range", &self.key.node().range()) .field("source", &TruncatedSource(source)) .finish() } } struct DebugNodeComments<'a> { comments: &'a CommentsMap<'a>, source_code: SourceCode<'a>, key: NodeRefEqualityKey<'a>, } impl Debug for DebugNodeComments<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_map() .entry( &"leading", &DebugNodeCommentSlice { node_comments: self.comments.leading(&self.key), source_code: self.source_code, }, ) .entry( &"dangling", &DebugNodeCommentSlice { node_comments: self.comments.dangling(&self.key), source_code: self.source_code, }, ) .entry( &"trailing", &DebugNodeCommentSlice { node_comments: self.comments.trailing(&self.key), source_code: self.source_code, }, ) .finish() } } struct DebugNodeCommentSlice<'a> { node_comments: &'a [SourceComment], source_code: SourceCode<'a>, } impl Debug for DebugNodeCommentSlice<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut list = f.debug_list(); for comment in self.node_comments { list.entry(&comment.debug(self.source_code)); } list.finish() } } #[cfg(test)] mod tests { use insta::assert_debug_snapshot; use ruff_formatter::SourceCode; use ruff_python_ast::{AnyNodeRef, AtomicNodeIndex}; use ruff_python_ast::{StmtBreak, StmtContinue}; use ruff_python_trivia::{CommentLinePosition, CommentRanges}; use ruff_text_size::{TextRange, TextSize}; use crate::comments::map::MultiMap; use crate::comments::{Comments, CommentsMap, SourceComment}; #[test] fn debug() { let continue_statement = StmtContinue { range: TextRange::new(TextSize::new(18), TextSize::new(26)), node_index: AtomicNodeIndex::NONE, }; let break_statement = StmtBreak { range: TextRange::new(TextSize::new(55), TextSize::new(60)), node_index: AtomicNodeIndex::NONE, }; let source = r"# leading comment continue; # trailing # break leading break; "; let source_code = SourceCode::new(source); let mut comments_map: CommentsMap = MultiMap::new(); comments_map.push_leading( AnyNodeRef::from(&continue_statement).into(), SourceComment::new( source_code.slice(TextRange::at(TextSize::new(0), TextSize::new(17))), CommentLinePosition::OwnLine, ), ); comments_map.push_trailing( AnyNodeRef::from(&continue_statement).into(), SourceComment::new( source_code.slice(TextRange::at(TextSize::new(28), TextSize::new(10))), CommentLinePosition::EndOfLine, ), ); comments_map.push_leading( AnyNodeRef::from(&break_statement).into(), SourceComment::new( source_code.slice(TextRange::at(TextSize::new(39), TextSize::new(15))), CommentLinePosition::OwnLine, ), ); let comment_ranges = CommentRanges::default(); let comments = Comments::new(comments_map, &comment_ranges); assert_debug_snapshot!(comments.debug(source_code)); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/comments/map.rs
crates/ruff_python_formatter/src/comments/map.rs
use countme::Count; use rustc_hash::FxHashMap; use std::fmt::{Debug, Formatter}; use std::iter::FusedIterator; use std::num::NonZeroU32; use std::ops::Range; /// An optimized multi-map implementation for storing *leading*, *dangling*, and *trailing* parts for a key. /// The inserted parts are stored in insertion-order. /// /// A naive implementation using three multimaps, one to store the *leading*, another for the *dangling* parts, /// and a third for the *trailing* parts, requires between `keys < allocations < keys * 3` vec allocations. /// /// This map implementation optimises for the use case where: /// * Parts belonging to the same key are inserted together. For example, all parts for the key `a` are inserted /// before inserting any parts for the key `b`. /// * The parts per key are inserted in the following order: *leading*, *dangling*, and then the *trailing* parts. /// /// Parts inserted in the above-mentioned order are stored in a `Vec` shared by all keys to reduce the number /// of allocations and increased cache locality. The implementation falls back to storing the *leading*, /// *dangling*, and *trailing* parts of a key in dedicated `Vec`s if the parts aren't inserted in the before mentioned order. /// Out of order insertions come with a slight performance penalty due to: /// * It requiring up to three [Vec] allocations, one for the *leading*, *dangling*, and *trailing* parts. /// * It requires copying already inserted parts for that key (by cloning) into the newly allocated [Vec]s. /// * The resolving of each part for that key requires an extra level of indirection. /// /// ## Limitations /// The map supports storing up to `u32::MAX - 1` parts. Inserting the `u32::MAX`nth part panics. /// /// ## Comments /// /// Storing the *leading*, *dangling*, and *trailing* comments is an exemplary use case for this map implementation because /// it is generally desired to keep the comments in the same order as they appear in the source document. /// This translates to inserting the comments per node and for every node in 1) *leading*, 2) *dangling*, 3) *trailing* order (the order this map optimises for). /// /// Running Rome's formatter on real world use cases showed that more than 99.99% of comments get inserted in /// the described order. /// /// The size limitation isn't a concern for comments because Ruff supports source documents with a size up to 4GB (`u32::MAX`) /// and every comment has at least a size of 2 bytes: /// * 1 byte for the start sequence, e.g. `#` /// * 1 byte for the end sequence, e.g. `\n` /// /// Meaning, the upper bound for comments is `u32::MAX / 2`. #[derive(Clone)] pub(super) struct MultiMap<K, V> { /// Lookup table to retrieve the entry for a key. index: FxHashMap<K, Entry>, /// Flat array storing all the parts that have been inserted in order. parts: Vec<V>, /// Vector containing the *leading*, *dangling*, and *trailing* vectors for out of order entries. /// /// The length of `out_of_order` is a multiple of 3 where: /// * `index % 3 == 0`: *Leading* parts /// * `index % 3 == 1`: *Dangling* parts /// * `index % 3 == 2`: *Trailing* parts out_of_order_parts: Vec<Vec<V>>, } impl<K: std::hash::Hash + Eq, V> MultiMap<K, V> { pub(super) fn new() -> Self { Self { index: FxHashMap::default(), parts: Vec::new(), out_of_order_parts: Vec::new(), } } /// Pushes a *leading* part for `key`. pub(super) fn push_leading(&mut self, key: K, part: V) where V: Clone, { match self.index.get_mut(&key) { None => { let start = self.parts.len(); self.parts.push(part); self.index.insert( key, Entry::InOrder(InOrderEntry::leading(start..self.parts.len())), ); } // Has only *leading* parts and no elements have been pushed since Some(Entry::InOrder(entry)) if entry.trailing_start.is_none() && self.parts.len() == entry.range().end => { self.parts.push(part); entry.increment_leading_range(); } Some(Entry::OutOfOrder(entry)) => { let leading = &mut self.out_of_order_parts[entry.leading_index()]; leading.push(part); } Some(entry) => { let out_of_order = Self::entry_to_out_of_order(entry, &self.parts, &mut self.out_of_order_parts); self.out_of_order_parts[out_of_order.leading_index()].push(part); } } } /// Pushes a *dangling* part for `key` pub(super) fn push_dangling(&mut self, key: K, part: V) where V: Clone, { match self.index.get_mut(&key) { None => { let start = self.parts.len(); self.parts.push(part); self.index.insert( key, Entry::InOrder(InOrderEntry::dangling(start..self.parts.len())), ); } // Has leading and dangling comments and no new parts have been inserted since. Some(Entry::InOrder(entry)) if entry.trailing_end.is_none() && self.parts.len() == entry.range().end => { self.parts.push(part); entry.increment_dangling_range(); } Some(Entry::OutOfOrder(entry)) => { let dangling = &mut self.out_of_order_parts[entry.dangling_index()]; dangling.push(part); } Some(entry) => { let out_of_order = Self::entry_to_out_of_order(entry, &self.parts, &mut self.out_of_order_parts); self.out_of_order_parts[out_of_order.dangling_index()].push(part); } } } /// Pushes a *trailing* part for `key`. pub(super) fn push_trailing(&mut self, key: K, part: V) where V: Clone, { match self.index.get_mut(&key) { None => { let start = self.parts.len(); self.parts.push(part); self.index.insert( key, Entry::InOrder(InOrderEntry::trailing(start..self.parts.len())), ); } // No new parts have been inserted since Some(Entry::InOrder(entry)) if entry.range().end == self.parts.len() => { self.parts.push(part); entry.increment_trailing_range(); } Some(Entry::OutOfOrder(entry)) => { let trailing = &mut self.out_of_order_parts[entry.trailing_index()]; trailing.push(part); } Some(entry) => { let out_of_order = Self::entry_to_out_of_order(entry, &self.parts, &mut self.out_of_order_parts); self.out_of_order_parts[out_of_order.trailing_index()].push(part); } } } /// Slow path for converting an in-order entry to an out-of order entry. /// Copies over all parts into the `out_of_order` vec. #[cold] fn entry_to_out_of_order<'a>( entry: &'a mut Entry, parts: &[V], out_of_order: &mut Vec<Vec<V>>, ) -> &'a mut OutOfOrderEntry where V: Clone, { match entry { Entry::InOrder(in_order) => { let index = out_of_order.len(); out_of_order.push(parts[in_order.leading_range()].to_vec()); out_of_order.push(parts[in_order.dangling_range()].to_vec()); out_of_order.push(parts[in_order.trailing_range()].to_vec()); *entry = Entry::OutOfOrder(OutOfOrderEntry { leading_index: index, _count: Count::new(), }); match entry { Entry::InOrder(_) => unreachable!(), Entry::OutOfOrder(out_of_order) => out_of_order, } } Entry::OutOfOrder(entry) => entry, } } pub(super) fn keys(&self) -> Keys<'_, K> { Keys { inner: self.index.keys(), } } /// Returns the *leading* parts of `key` in insertion-order. pub(super) fn leading(&self, key: &K) -> &[V] { match self.index.get(key) { None => &[], Some(Entry::InOrder(in_order)) => &self.parts[in_order.leading_range()], Some(Entry::OutOfOrder(entry)) => &self.out_of_order_parts[entry.leading_index()], } } /// Returns the *dangling* parts of `key` in insertion-order. pub(super) fn dangling(&self, key: &K) -> &[V] { match self.index.get(key) { None => &[], Some(Entry::InOrder(in_order)) => &self.parts[in_order.dangling_range()], Some(Entry::OutOfOrder(entry)) => &self.out_of_order_parts[entry.dangling_index()], } } /// Returns the *trailing* parts of `key` in insertion order. pub(super) fn trailing(&self, key: &K) -> &[V] { match self.index.get(key) { None => &[], Some(Entry::InOrder(in_order)) => &self.parts[in_order.trailing_range()], Some(Entry::OutOfOrder(entry)) => &self.out_of_order_parts[entry.trailing_index()], } } /// Returns `true` if `key` has any *leading*, *dangling*, or *trailing* parts. pub(super) fn has(&self, key: &K) -> bool { self.index.contains_key(key) } /// Returns the *leading*, *dangling*, and *trailing* parts of `key`. pub(super) fn leading_dangling_trailing(&self, key: &K) -> LeadingDanglingTrailing<'_, V> { match self.index.get(key) { None => LeadingDanglingTrailing { leading: &[], dangling: &[], trailing: &[], }, Some(Entry::InOrder(entry)) => LeadingDanglingTrailing { leading: &self.parts[entry.leading_range()], dangling: &self.parts[entry.dangling_range()], trailing: &self.parts[entry.trailing_range()], }, Some(Entry::OutOfOrder(entry)) => LeadingDanglingTrailing { leading: &self.out_of_order_parts[entry.leading_index()], dangling: &self.out_of_order_parts[entry.dangling_index()], trailing: &self.out_of_order_parts[entry.trailing_index()], }, } } /// Returns an iterator over the parts of all keys. #[allow(unused)] pub(super) fn all_parts(&self) -> impl Iterator<Item = &V> { self.index .values() .flat_map(|entry| LeadingDanglingTrailing::from_entry(entry, self)) } } impl<K: std::hash::Hash + Eq, V> Default for MultiMap<K, V> { fn default() -> Self { Self::new() } } impl<K, V> Debug for MultiMap<K, V> where K: Debug, V: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut builder = f.debug_map(); for (key, entry) in &self.index { builder.entry(&key, &LeadingDanglingTrailing::from_entry(entry, self)); } builder.finish() } } #[derive(Clone)] pub(crate) struct LeadingDanglingTrailing<'a, T> { pub(crate) leading: &'a [T], pub(crate) dangling: &'a [T], pub(crate) trailing: &'a [T], } impl<'a, T> LeadingDanglingTrailing<'a, T> { fn from_entry<K>(entry: &Entry, map: &'a MultiMap<K, T>) -> Self { match entry { Entry::InOrder(entry) => LeadingDanglingTrailing { leading: &map.parts[entry.leading_range()], dangling: &map.parts[entry.dangling_range()], trailing: &map.parts[entry.trailing_range()], }, Entry::OutOfOrder(entry) => LeadingDanglingTrailing { leading: &map.out_of_order_parts[entry.leading_index()], dangling: &map.out_of_order_parts[entry.dangling_index()], trailing: &map.out_of_order_parts[entry.trailing_index()], }, } } } impl<'a, T> IntoIterator for LeadingDanglingTrailing<'a, T> { type Item = &'a T; type IntoIter = std::iter::Chain< std::iter::Chain<std::slice::Iter<'a, T>, std::slice::Iter<'a, T>>, std::slice::Iter<'a, T>, >; fn into_iter(self) -> Self::IntoIter { self.leading .iter() .chain(self.dangling) .chain(self.trailing) } } impl<T> Debug for LeadingDanglingTrailing<'_, T> where T: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut list = f.debug_list(); list.entries(self.leading.iter().map(DebugValue::Leading)); list.entries(self.dangling.iter().map(DebugValue::Dangling)); list.entries(self.trailing.iter().map(DebugValue::Trailing)); list.finish() } } #[derive(Clone, Debug)] enum Entry { InOrder(InOrderEntry), OutOfOrder(OutOfOrderEntry), } enum DebugValue<'a, V> { Leading(&'a V), Dangling(&'a V), Trailing(&'a V), } impl<V> Debug for DebugValue<'_, V> where V: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { DebugValue::Leading(leading) => f.debug_tuple("Leading").field(leading).finish(), DebugValue::Dangling(dangling) => f.debug_tuple("Dangling").field(dangling).finish(), DebugValue::Trailing(trailing) => f.debug_tuple("Trailing").field(trailing).finish(), } } } #[derive(Clone, Debug)] struct InOrderEntry { /// Index into the [`MultiMap::parts`] vector where the leading parts of this entry start leading_start: PartIndex, /// Index into the [`MultiMap::parts`] vector where the dangling parts (and, thus, the leading parts end) start. dangling_start: PartIndex, /// Index into the [`MultiMap::parts`] vector where the trailing parts (and, thus, the dangling parts end) of this entry start trailing_start: Option<PartIndex>, /// Index into the [`MultiMap::parts`] vector where the trailing parts of this entry end trailing_end: Option<PartIndex>, _count: Count<InOrderEntry>, } impl InOrderEntry { fn leading(range: Range<usize>) -> Self { InOrderEntry { leading_start: PartIndex::from_len(range.start), dangling_start: PartIndex::from_len(range.end), trailing_start: None, trailing_end: None, _count: Count::new(), } } fn dangling(range: Range<usize>) -> Self { let start = PartIndex::from_len(range.start); InOrderEntry { leading_start: start, dangling_start: start, trailing_start: Some(PartIndex::from_len(range.end)), trailing_end: None, _count: Count::new(), } } fn trailing(range: Range<usize>) -> Self { let start = PartIndex::from_len(range.start); InOrderEntry { leading_start: start, dangling_start: start, trailing_start: Some(start), trailing_end: Some(PartIndex::from_len(range.end)), _count: Count::new(), } } fn increment_leading_range(&mut self) { assert!( self.trailing_start.is_none(), "Can't extend the leading range for an in order entry with dangling comments." ); self.dangling_start.increment(); } fn increment_dangling_range(&mut self) { assert!( self.trailing_end.is_none(), "Can't extend the dangling range for an in order entry with trailing comments." ); match &mut self.trailing_start { Some(start) => start.increment(), None => self.trailing_start = Some(self.dangling_start.incremented()), } } fn increment_trailing_range(&mut self) { match (self.trailing_start, &mut self.trailing_end) { // Already has some trailing comments (Some(_), Some(end)) => end.increment(), // Has dangling comments only (Some(start), None) => self.trailing_end = Some(start.incremented()), // Has leading comments only (None, None) => { self.trailing_start = Some(self.dangling_start); self.trailing_end = Some(self.dangling_start.incremented()); } (None, Some(_)) => { unreachable!() } } } fn leading_range(&self) -> Range<usize> { self.leading_start.value()..self.dangling_start.value() } fn dangling_range(&self) -> Range<usize> { match self.trailing_start { None => self.dangling_start.value()..self.dangling_start.value(), Some(trailing_start) => self.dangling_start.value()..trailing_start.value(), } } fn trailing_range(&self) -> Range<usize> { match (self.trailing_start, self.trailing_end) { (Some(trailing_start), Some(trailing_end)) => { trailing_start.value()..trailing_end.value() } // Only dangling comments (Some(trailing_start), None) => trailing_start.value()..trailing_start.value(), (None, Some(_)) => { panic!("Trailing end shouldn't be set if trailing start is none"); } (None, None) => self.dangling_start.value()..self.dangling_start.value(), } } fn range(&self) -> Range<usize> { self.leading_start.value() ..self .trailing_end .or(self.trailing_start) .unwrap_or(self.dangling_start) .value() } } #[derive(Clone, Debug)] struct OutOfOrderEntry { /// Index into the [`MultiMap::out_of_order_parts`] vector at which offset the leading vec is stored. leading_index: usize, _count: Count<OutOfOrderEntry>, } impl OutOfOrderEntry { const fn leading_index(&self) -> usize { self.leading_index } const fn dangling_index(&self) -> usize { self.leading_index + 1 } const fn trailing_index(&self) -> usize { self.leading_index + 2 } } /// Index into the [`MultiMap::parts`] vector. /// /// Stores the index as a [`NonZeroU32`], starting at 1 instead of 0 so that /// `size_of::<PartIndex>() == size_of::<Option<PartIndex>>()`. /// /// This means, that only `u32 - 1` parts can be stored. This should be sufficient for storing comments /// because: Comments have length of two or more bytes because they consist of a start and end character sequence (`#` + new line, `/*` and `*/`). /// Thus, a document with length `u32` can have at most `u32::MAX / 2` comment-parts. #[repr(transparent)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] struct PartIndex(NonZeroU32); impl PartIndex { fn from_len(value: usize) -> Self { assert!(value < u32::MAX as usize); // OK because: // * The `value < u32::MAX` guarantees that the add doesn't overflow. // * The `+ 1` guarantees that the index is not zero #[expect(clippy::cast_possible_truncation)] Self(std::num::NonZeroU32::new((value as u32) + 1).expect("valid value")) } fn value(self) -> usize { (u32::from(self.0) - 1) as usize } fn increment(&mut self) { *self = self.incremented(); } fn incremented(self) -> PartIndex { PartIndex(NonZeroU32::new(self.0.get() + 1).unwrap()) } } /// Iterator over the keys of a comments multi map pub(super) struct Keys<'a, K> { inner: std::collections::hash_map::Keys<'a, K, Entry>, } impl<'a, K> Iterator for Keys<'a, K> { type Item = &'a K; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } impl<K> ExactSizeIterator for Keys<'_, K> {} impl<K> FusedIterator for Keys<'_, K> {} #[cfg(test)] mod tests { use crate::comments::map::MultiMap; static EMPTY: [i32; 0] = []; #[test] fn leading_dangling_trailing() { let mut map = MultiMap::new(); map.push_leading("a", 1); map.push_dangling("a", 2); map.push_dangling("a", 3); map.push_trailing("a", 4); assert_eq!(map.parts, vec![1, 2, 3, 4]); assert_eq!(map.leading(&"a"), &[1]); assert_eq!(map.dangling(&"a"), &[2, 3]); assert_eq!(map.trailing(&"a"), &[4]); assert!(map.has(&"a")); assert_eq!( map.leading_dangling_trailing(&"a") .into_iter() .copied() .collect::<Vec<_>>(), vec![1, 2, 3, 4] ); } #[test] fn dangling_trailing() { let mut map = MultiMap::new(); map.push_dangling("a", 1); map.push_dangling("a", 2); map.push_trailing("a", 3); assert_eq!(map.parts, vec![1, 2, 3]); assert_eq!(map.leading(&"a"), &EMPTY); assert_eq!(map.dangling(&"a"), &[1, 2]); assert_eq!(map.trailing(&"a"), &[3]); assert!(map.has(&"a")); assert_eq!( map.leading_dangling_trailing(&"a") .into_iter() .copied() .collect::<Vec<_>>(), vec![1, 2, 3] ); } #[test] fn trailing() { let mut map = MultiMap::new(); map.push_trailing("a", 1); map.push_trailing("a", 2); assert_eq!(map.parts, vec![1, 2]); assert_eq!(map.leading(&"a"), &EMPTY); assert_eq!(map.dangling(&"a"), &EMPTY); assert_eq!(map.trailing(&"a"), &[1, 2]); assert!(map.has(&"a")); assert_eq!( map.leading_dangling_trailing(&"a") .into_iter() .copied() .collect::<Vec<_>>(), vec![1, 2] ); } #[test] fn empty() { let map = MultiMap::<&str, i32>::default(); assert_eq!(map.parts, Vec::<i32>::new()); assert_eq!(map.leading(&"a"), &EMPTY); assert_eq!(map.dangling(&"a"), &EMPTY); assert_eq!(map.trailing(&"a"), &EMPTY); assert!(!map.has(&"a")); assert_eq!( map.leading_dangling_trailing(&"a") .into_iter() .copied() .collect::<Vec<_>>(), Vec::<i32>::new() ); } #[test] fn multiple_keys() { let mut map = MultiMap::new(); map.push_leading("a", 1); map.push_dangling("b", 2); map.push_trailing("c", 3); map.push_leading("d", 4); map.push_dangling("d", 5); map.push_trailing("d", 6); assert_eq!(map.parts, &[1, 2, 3, 4, 5, 6]); assert_eq!(map.leading(&"a"), &[1]); assert_eq!(map.dangling(&"a"), &EMPTY); assert_eq!(map.trailing(&"a"), &EMPTY); assert_eq!( map.leading_dangling_trailing(&"a") .into_iter() .copied() .collect::<Vec<_>>(), vec![1] ); assert_eq!(map.leading(&"b"), &EMPTY); assert_eq!(map.dangling(&"b"), &[2]); assert_eq!(map.trailing(&"b"), &EMPTY); assert_eq!( map.leading_dangling_trailing(&"b") .into_iter() .copied() .collect::<Vec<_>>(), vec![2] ); assert_eq!(map.leading(&"c"), &EMPTY); assert_eq!(map.dangling(&"c"), &EMPTY); assert_eq!(map.trailing(&"c"), &[3]); assert_eq!( map.leading_dangling_trailing(&"c") .into_iter() .copied() .collect::<Vec<_>>(), vec![3] ); assert_eq!(map.leading(&"d"), &[4]); assert_eq!(map.dangling(&"d"), &[5]); assert_eq!(map.trailing(&"d"), &[6]); assert_eq!( map.leading_dangling_trailing(&"d") .into_iter() .copied() .collect::<Vec<_>>(), vec![4, 5, 6] ); } #[test] fn dangling_leading() { let mut map = MultiMap::new(); map.push_dangling("a", 1); map.push_leading("a", 2); map.push_dangling("a", 3); map.push_trailing("a", 4); assert_eq!(map.leading(&"a"), [2]); assert_eq!(map.dangling(&"a"), [1, 3]); assert_eq!(map.trailing(&"a"), [4]); assert_eq!( map.leading_dangling_trailing(&"a") .into_iter() .copied() .collect::<Vec<_>>(), vec![2, 1, 3, 4] ); assert!(map.has(&"a")); } #[test] fn trailing_leading() { let mut map = MultiMap::new(); map.push_trailing("a", 1); map.push_leading("a", 2); map.push_dangling("a", 3); map.push_trailing("a", 4); assert_eq!(map.leading(&"a"), [2]); assert_eq!(map.dangling(&"a"), [3]); assert_eq!(map.trailing(&"a"), [1, 4]); assert_eq!( map.leading_dangling_trailing(&"a") .into_iter() .copied() .collect::<Vec<_>>(), vec![2, 3, 1, 4] ); assert!(map.has(&"a")); } #[test] fn trailing_dangling() { let mut map = MultiMap::new(); map.push_trailing("a", 1); map.push_dangling("a", 2); map.push_trailing("a", 3); assert_eq!(map.leading(&"a"), &EMPTY); assert_eq!(map.dangling(&"a"), &[2]); assert_eq!(map.trailing(&"a"), &[1, 3]); assert_eq!( map.leading_dangling_trailing(&"a") .into_iter() .copied() .collect::<Vec<_>>(), vec![2, 1, 3] ); assert!(map.has(&"a")); } #[test] fn keys_out_of_order() { let mut map = MultiMap::new(); map.push_leading("a", 1); map.push_dangling("b", 2); map.push_leading("a", 3); map.push_trailing("c", 4); map.push_dangling("b", 5); map.push_leading("d", 6); map.push_trailing("c", 7); assert_eq!(map.leading(&"a"), &[1, 3]); assert_eq!(map.dangling(&"b"), &[2, 5]); assert_eq!(map.trailing(&"c"), &[4, 7]); assert!(map.has(&"a")); assert!(map.has(&"b")); assert!(map.has(&"c")); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/comments/placement.rs
crates/ruff_python_formatter/src/comments/placement.rs
use ast::helpers::comment_indentation_after; use ruff_python_ast::whitespace::indentation; use ruff_python_ast::{ self as ast, AnyNodeRef, Comprehension, Expr, ModModule, Parameter, Parameters, StringLike, }; use ruff_python_trivia::{ BackwardsTokenizer, CommentRanges, SimpleToken, SimpleTokenKind, SimpleTokenizer, find_only_token_in_range, first_non_trivia_token, indentation_at_offset, }; use ruff_source_file::LineRanges; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use std::cmp::Ordering; use crate::comments::visitor::{CommentPlacement, DecoratedComment}; use crate::expression::expr_slice::{ExprSliceCommentSection, assign_comment_in_slice}; use crate::expression::parentheses::is_expression_parenthesized; use crate::other::parameters::{ assign_argument_separator_comment_placement, find_parameter_separators, }; use crate::pattern::pattern_match_sequence::SequenceType; /// Manually attach comments to nodes that the default placement gets wrong. pub(super) fn place_comment<'a>( comment: DecoratedComment<'a>, comment_ranges: &CommentRanges, source: &str, ) -> CommentPlacement<'a> { handle_parenthesized_comment(comment, source) .or_else(|comment| handle_end_of_line_comment_around_body(comment, source)) .or_else(|comment| handle_own_line_comment_around_body(comment, source)) .or_else(|comment| handle_enclosed_comment(comment, comment_ranges, source)) } /// Handle parenthesized comments. A parenthesized comment is a comment that appears within a /// parenthesis, but not within the range of the expression enclosed by the parenthesis. /// For example, the comment here is a parenthesized comment: /// ```python /// if ( /// # comment /// True /// ): /// ... /// ``` /// The parentheses enclose `True`, but the range of `True` doesn't include the `# comment`. /// /// Default handling can get parenthesized comments wrong in a number of ways. For example, the /// comment here is marked (by default) as a trailing comment of `x`, when it should be a leading /// comment of `y`: /// ```python /// assert ( /// x /// ), ( # comment /// y /// ) /// ``` /// /// Similarly, this is marked as a leading comment of `y`, when it should be a trailing comment of /// `x`: /// ```python /// if ( /// x /// # comment /// ): /// y /// ``` /// /// As a generalized solution, if a comment has a preceding node and a following node, we search for /// opening and closing parentheses between the two nodes. If we find a closing parenthesis between /// the preceding node and the comment, then the comment is a trailing comment of the preceding /// node. If we find an opening parenthesis between the comment and the following node, then the /// comment is a leading comment of the following node. fn handle_parenthesized_comment<'a>( comment: DecoratedComment<'a>, source: &str, ) -> CommentPlacement<'a> { // As a special-case, ignore comments within f-strings, like: // ```python // ( // f'{1}' # comment // f'{2}' // ) // ``` // These can't be parenthesized, as they must fall between two string tokens in an implicit // concatenation. But the expression ranges only include the `1` and `2` above, so we also // can't lex the contents between them. if comment.enclosing_node().is_expr_f_string() { return CommentPlacement::Default(comment); } let Some(preceding) = comment.preceding_node() else { return CommentPlacement::Default(comment); }; let Some(following) = comment.following_node() else { return CommentPlacement::Default(comment); }; // TODO(charlie): Assert that there are no bogus tokens in these ranges. There are a few cases // where we _can_ hit bogus tokens, but the parentheses need to come before them. For example: // ```python // try: // some_call() // except ( // UnformattedError // # trailing comment // ) as err: // handle_exception() // ``` // Here, we lex from the end of `UnformattedError` to the start of `handle_exception()`, which // means we hit an "other" token at `err`. We know the parentheses must precede the `err`, but // this could be fixed by including `as err` in the node range. // // Another example: // ```python // @deco // # comment // def decorated(): // pass // ``` // Here, we lex from the end of `deco` to the start of the arguments of `decorated`. We hit an // "other" token at `decorated`, but any parentheses must precede that. // // For now, we _can_ assert, but to do so, we stop lexing when we hit a token that precedes an // identifier. // Search for comments that to the right of a parenthesized node, e.g.: // ```python // [ // x # comment, // ( // y, // ), // ] // ``` let range = TextRange::new(preceding.end(), comment.start()); let tokenizer = SimpleTokenizer::new(source, range); if tokenizer .skip_trivia() .take_while(|token| { !matches!( token.kind, SimpleTokenKind::As | SimpleTokenKind::Def | SimpleTokenKind::Class ) }) .any(|token| { debug_assert!( !matches!(token.kind, SimpleTokenKind::Bogus), "Unexpected token between nodes: `{:?}`", &source[range] ); token.kind() == SimpleTokenKind::LParen }) { return CommentPlacement::leading(following, comment); } // Search for comments that to the right of a parenthesized node, e.g.: // ```python // [ // ( // x # comment, // ), // y // ] // ``` let range = TextRange::new(comment.end(), following.start()); let tokenizer = SimpleTokenizer::new(source, range); if tokenizer .skip_trivia() .take_while(|token| { !matches!( token.kind, SimpleTokenKind::As | SimpleTokenKind::Def | SimpleTokenKind::Class ) }) .any(|token| { debug_assert!( !matches!(token.kind, SimpleTokenKind::Bogus), "Unexpected token between nodes: `{:?}`", &source[range] ); token.kind() == SimpleTokenKind::RParen }) { return CommentPlacement::trailing(preceding, comment); } CommentPlacement::Default(comment) } /// Handle a comment that is enclosed by a node. fn handle_enclosed_comment<'a>( comment: DecoratedComment<'a>, comment_ranges: &CommentRanges, source: &str, ) -> CommentPlacement<'a> { match comment.enclosing_node() { AnyNodeRef::Parameters(parameters) => { handle_parameters_separator_comment(comment, parameters, source).or_else(|comment| { if are_parameters_parenthesized(parameters, source) { handle_bracketed_end_of_line_comment(comment, source) } else { CommentPlacement::Default(comment) } }) } AnyNodeRef::Parameter(parameter) => handle_parameter_comment(comment, parameter, source), AnyNodeRef::Arguments(_) | AnyNodeRef::TypeParams(_) | AnyNodeRef::PatternArguments(_) => { handle_bracketed_end_of_line_comment(comment, source) } AnyNodeRef::Comprehension(comprehension) => { handle_comprehension_comment(comment, comprehension, source) } AnyNodeRef::ExprAttribute(attribute) => { handle_attribute_comment(comment, attribute, source) } AnyNodeRef::ExprBinOp(binary_expression) => { handle_trailing_binary_expression_left_or_operator_comment( comment, binary_expression, source, ) } AnyNodeRef::ExprBoolOp(_) | AnyNodeRef::ExprCompare(_) => { handle_trailing_binary_like_comment(comment, source) } AnyNodeRef::Keyword(keyword) => handle_keyword_comment(comment, keyword, source), AnyNodeRef::PatternKeyword(pattern_keyword) => { handle_pattern_keyword_comment(comment, pattern_keyword, source) } AnyNodeRef::ExprUnaryOp(unary_op) => handle_unary_op_comment(comment, unary_op, source), AnyNodeRef::ExprNamed(_) => handle_named_expr_comment(comment, source), AnyNodeRef::ExprLambda(lambda) => handle_lambda_comment(comment, lambda, source), AnyNodeRef::ExprDict(_) => handle_dict_unpacking_comment(comment, source) .or_else(|comment| handle_bracketed_end_of_line_comment(comment, source)) .or_else(|comment| handle_key_value_comment(comment, source)), AnyNodeRef::ExprDictComp(_) => handle_key_value_comment(comment, source) .or_else(|comment| handle_bracketed_end_of_line_comment(comment, source)), AnyNodeRef::ExprIf(expr_if) => handle_expr_if_comment(comment, expr_if, source), AnyNodeRef::ExprSlice(expr_slice) => { handle_slice_comments(comment, expr_slice, comment_ranges, source) } AnyNodeRef::ExprStarred(starred) => { handle_trailing_expression_starred_star_end_of_line_comment(comment, starred, source) } AnyNodeRef::ExprSubscript(expr_subscript) => { if let Expr::Slice(expr_slice) = expr_subscript.slice.as_ref() { return handle_slice_comments(comment, expr_slice, comment_ranges, source); } // Handle non-slice subscript end-of-line comments coming after the `[` // ```python // repro( // "some long string that takes up some space" // )[ # some long comment also taking up space // 0 // ] // ``` if comment.line_position().is_end_of_line() && expr_subscript.value.end() < comment.start() { // Ensure that there are no tokens between the open bracket and the comment. let mut lexer = SimpleTokenizer::new( source, TextRange::new(expr_subscript.value.end(), comment.start()), ) .skip_trivia(); // Skip to after the opening parenthesis (may skip some closing parentheses of value) if !lexer .by_ref() .any(|token| token.kind() == SimpleTokenKind::LBracket) { return CommentPlacement::Default(comment); } // If there are no additional tokens between the open parenthesis and the comment, then // it should be attached as a dangling comment on the brackets, rather than a leading // comment on the first argument. if lexer.next().is_none() { return CommentPlacement::dangling(expr_subscript, comment); } } CommentPlacement::Default(comment) } AnyNodeRef::ModModule(module) => { handle_trailing_module_comment(module, comment).or_else(|comment| { handle_module_level_own_line_comment_before_class_or_function_comment( comment, source, ) }) } AnyNodeRef::WithItem(_) => handle_with_item_comment(comment, source), AnyNodeRef::PatternMatchSequence(pattern_match_sequence) => { if SequenceType::from_pattern(pattern_match_sequence, source).is_parenthesized() { handle_bracketed_end_of_line_comment(comment, source) } else { CommentPlacement::Default(comment) } } AnyNodeRef::PatternMatchClass(class) => handle_pattern_match_class_comment(comment, class), AnyNodeRef::PatternMatchAs(_) => handle_pattern_match_as_comment(comment, source), AnyNodeRef::PatternMatchStar(_) => handle_pattern_match_star_comment(comment), AnyNodeRef::PatternMatchMapping(pattern) => { handle_bracketed_end_of_line_comment(comment, source) .or_else(|comment| handle_pattern_match_mapping_comment(comment, pattern, source)) } AnyNodeRef::StmtFunctionDef(_) => handle_leading_function_with_decorators_comment(comment), AnyNodeRef::StmtClassDef(class_def) => { handle_leading_class_with_decorators_comment(comment, class_def) } AnyNodeRef::StmtImportFrom(import_from) => { handle_import_from_comment(comment, import_from, source) } AnyNodeRef::Alias(alias) => handle_alias_comment(comment, alias, source), AnyNodeRef::StmtWith(with_) => handle_with_comment(comment, with_), AnyNodeRef::ExprCall(_) => handle_call_comment(comment), AnyNodeRef::ExprStringLiteral(_) => match comment.enclosing_parent() { Some(AnyNodeRef::FString(fstring)) => CommentPlacement::dangling(fstring, comment), Some(AnyNodeRef::TString(tstring)) => CommentPlacement::dangling(tstring, comment), _ => CommentPlacement::Default(comment), }, AnyNodeRef::FString(fstring) => CommentPlacement::dangling(fstring, comment), AnyNodeRef::TString(tstring) => CommentPlacement::dangling(tstring, comment), AnyNodeRef::InterpolatedElement(element) => { if let Some(preceding) = comment.preceding_node() { // Own line comment before format specifier // ```py // aaaaaaaaaaa = f"""asaaaaaaaaaaaaaaaa { // aaaaaaaaaaaa + bbbbbbbbbbbb + ccccccccccccccc + dddddddd // # comment // :.3f} cccccccccc""" // ``` if comment.line_position().is_own_line() && element.format_spec.is_some() && comment.following_node().is_some() { return CommentPlacement::trailing(preceding, comment); } } handle_bracketed_end_of_line_comment(comment, source) } AnyNodeRef::ExprList(_) | AnyNodeRef::ExprSet(_) | AnyNodeRef::ExprListComp(_) | AnyNodeRef::ExprSetComp(_) => handle_bracketed_end_of_line_comment(comment, source), AnyNodeRef::ExprTuple(ast::ExprTuple { parenthesized: true, .. }) => handle_bracketed_end_of_line_comment(comment, source), AnyNodeRef::ExprGenerator(generator) if generator.parenthesized => { handle_bracketed_end_of_line_comment(comment, source) } AnyNodeRef::StmtReturn(_) => { handle_trailing_implicit_concatenated_string_comment(comment, comment_ranges, source) } AnyNodeRef::StmtAssign(assignment) if comment.preceding_node().is_some_and(|preceding| { preceding.ptr_eq(AnyNodeRef::from(&*assignment.value)) }) => { handle_trailing_implicit_concatenated_string_comment(comment, comment_ranges, source) } AnyNodeRef::StmtAnnAssign(assignment) if comment.preceding_node().is_some_and(|preceding| { assignment .value .as_deref() .is_some_and(|value| preceding.ptr_eq(value.into())) }) => { handle_trailing_implicit_concatenated_string_comment(comment, comment_ranges, source) } AnyNodeRef::StmtAugAssign(assignment) if comment.preceding_node().is_some_and(|preceding| { preceding.ptr_eq(AnyNodeRef::from(&*assignment.value)) }) => { handle_trailing_implicit_concatenated_string_comment(comment, comment_ranges, source) } AnyNodeRef::StmtTypeAlias(assignment) if comment.preceding_node().is_some_and(|preceding| { preceding.ptr_eq(AnyNodeRef::from(&*assignment.value)) }) => { handle_trailing_implicit_concatenated_string_comment(comment, comment_ranges, source) } _ => CommentPlacement::Default(comment), } } /// Handle an end-of-line comment around a body. fn handle_end_of_line_comment_around_body<'a>( comment: DecoratedComment<'a>, source: &str, ) -> CommentPlacement<'a> { if comment.line_position().is_own_line() { return CommentPlacement::Default(comment); } // Handle comments before the first statement in a body // ```python // for x in range(10): # in the main body ... // pass // else: # ... and in alternative bodies // pass // ``` if let Some(following) = comment.following_node() { if following.is_first_statement_in_body(comment.enclosing_node()) && SimpleTokenizer::new(source, TextRange::new(comment.end(), following.start())) .skip_trivia() .next() .is_none() { return CommentPlacement::dangling(comment.enclosing_node(), comment); } } // Handle comments after a body // ```python // if True: // pass # after the main body ... // // try: // 1 / 0 // except ZeroDivisionError: // print("Error") # ... and after alternative bodies // ``` // The first earlier branch filters out ambiguities e.g. around try-except-finally. if let Some(preceding) = comment.preceding_node() { if let Some(last_child) = preceding.last_child_in_body() { let innermost_child = std::iter::successors(Some(last_child), AnyNodeRef::last_child_in_body) .last() .unwrap_or(last_child); return CommentPlacement::trailing(innermost_child, comment); } } CommentPlacement::Default(comment) } /// Handles own-line comments around a body (at the end of the body, at the end of the header /// preceding the body, or between bodies): /// /// ```python /// for x in y: /// pass /// # This should be a trailing comment of `pass` and not a leading comment of the `print` /// # This is a dangling comment that should be remain before the `else` /// else: /// print("I have no comments") /// # This should be a trailing comment of the print /// # This is a trailing comment of the entire statement /// /// if ( /// True /// # This should be a trailing comment of `True` and not a leading comment of `pass` /// ): /// pass /// ``` fn handle_own_line_comment_around_body<'a>( comment: DecoratedComment<'a>, source: &str, ) -> CommentPlacement<'a> { if comment.line_position().is_end_of_line() { return CommentPlacement::Default(comment); } // If the following is the first child in an alternative body, this must be the last child in // the previous one let Some(preceding) = comment.preceding_node() else { return CommentPlacement::Default(comment); }; // If there's any non-trivia token between the preceding node and the comment, then it means // we're past the case of the alternate branch, defer to the default rules // ```python // if a: // preceding() // # comment we place // else: // # default placement comment // def inline_after_else(): ... // ``` let maybe_token = SimpleTokenizer::new(source, TextRange::new(preceding.end(), comment.start())) .skip_trivia() .next(); if maybe_token.is_some() { return CommentPlacement::Default(comment); } // Check if we're between bodies and should attach to the following body. handle_own_line_comment_between_branches(comment, preceding, source) .or_else(|comment| { // Otherwise, there's no following branch or the indentation is too deep, so attach to the // recursively last statement in the preceding body with the matching indentation. handle_own_line_comment_after_branch(comment, preceding, source) }) .or_else(|comment| handle_own_line_comment_between_statements(comment, source)) } /// Handles own-line comments between statements. If an own-line comment is between two statements, /// it's treated as a leading comment of the following statement _if_ there are no empty lines /// separating the comment and the statement; otherwise, it's treated as a trailing comment of the /// preceding statement. /// /// For example, this comment would be a trailing comment of `x = 1`: /// ```python /// x = 1 /// # comment /// /// y = 2 /// ``` /// /// However, this comment would be a leading comment of `y = 2`: /// ```python /// x = 1 /// /// # comment /// y = 2 /// ``` fn handle_own_line_comment_between_statements<'a>( comment: DecoratedComment<'a>, source: &str, ) -> CommentPlacement<'a> { let Some(preceding) = comment.preceding_node() else { return CommentPlacement::Default(comment); }; let Some(following) = comment.following_node() else { return CommentPlacement::Default(comment); }; // We're looking for comments between two statements, like: // ```python // x = 1 // # comment // y = 2 // ``` if !preceding.is_statement() || !following.is_statement() { return CommentPlacement::Default(comment); } if comment.line_position().is_end_of_line() { return CommentPlacement::Default(comment); } // If the comment is directly attached to the following statement; make it a leading // comment: // ```python // x = 1 // // # leading comment // y = 2 // ``` // // Otherwise, if there's at least one empty line, make it a trailing comment: // ```python // x = 1 // # trailing comment // // y = 2 // ``` if max_empty_lines(&source[TextRange::new(comment.end(), following.start())]) == 0 { CommentPlacement::leading(following, comment) } else { CommentPlacement::trailing(preceding, comment) } } /// Handles own line comments between two branches of a node. /// ```python /// for x in y: /// pass /// # This one ... /// else: /// print("I have no comments") /// # ... but not this one /// ``` fn handle_own_line_comment_between_branches<'a>( comment: DecoratedComment<'a>, preceding: AnyNodeRef<'a>, source: &str, ) -> CommentPlacement<'a> { // The following statement must be the first statement in an alternate body, otherwise check // if it's a comment after the final body and handle that case let Some(following) = comment.following_node() else { return CommentPlacement::Default(comment); }; if !following.is_first_statement_in_alternate_body(comment.enclosing_node()) { return CommentPlacement::Default(comment); } // It depends on the indentation level of the comment if it is a leading comment for the // following branch or if it a trailing comment of the previous body's last statement. let comment_indentation = comment_indentation_after(preceding, comment.range(), source); let preceding_indentation = indentation(source, &preceding).map_or_else( // If `indentation` returns `None`, then there is leading // content before the preceding node. In this case, we // always treat the comment as being less-indented than the // preceding. For example: // // ```python // if True: pass // # leading on `else` // else: // pass // ``` // Note we even do this if the comment is very indented // (which matches `black`'s behavior as of 2025.11.11) // // ```python // if True: pass // # leading on `else` // else: // pass // ``` || { comment_indentation // This can be any positive number - we just // want to hit the `Less` branch below + TextSize::new(1) }, ruff_text_size::TextLen::text_len, ); // Compare to the last statement in the body match comment_indentation.cmp(&preceding_indentation) { Ordering::Greater => { // The comment might belong to an arbitrarily deeply nested inner statement // ```python // while True: // def f_inner(): // pass // # comment // else: // print("noop") // ``` CommentPlacement::Default(comment) } Ordering::Equal => { // The comment belongs to the last statement, unless the preceding branch has a body. // ```python // try: // pass // # I'm a trailing comment of the `pass` // except ZeroDivisionError: // print() // # I'm a dangling comment of the try, even if the indentation matches the except // else: // pass // ``` if preceding.is_alternative_branch_with_node() { // The indentation is equal, but only because the preceding branch has a node. The // comment still belongs to the following branch, which may not have a node. CommentPlacement::dangling(comment.enclosing_node(), comment) } else { CommentPlacement::trailing(preceding, comment) } } Ordering::Less => { // The comment is leading on the following block if following.is_alternative_branch_with_node() { // For some alternative branches, there are nodes ... // ```python // try: // pass // # I'm a leading comment of the `except` statement. // except ZeroDivisionError: // print() // ``` CommentPlacement::leading(following, comment) } else { // ... while for others, such as "else" of for loops and finally branches, the bodies // that are represented as a `Vec<Stmt>`, lacking a no node for the branch that we could // attach the comments to. We mark these as dangling comments and format them manually // in the enclosing node's formatting logic. For `try`, it's the formatters // responsibility to correctly identify the comments for the `finally` and `orelse` // block by looking at the comment's range. // ```python // for x in y: // pass // # I'm a leading comment of the `else` branch but there's no `else` node. // else: // print() // ``` CommentPlacement::dangling(comment.enclosing_node(), comment) } } } } /// Determine where to attach an own line comment after a branch depending on its indentation fn handle_own_line_comment_after_branch<'a>( comment: DecoratedComment<'a>, preceding: AnyNodeRef<'a>, source: &str, ) -> CommentPlacement<'a> { // If the preceding node has a body, we want the last child - e.g. // // ```python // if True: // def foo(): // something // last_child // # comment // else: // pass // ``` // // Otherwise, the preceding node may be the last statement in the body // of the preceding branch, in which case we can take it as our // `last_child` here - e.g. // // ```python // if True: // something // last_child // # comment // else: // pass // ``` let last_child = match preceding.last_child_in_body() { Some(last) => last, None if comment.following_node().is_some_and(|following| { following.is_first_statement_in_alternate_body(comment.enclosing_node()) }) => { preceding } _ => { return CommentPlacement::Default(comment); } }; // We only care about the length because indentations with mixed spaces and tabs are only valid if // the indent-level doesn't depend on the tab width (the indent level must be the same if the tab width is 1 or 8). let comment_indentation = comment_indentation_after(preceding, comment.range(), source); // Keep the comment on the entire statement in case it's a trailing comment // ```python // if "first if": // pass // elif "first elif": // pass // # Trailing if comment // ``` // Here we keep the comment a trailing comment of the `if` let preceding_indentation = indentation_at_offset(preceding.start(), source) .unwrap_or_default() .text_len(); if comment_indentation == preceding_indentation { return CommentPlacement::Default(comment); } let mut parent = None; let mut last_child_in_parent = last_child; loop { let child_indentation = indentation(source, &last_child_in_parent) .unwrap_or_default() .text_len(); // There a three cases: // ```python // if parent_body: // if current_body: // child_in_body() // last_child_in_current_body # may or may not have children on its own // # less: Comment belongs to the parent block. // # less: Comment belongs to the parent block. // # equal: The comment belongs to this block. // # greater (but less in the next iteration) // # greater: The comment belongs to the inner block. // ``` match comment_indentation.cmp(&child_indentation) { Ordering::Less => { return if let Some(parent_block) = parent { // Comment belongs to the parent block. CommentPlacement::trailing(parent_block, comment) } else { // The comment does not belong to this block. // ```python // if test: // pass // # comment // ``` CommentPlacement::Default(comment) }; } Ordering::Equal => { // The comment belongs to this block. return CommentPlacement::trailing(last_child_in_parent, comment); } Ordering::Greater => { if let Some(nested_child) = last_child_in_parent.last_child_in_body() { // The comment belongs to the inner block. parent = Some(last_child_in_parent); last_child_in_parent = nested_child; } else { // The comment is overindented, we assign it to the most indented child we have. // ```python // if test: // pass // # comment // ``` return CommentPlacement::trailing(last_child_in_parent, comment); } } } } } /// Attaches comments for the positional-only parameters separator `/` or the keywords-only /// parameters separator `*` as dangling comments to the enclosing [`Parameters`] node. /// /// See [`assign_argument_separator_comment_placement`] fn handle_parameters_separator_comment<'a>( comment: DecoratedComment<'a>, parameters: &Parameters, source: &str, ) -> CommentPlacement<'a> { let (slash, star) = find_parameter_separators(source, parameters); let placement = assign_argument_separator_comment_placement( slash.as_ref(), star.as_ref(), comment.range(), comment.line_position(), ); if placement.is_some() { return CommentPlacement::dangling(comment.enclosing_node(), comment); } CommentPlacement::Default(comment) } /// Associate comments that come before the `:` starting the type annotation or before the /// parameter's name for unannotated parameters as leading parameter-comments. /// /// The parameter's name isn't a node to which comments can be associated. /// That's why we pull out all comments that come before the expression name or the type annotation
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
true
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/comments/mod.rs
crates/ruff_python_formatter/src/comments/mod.rs
//! Types for extracting and representing comments of a syntax tree. //! //! Most programming languages support comments allowing programmers to document their programs. //! Comments are different from other syntax because programming languages allow comments in almost any position, //! giving programmers great flexibility on where they can write comments: //! //! ```javascript //! /** //! * Documentation comment //! */ //! async /* comment */ function Test () // line comment //! {/*inline*/} //! ``` //! //! This flexibility makes formatting comments challenging because: //! * The formatter must consistently place comments so that re-formatting the output yields the same result, //! and does not create invalid syntax (line comments). //! * It is essential that formatters place comments close to the syntax the programmer intended to document. //! However, the lack of rules regarding where comments are allowed and what syntax they document requires //! the use of heuristics to infer the documented syntax. //! //! This module tries to strike a balance between placing comments as closely as possible to their source location //! and reducing the complexity of formatting comments. It does so by associating comments per node rather than a token. //! This greatly reduces the combinations of possible comment positions, but turns out to be, in practice, //! sufficiently precise to keep comments close to their source location. //! //! Luckily, Python doesn't support inline comments, which simplifying the problem significantly. //! //! ## Node comments //! //! Comments are associated per node but get further distinguished on their location related to that node: //! //! ### Leading Comments //! //! A comment at the start of a node //! //! ```python //! # Leading comment of the statement //! print("test"); //! //! [ # Leading comment of a //! a //! ]; //! ``` //! //! ### Dangling Comments //! //! A comment that is neither at the start nor the end of a node. //! //! ```python //! [ //! # I'm between two brackets. There are no nodes //! ]; //! ``` //! //! ### Trailing Comments //! //! A comment at the end of a node. //! //! ```python //! [ //! a, # trailing comment of a //! b, c //! ]; //! ``` //! //! ## Limitations //! Limiting the placement of comments to leading, dangling, or trailing node comments reduces complexity inside the formatter but means, //! that the formatter's possibility of where comments can be formatted depends on the AST structure. //! //! For example, *`RustPython`* doesn't create a node for the `/` operator separating positional only arguments from the other arguments. //! //! ```python //! def test( //! a, //! /, # The following arguments are positional or named arguments //! b //! ): //! pass //! ``` //! //! Because *`RustPython`* doesn't create a Node for the `/` argument, it is impossible to associate any //! comments with it. Meaning, the default behaviour is to associate the `# The following ...` comment //! with the `b` argument, which is incorrect. This limitation can be worked around by implementing //! a custom rule to associate comments for `/` as *dangling comments* of the `Arguments` node and then //! implement custom formatting inside of the arguments formatter. //! //! It is possible to add an additional optional label to [`SourceComment`] If ever the need arises to distinguish two *dangling comments* in the formatting logic, use std::cell::Cell; use std::fmt::Debug; use std::rc::Rc; pub(crate) use format::{ dangling_comments, dangling_node_comments, dangling_open_parenthesis_comments, leading_alternate_branch_comments, leading_comments, leading_node_comments, trailing_comments, }; use ruff_formatter::{SourceCode, SourceCodeSlice}; use ruff_python_ast::AnyNodeRef; use ruff_python_trivia::{CommentLinePosition, CommentRanges, SuppressionKind}; use ruff_text_size::{Ranged, TextRange}; pub(crate) use visitor::collect_comments; use crate::comments::debug::{DebugComment, DebugComments}; use crate::comments::map::{LeadingDanglingTrailing, MultiMap}; use crate::comments::node_key::NodeRefEqualityKey; use crate::comments::visitor::{CommentsMapBuilder, CommentsVisitor}; mod debug; pub(crate) mod format; mod map; mod node_key; mod placement; mod visitor; /// A comment in the source document. #[derive(Debug, Clone, Eq, PartialEq)] pub(crate) struct SourceComment { /// The location of the comment in the source document. slice: SourceCodeSlice, /// Whether the comment has been formatted or not. formatted: Cell<bool>, line_position: CommentLinePosition, } impl SourceComment { fn new(slice: SourceCodeSlice, position: CommentLinePosition) -> Self { Self { slice, line_position: position, formatted: Cell::new(false), } } /// Returns the location of the comment in the original source code. /// Allows retrieving the text of the comment. pub(crate) const fn slice(&self) -> &SourceCodeSlice { &self.slice } pub(crate) const fn line_position(&self) -> CommentLinePosition { self.line_position } /// Marks the comment as formatted pub(crate) fn mark_formatted(&self) { self.formatted.set(true); } /// Marks the comment as not-formatted pub(crate) fn mark_unformatted(&self) { self.formatted.set(false); } /// If the comment has already been formatted pub(crate) fn is_formatted(&self) -> bool { self.formatted.get() } pub(crate) fn is_unformatted(&self) -> bool { !self.is_formatted() } /// Returns a nice debug representation that prints the source code for every comment (and not just the range). pub(crate) fn debug<'a>(&'a self, source_code: SourceCode<'a>) -> DebugComment<'a> { DebugComment::new(self, source_code) } pub(crate) fn is_suppression_off_comment(&self, text: &str) -> bool { SuppressionKind::is_suppression_off(self.text(text), self.line_position) } pub(crate) fn is_suppression_on_comment(&self, text: &str) -> bool { SuppressionKind::is_suppression_on(self.text(text), self.line_position) } fn text<'a>(&self, text: &'a str) -> &'a str { self.slice.text(SourceCode::new(text)) } } impl Ranged for SourceComment { #[inline] fn range(&self) -> TextRange { self.slice.range() } } type CommentsMap<'a> = MultiMap<NodeRefEqualityKey<'a>, SourceComment>; /// The comments of a syntax tree stored by node. /// /// Cloning `comments` is cheap as it only involves bumping a reference counter. #[derive(Debug, Clone)] pub(crate) struct Comments<'a> { /// The implementation uses an [Rc] so that [Comments] has a lifetime independent from the [`crate::Formatter`]. /// Independent lifetimes are necessary to support the use case where a (formattable object)[`crate::Format`] /// iterates over all comments, and writes them into the [`crate::Formatter`] (mutably borrowing the [`crate::Formatter`] and in turn its context). /// /// ```block /// for leading in f.context().comments().leading_comments(node) { /// ^ /// |- Borrows comments /// write!(f, [comment(leading.piece.text())])?; /// ^ /// |- Mutably borrows the formatter, state, context, and comments (if comments aren't cloned) /// } /// ``` /// /// The use of an `Rc` solves this problem because we can cheaply clone `comments` before iterating. /// /// ```block /// let comments = f.context().comments().clone(); /// for leading in comments.leading_comments(node) { /// write!(f, [comment(leading.piece.text())])?; /// } /// ``` data: Rc<CommentsData<'a>>, } impl<'a> Comments<'a> { fn new(comments: CommentsMap<'a>, comment_ranges: &'a CommentRanges) -> Self { Self { data: Rc::new(CommentsData { comments, comment_ranges, }), } } /// Effectively a [`Default`] implementation that works around the lifetimes for tests #[cfg(test)] pub(crate) fn from_ranges(comment_ranges: &'a CommentRanges) -> Self { Self { data: Rc::new(CommentsData { comments: CommentsMap::default(), comment_ranges, }), } } pub(crate) fn ranges(&self) -> &'a CommentRanges { self.data.comment_ranges } /// Extracts the comments from the AST. pub(crate) fn from_ast( root: impl Into<AnyNodeRef<'a>>, source_code: SourceCode<'a>, comment_ranges: &'a CommentRanges, ) -> Self { fn collect_comments<'a>( root: AnyNodeRef<'a>, source_code: SourceCode<'a>, comment_ranges: &'a CommentRanges, ) -> Comments<'a> { let map = if comment_ranges.is_empty() { CommentsMap::new() } else { let mut builder = CommentsMapBuilder::new(source_code.as_str(), comment_ranges); CommentsVisitor::new(source_code, comment_ranges, &mut builder).visit(root); builder.finish() }; Comments::new(map, comment_ranges) } collect_comments(root.into(), source_code, comment_ranges) } /// Returns `true` if the given `node` has any comments. #[inline] pub(crate) fn has<T>(&self, node: T) -> bool where T: Into<AnyNodeRef<'a>>, { self.data .comments .has(&NodeRefEqualityKey::from_ref(node.into())) } /// Returns `true` if the given `node` has any [leading comments](self#leading-comments). #[inline] pub(crate) fn has_leading<T>(&self, node: T) -> bool where T: Into<AnyNodeRef<'a>>, { !self.leading(node).is_empty() } /// Returns the `node`'s [leading comments](self#leading-comments). #[inline] pub(crate) fn leading<T>(&self, node: T) -> &[SourceComment] where T: Into<AnyNodeRef<'a>>, { self.data .comments .leading(&NodeRefEqualityKey::from_ref(node.into())) } /// Returns `true` if node has any [dangling comments](self#dangling-comments). pub(crate) fn has_dangling<T>(&self, node: T) -> bool where T: Into<AnyNodeRef<'a>>, { !self.dangling(node).is_empty() } /// Returns the [dangling comments](self#dangling-comments) of `node` pub(crate) fn dangling<T>(&self, node: T) -> &[SourceComment] where T: Into<AnyNodeRef<'a>>, { self.data .comments .dangling(&NodeRefEqualityKey::from_ref(node.into())) } /// Returns the `node`'s [trailing comments](self#trailing-comments). #[inline] pub(crate) fn trailing<T>(&self, node: T) -> &[SourceComment] where T: Into<AnyNodeRef<'a>>, { self.data .comments .trailing(&NodeRefEqualityKey::from_ref(node.into())) } /// Returns `true` if the given `node` has any [trailing comments](self#trailing-comments). #[inline] pub(crate) fn has_trailing<T>(&self, node: T) -> bool where T: Into<AnyNodeRef<'a>>, { !self.trailing(node).is_empty() } /// Returns `true` if the given `node` has any [trailing own line comments](self#trailing-comments). #[inline] pub(crate) fn has_trailing_own_line<T>(&self, node: T) -> bool where T: Into<AnyNodeRef<'a>>, { self.trailing(node) .iter() .any(|comment| comment.line_position().is_own_line()) } /// Returns an iterator over the [leading](self#leading-comments) and [trailing comments](self#trailing-comments) of `node`. pub(crate) fn leading_trailing<T>(&self, node: T) -> impl Iterator<Item = &SourceComment> where T: Into<AnyNodeRef<'a>>, { let comments = self.leading_dangling_trailing(node); comments.leading.iter().chain(comments.trailing) } /// Returns an iterator over the [leading](self#leading-comments), [dangling](self#dangling-comments), and [trailing](self#trailing) comments of `node`. pub(crate) fn leading_dangling_trailing<T>( &self, node: T, ) -> LeadingDanglingTrailingComments<'_> where T: Into<AnyNodeRef<'a>>, { self.data .comments .leading_dangling_trailing(&NodeRefEqualityKey::from_ref(node.into())) } #[inline(always)] #[cfg(not(debug_assertions))] pub(crate) fn assert_all_formatted(&self, _source_code: SourceCode) {} #[cfg(debug_assertions)] pub(crate) fn assert_all_formatted(&self, source_code: SourceCode) { use std::fmt::Write; let mut output = String::new(); let unformatted_comments = self .data .comments .all_parts() .filter(|c| !c.formatted.get()); for comment in unformatted_comments { // SAFETY: Writing to a string never fails. writeln!(output, "{:#?}", comment.debug(source_code)).unwrap(); } assert!( output.is_empty(), "The following comments have not been formatted.\n{output}" ); } #[inline(always)] #[cfg(not(debug_assertions))] pub(crate) fn mark_verbatim_node_comments_formatted(&self, _node: AnyNodeRef) {} /// Marks the comments of a node printed in verbatim (suppressed) as formatted. /// /// Marks the dangling comments and the comments of all descendants as formatted. /// The leading and trailing comments are not marked as formatted because they are formatted /// normally if `node` is the first or last node of a suppression range. #[cfg(debug_assertions)] pub(crate) fn mark_verbatim_node_comments_formatted(&self, node: AnyNodeRef) { use ruff_python_ast::visitor::source_order::{SourceOrderVisitor, TraversalSignal}; struct MarkVerbatimCommentsAsFormattedVisitor<'a>(&'a Comments<'a>); impl<'a> SourceOrderVisitor<'a> for MarkVerbatimCommentsAsFormattedVisitor<'a> { fn enter_node(&mut self, node: AnyNodeRef<'a>) -> TraversalSignal { for comment in self.0.leading_dangling_trailing(node) { comment.mark_formatted(); } TraversalSignal::Traverse } } for dangling in self.dangling(node) { dangling.mark_formatted(); } node.visit_source_order(&mut MarkVerbatimCommentsAsFormattedVisitor(self)); } /// Returns an object that implements [Debug] for nicely printing the [`Comments`]. pub(crate) fn debug(&'a self, source_code: SourceCode<'a>) -> DebugComments<'a> { DebugComments::new(&self.data.comments, source_code) } /// Returns true if the node itself or any of its descendants have comments. pub(crate) fn contains_comments(&self, node: AnyNodeRef) -> bool { use ruff_python_ast::visitor::source_order::{SourceOrderVisitor, TraversalSignal}; struct Visitor<'a> { comments: &'a Comments<'a>, has_comment: bool, } impl<'a> SourceOrderVisitor<'a> for Visitor<'a> { fn enter_node(&mut self, node: AnyNodeRef<'a>) -> TraversalSignal { if self.has_comment { TraversalSignal::Skip } else if self.comments.has(node) { self.has_comment = true; TraversalSignal::Skip } else { TraversalSignal::Traverse } } } if self.has(node) { return true; } let mut visitor = Visitor { comments: self, has_comment: false, }; node.visit_source_order(&mut visitor); visitor.has_comment } } pub(crate) type LeadingDanglingTrailingComments<'a> = LeadingDanglingTrailing<'a, SourceComment>; impl LeadingDanglingTrailingComments<'_> { /// Returns `true` if the struct has any [leading comments](self#leading-comments). #[inline] pub(crate) fn has_leading(&self) -> bool { !self.leading.is_empty() } /// Returns `true` if the struct has any [trailing comments](self#trailing-comments). #[inline] pub(crate) fn has_trailing(&self) -> bool { !self.trailing.is_empty() } /// Returns `true` if the struct has any [trailing own line comments](self#trailing-comments). #[inline] pub(crate) fn has_trailing_own_line(&self) -> bool { self.trailing .iter() .any(|comment| comment.line_position().is_own_line()) } } #[derive(Debug)] struct CommentsData<'a> { comments: CommentsMap<'a>, /// We need those for backwards lexing comment_ranges: &'a CommentRanges, } pub(crate) fn has_skip_comment(trailing_comments: &[SourceComment], source: &str) -> bool { trailing_comments.iter().any(|comment| { comment.line_position().is_end_of_line() && matches!( SuppressionKind::from_comment(comment.text(source)), Some(SuppressionKind::Skip | SuppressionKind::Off) ) }) } #[cfg(test)] mod tests { use insta::assert_debug_snapshot; use ruff_formatter::SourceCode; use ruff_python_ast::{Mod, PySourceType}; use ruff_python_parser::{ParseOptions, Parsed, parse}; use ruff_python_trivia::CommentRanges; use crate::comments::Comments; struct CommentsTestCase<'a> { parsed: Parsed<Mod>, comment_ranges: CommentRanges, source_code: SourceCode<'a>, } impl<'a> CommentsTestCase<'a> { fn from_code(source: &'a str) -> Self { let source_code = SourceCode::new(source); let source_type = PySourceType::Python; let parsed = parse(source, ParseOptions::from(source_type)) .expect("Expect source to be valid Python"); let comment_ranges = CommentRanges::from(parsed.tokens()); CommentsTestCase { parsed, comment_ranges, source_code, } } fn to_comments(&self) -> Comments<'_> { Comments::from_ast(self.parsed.syntax(), self.source_code, &self.comment_ranges) } } #[test] fn base_test() { let source = r#" # Function Leading comment def test(x, y): if x == y: # if statement end of line comment print("Equal") # Leading comment elif x < y: print("Less") else: print("Greater") # own line comment test(10, 20) "#; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn only_comments() { let source = r" # Some comment # another comment "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn empty_file() { let source = r""; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn dangling_comment() { let source = r" def test( # Some comment ): pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn parenthesized_expression() { let source = r" a = ( # Trailing comment 10 + # More comments 3 ) "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn parenthesized_trailing_comment() { let source = r"( a # comment ) "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn trailing_function_comment() { let source = r#" def test(x, y): if x == y: pass elif x < y: print("Less") else: print("Greater") # trailing `else` comment # Trailing `if` statement comment def other(y, z): if y == z: pass # Trailing `pass` comment # Trailing `if` statement comment class Test: def func(): pass # Trailing `func` function comment test(10, 20) "#; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn trailing_comment_after_single_statement_body() { let source = r#" if x == y: pass # Test print("test") "#; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn if_elif_else_comments() { let source = r" if x == y: pass # trailing `pass` comment # Root `if` trailing comment # Leading elif comment elif x < y: pass # `elif` trailing comment # Leading else comment else: pass # `else` trailing comment "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn if_elif_if_else_comments() { let source = r" if x == y: pass elif x < y: if x < 10: pass # `elif` trailing comment # Leading else comment else: pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn try_except_finally_else() { let source = r#" try: pass # trailing try comment # leading handler comment except Exception as ex: pass # Trailing except comment # leading else comment else: pass # trailing else comment # leading finally comment finally: print("Finally!") # Trailing finally comment "#; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn try_except() { let source = r#" def test(): try: pass # trailing try comment # leading handler comment except Exception as ex: pass # Trailing except comment # Trailing function comment print("Next statement"); "#; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } // Issue: Match cases #[test] fn match_cases() { let source = r#"def make_point_3d(pt): match pt: # Leading `case(x, y)` comment case (x, y): return Point3d(x, y, 0) # Trailing `case(x, y) comment # Leading `case (x, y, z)` comment case (x, y, z): if x < y: print("if") else: print("else") # Trailing else comment # trailing case comment case Point2d(x, y): return Point3d(x, y, 0) case _: raise TypeError("not a point we support") # Trailing last case comment # Trailing match comment # After match comment print("other") "#; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn leading_most_outer() { let source = r" # leading comment x "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } // Comment should be attached to the statement #[test] fn trailing_most_outer() { let source = r" x # trailing comment y # trailing last node "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn trailing_most_outer_nested() { let source = r" x + ( 3 # trailing comment ) # outer "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn trailing_after_comma() { let source = r" def test( a, # Trailing comment for argument `a` b, ): pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn positional_argument_only_comment() { let source = r" def test( a, # trailing positional comment # Positional arguments only after here /, # trailing positional argument comment. # leading b comment b, ): pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn positional_argument_only_leading_comma_comment() { let source = r" def test( a # trailing positional comment # Positional arguments only after here ,/, # trailing positional argument comment. # leading b comment b, ): pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn positional_argument_only_comment_without_following_node() { let source = r" def test( a, # trailing positional comment # Positional arguments only after here /, # trailing positional argument comment. # Trailing on new line ): pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn non_positional_arguments_with_defaults() { let source = r" def test( a=10 # trailing positional comment # Positional arguments only after here ,/, # trailing positional argument comment. # leading comment for b b=20 ): pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn non_positional_arguments_slash_on_same_line() { let source = r" def test(a=10,/, # trailing positional argument comment. # leading comment for b b=20 ): pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn binary_expression_left_operand_comment() { let source = r" a = ( 5 # trailing left comment + # leading right comment 3 ) "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn binary_expression_left_operand_trailing_end_of_line_comment() { let source = r" a = ( 5 # trailing left comment + # trailing operator comment # leading right comment 3 ) "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn nested_binary_expression() { let source = r" a = ( (5 # trailing left comment * 2) + # trailing operator comment # leading right comment 3 ) "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn while_trailing_end_of_line_comment() { let source = r"while True: if something.changed: do.stuff() # trailing comment "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn while_trailing_else_end_of_line_comment() { let source = r"while True: pass else: # trailing comment pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn while_else_indented_comment_between_branches() { let source = r"while True: pass # comment else: pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } #[test] fn while_else_very_indented_comment_between_branches() { let source = r"while True: pass # comment else: pass "; let test_case = CommentsTestCase::from_code(source); let comments = test_case.to_comments(); assert_debug_snapshot!(comments.debug(test_case.source_code)); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/comments/format.rs
crates/ruff_python_formatter/src/comments/format.rs
use std::borrow::Cow; use ruff_formatter::{FormatError, FormatOptions, SourceCode, format_args, write}; use ruff_python_ast::{AnyNodeRef, NodeKind, PySourceType}; use ruff_python_trivia::{ CommentLinePosition, is_pragma_comment, lines_after, lines_after_ignoring_trivia, lines_before, }; use ruff_text_size::{Ranged, TextLen, TextRange}; use crate::comments::SourceComment; use crate::context::NodeLevel; use crate::prelude::*; use crate::statement::suite::should_insert_blank_line_after_class_in_stub_file; /// Formats the leading comments of a node. pub(crate) fn leading_node_comments<'a, T>(node: T) -> FormatLeadingComments<'a> where T: Into<AnyNodeRef<'a>>, { FormatLeadingComments::Node(node.into()) } /// Formats the passed comments as leading comments pub(crate) const fn leading_comments(comments: &[SourceComment]) -> FormatLeadingComments<'_> { FormatLeadingComments::Comments(comments) } #[derive(Copy, Clone, Debug)] pub(crate) enum FormatLeadingComments<'a> { Node(AnyNodeRef<'a>), Comments(&'a [SourceComment]), } impl Format<PyFormatContext<'_>> for FormatLeadingComments<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { fn write_leading_comments( comments: &[SourceComment], f: &mut PyFormatter, ) -> FormatResult<()> { for comment in comments.iter().filter(|comment| comment.is_unformatted()) { let lines_after_comment = lines_after(comment.end(), f.context().source()); write!( f, [format_comment(comment), empty_lines(lines_after_comment)] )?; comment.mark_formatted(); } Ok(()) } match self { FormatLeadingComments::Node(node) => { let comments = f.context().comments().clone(); write_leading_comments(comments.leading(*node), f) } FormatLeadingComments::Comments(comments) => write_leading_comments(comments, f), } } } /// Formats the leading `comments` of an alternate branch and ensures that it preserves the right /// number of empty lines before. The `last_node` is the last node of the preceding body. /// /// For example, `last_node` is the last statement in the if body when formatting the leading /// comments of the `else` branch. pub(crate) fn leading_alternate_branch_comments<'a, T>( comments: &'a [SourceComment], last_node: Option<T>, ) -> FormatLeadingAlternateBranchComments<'a> where T: Into<AnyNodeRef<'a>>, { FormatLeadingAlternateBranchComments { comments, last_node: last_node.map(Into::into), } } pub(crate) struct FormatLeadingAlternateBranchComments<'a> { comments: &'a [SourceComment], last_node: Option<AnyNodeRef<'a>>, } impl Format<PyFormatContext<'_>> for FormatLeadingAlternateBranchComments<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { if self.last_node.is_some_and(|preceding| { should_insert_blank_line_after_class_in_stub_file(preceding, None, f.context()) }) { write!(f, [empty_line(), leading_comments(self.comments)])?; } else if let Some(first_leading) = self.comments.first() { // Leading comments only preserves the lines after the comment but not before. // Insert the necessary lines. write!( f, [empty_lines(lines_before( first_leading.start(), f.context().source() ))] )?; write!(f, [leading_comments(self.comments)])?; } else if let Some(last_preceding) = self.last_node { // The leading comments formatting ensures that it preserves the right amount of lines // after We need to take care of this ourselves, if there's no leading `else` comment. // Since the `last_node` could be a compound node, we need to skip _all_ trivia. // // For example, here, when formatting the `if` statement, the `last_node` (the `while`) // would end at the end of `pass`, but we want to skip _all_ comments: // ```python // if True: // while True: // pass // # comment // // # comment // else: // ... // ``` // // `lines_after_ignoring_trivia` is safe here, as we _know_ that the `else` doesn't // have any leading comments. write!( f, [empty_lines(lines_after_ignoring_trivia( last_preceding.end(), f.context().source() ))] )?; } Ok(()) } } /// Formats the passed comments as trailing comments pub(crate) fn trailing_comments(comments: &[SourceComment]) -> FormatTrailingComments<'_> { FormatTrailingComments(comments) } pub(crate) struct FormatTrailingComments<'a>(&'a [SourceComment]); impl Format<PyFormatContext<'_>> for FormatTrailingComments<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { let mut has_trailing_own_line_comment = false; for trailing in self.0.iter().filter(|comment| comment.is_unformatted()) { has_trailing_own_line_comment |= trailing.line_position().is_own_line(); if has_trailing_own_line_comment { let lines_before_comment = lines_before(trailing.start(), f.context().source()); // A trailing comment at the end of a body or list // ```python // def test(): // pass // // # Some comment // ``` write!( f, [ line_suffix( &format_args![ empty_lines(lines_before_comment), format_comment(trailing), ], // Reserving width isn't necessary because we don't split // comments and the empty lines expand any enclosing group. 0 ), expand_parent() ] )?; } else { // A trailing comment at the end of a line has a reserved width to // consider during line measurement. // ```python // tup = ( // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // ) # Some comment // ``` trailing_end_of_line_comment(trailing).fmt(f)?; } trailing.mark_formatted(); } Ok(()) } } /// Formats the dangling comments of `node`. pub(crate) fn dangling_node_comments<'a, T>(node: T) -> FormatDanglingComments<'a> where T: Into<AnyNodeRef<'a>>, { FormatDanglingComments::Node(node.into()) } pub(crate) fn dangling_comments(comments: &[SourceComment]) -> FormatDanglingComments<'_> { FormatDanglingComments::Comments(comments) } pub(crate) enum FormatDanglingComments<'a> { Node(AnyNodeRef<'a>), Comments(&'a [SourceComment]), } impl Format<PyFormatContext<'_>> for FormatDanglingComments<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> { let comments = f.context().comments().clone(); let dangling_comments = match self { Self::Comments(comments) => comments, Self::Node(node) => comments.dangling(*node), }; let mut first = true; for comment in dangling_comments .iter() .filter(|comment| comment.is_unformatted()) { if first { match comment.line_position { CommentLinePosition::OwnLine => { write!(f, [hard_line_break()])?; } CommentLinePosition::EndOfLine => { write!(f, [space(), space()])?; } } } write!( f, [ format_comment(comment), empty_lines(lines_after(comment.end(), f.context().source())) ] )?; comment.mark_formatted(); first = false; } Ok(()) } } /// Formats the dangling comments within a parenthesized expression, for example: /// ```python /// [ # comment /// 1, /// 2, /// 3, /// ] /// ``` pub(crate) fn dangling_open_parenthesis_comments( comments: &[SourceComment], ) -> FormatDanglingOpenParenthesisComments<'_> { FormatDanglingOpenParenthesisComments { comments } } pub(crate) struct FormatDanglingOpenParenthesisComments<'a> { comments: &'a [SourceComment], } impl Format<PyFormatContext<'_>> for FormatDanglingOpenParenthesisComments<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> { for comment in self .comments .iter() .filter(|comment| comment.is_unformatted()) { debug_assert!( comment.line_position().is_end_of_line(), "Expected dangling comment to be at the end of the line" ); trailing_end_of_line_comment(comment).fmt(f)?; comment.mark_formatted(); } Ok(()) } } /// Formats the content of the passed comment. /// /// * Adds a whitespace between `#` and the comment text except if the first character is a `#`, `:`, `'`, or `!` /// * Replaces non breaking whitespaces with regular whitespaces except if in front of a `types:` comment pub(crate) const fn format_comment(comment: &SourceComment) -> FormatComment<'_> { FormatComment { comment } } pub(crate) struct FormatComment<'a> { comment: &'a SourceComment, } impl Format<PyFormatContext<'_>> for FormatComment<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { let slice = self.comment.slice(); let source = SourceCode::new(f.context().source()); let normalized_comment = normalize_comment(self.comment, source)?; format_normalized_comment(normalized_comment, slice.range()).fmt(f) } } /// Helper that inserts the appropriate number of empty lines before a comment, depending on the node level: /// - Top-level: Up to two empty lines. /// - Parenthesized: A single empty line. /// - Otherwise: Up to a single empty line. pub(crate) const fn empty_lines(lines: u32) -> FormatEmptyLines { FormatEmptyLines { lines } } #[derive(Copy, Clone, Debug)] pub(crate) struct FormatEmptyLines { lines: u32, } impl Format<PyFormatContext<'_>> for FormatEmptyLines { fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> { match f.context().node_level() { NodeLevel::TopLevel(_) => match self.lines { 0 | 1 => write!(f, [hard_line_break()]), 2 => write!(f, [empty_line()]), _ => match f.options().source_type() { PySourceType::Stub => { write!(f, [empty_line()]) } PySourceType::Python | PySourceType::Ipynb => { write!(f, [empty_line(), empty_line()]) } }, }, NodeLevel::CompoundStatement => match self.lines { 0 | 1 => write!(f, [hard_line_break()]), _ => write!(f, [empty_line()]), }, // Remove all whitespace in parenthesized expressions NodeLevel::Expression(_) | NodeLevel::ParenthesizedExpression => { write!(f, [hard_line_break()]) } } } } /// A helper that constructs a formattable element using a reserved-width line-suffix /// for normalized comments. /// /// * Black normalization of `SourceComment`. /// * Line suffix with reserved width for the final, normalized content. /// * Expands parent node. pub(crate) const fn trailing_end_of_line_comment( comment: &SourceComment, ) -> FormatTrailingEndOfLineComment<'_> { FormatTrailingEndOfLineComment { comment } } pub(crate) struct FormatTrailingEndOfLineComment<'a> { comment: &'a SourceComment, } impl Format<PyFormatContext<'_>> for FormatTrailingEndOfLineComment<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { let slice = self.comment.slice(); let source = SourceCode::new(f.context().source()); let normalized_comment = normalize_comment(self.comment, source)?; // Don't reserve width for excluded pragma comments. let reserved_width = if is_pragma_comment(&normalized_comment) { 0 } else { // Start with 2 because of the two leading spaces. 2u32.saturating_add( TextWidth::from_text(&normalized_comment, f.options().indent_width()) .width() .expect("Expected comment not to contain any newlines") .value(), ) }; write!( f, [ line_suffix( &format_args![ space(), space(), format_normalized_comment(normalized_comment, slice.range()) ], reserved_width ), expand_parent() ] ) } } /// A helper that constructs formattable normalized comment text as efficiently as /// possible. /// /// * If the content is unaltered then format with source text slice strategy and no /// unnecessary allocations. /// * If the content is modified then make as few allocations as possible and use /// a dynamic text element at the original slice's start position. pub(crate) const fn format_normalized_comment( comment: Cow<'_, str>, range: TextRange, ) -> FormatNormalizedComment<'_> { FormatNormalizedComment { comment, range } } pub(crate) struct FormatNormalizedComment<'a> { comment: Cow<'a, str>, range: TextRange, } impl Format<PyFormatContext<'_>> for FormatNormalizedComment<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> { let write_sourcemap = f.options().source_map_generation().is_enabled(); write_sourcemap .then_some(source_position(self.range.start())) .fmt(f)?; match self.comment { Cow::Borrowed(borrowed) => { source_text_slice(TextRange::at(self.range.start(), borrowed.text_len())).fmt(f)?; } Cow::Owned(ref owned) => { text(owned).fmt(f)?; } } write_sourcemap .then_some(source_position(self.range.end())) .fmt(f) } } /// A helper for normalizing comments by: /// * Trimming any trailing whitespace. /// * Adding a leading space after the `#`, if necessary. /// /// For example: /// * `#comment` is normalized to `# comment`. /// * `# comment ` is normalized to `# comment`. /// * `# comment` is left as-is. /// * `#!comment` is left as-is. fn normalize_comment<'a>( comment: &'a SourceComment, source: SourceCode<'a>, ) -> FormatResult<Cow<'a, str>> { let slice = comment.slice(); let comment_text = slice.text(source); let trimmed = comment_text.trim_end(); let content = strip_comment_prefix(trimmed)?; if content.is_empty() { return Ok(Cow::Borrowed("#")); } // Fast path for correctly formatted comments: if the comment starts with a space, or any // of the allowed characters, then it's included verbatim (apart for trimming any trailing // whitespace). if content.starts_with([' ', '!', ':', '#', '\'']) { return Ok(Cow::Borrowed(trimmed)); } // Otherwise, we need to normalize the comment by adding a space after the `#`. if content.starts_with('\u{A0}') { let trimmed = content.trim_start_matches('\u{A0}'); if trimmed.trim_start().starts_with("type:") { // Black adds a space before the non-breaking space if part of a type pragma. Ok(Cow::Owned(std::format!("# {content}"))) } else if trimmed.starts_with(' ') { // Black replaces the non-breaking space with a space if followed by a space. Ok(Cow::Owned(std::format!("# {trimmed}"))) } else { // Otherwise we replace the first non-breaking space with a regular space. Ok(Cow::Owned(std::format!("# {}", &content["\u{A0}".len()..]))) } } else { Ok(Cow::Owned(std::format!("# {}", content.trim_start()))) } } /// A helper for stripping '#' from comments. fn strip_comment_prefix(comment_text: &str) -> FormatResult<&str> { let Some(content) = comment_text.strip_prefix('#') else { return Err(FormatError::syntax_error( "Didn't find expected comment token `#`", )); }; Ok(content) } /// Format the empty lines between a node and its trailing comments. /// /// For example, given: /// ```python /// class Class: /// ... /// # comment /// ``` /// /// This builder will insert two empty lines before the comment. /// /// # Preview /// /// For preview style, this builder will insert a single empty line after a /// class definition in a stub file. /// /// For example, given: /// ```python /// class Foo: /// pass /// # comment /// ``` /// /// This builder will insert a single empty line before the comment. pub(crate) fn empty_lines_before_trailing_comments( comments: &[SourceComment], node_kind: NodeKind, ) -> FormatEmptyLinesBeforeTrailingComments<'_> { FormatEmptyLinesBeforeTrailingComments { comments, node_kind, } } #[derive(Copy, Clone, Debug)] pub(crate) struct FormatEmptyLinesBeforeTrailingComments<'a> { /// The trailing comments of the node. comments: &'a [SourceComment], node_kind: NodeKind, } impl Format<PyFormatContext<'_>> for FormatEmptyLinesBeforeTrailingComments<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> { if let Some(comment) = self .comments .iter() .find(|comment| comment.line_position().is_own_line()) { // Black has different rules for stub vs. non-stub and top level vs. indented let empty_lines = match (f.options().source_type(), f.context().node_level()) { (PySourceType::Stub, NodeLevel::TopLevel(_)) => 1, (PySourceType::Stub, _) => u32::from(self.node_kind == NodeKind::StmtClassDef), (_, NodeLevel::TopLevel(_)) => 2, (_, _) => 1, }; let actual = lines_before(comment.start(), f.context().source()).saturating_sub(1); for _ in actual..empty_lines { empty_line().fmt(f)?; } } Ok(()) } } /// Format the empty lines between a node and its leading comments. /// /// For example, given: /// ```python /// # comment /// /// class Class: /// ... /// ``` /// /// While `leading_comments` will preserve the existing empty line, this builder will insert an /// additional empty line before the comment. pub(crate) fn empty_lines_after_leading_comments( comments: &[SourceComment], ) -> FormatEmptyLinesAfterLeadingComments<'_> { FormatEmptyLinesAfterLeadingComments { comments } } #[derive(Copy, Clone, Debug)] pub(crate) struct FormatEmptyLinesAfterLeadingComments<'a> { /// The leading comments of the node. comments: &'a [SourceComment], } impl Format<PyFormatContext<'_>> for FormatEmptyLinesAfterLeadingComments<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext>) -> FormatResult<()> { if let Some(comment) = self .comments .iter() .rev() .find(|comment| comment.line_position().is_own_line()) { // Black has different rules for stub vs. non-stub and top level vs. indented let empty_lines = match (f.options().source_type(), f.context().node_level()) { (PySourceType::Stub, NodeLevel::TopLevel(_)) => 1, (PySourceType::Stub, _) => 0, (_, NodeLevel::TopLevel(_)) => 2, (_, _) => 1, }; let actual = lines_after(comment.end(), f.context().source()).saturating_sub(1); // If there are no empty lines, keep the comment tight to the node. if actual == 0 { return Ok(()); } // If there are more than enough empty lines already, `leading_comments` will // trim them as necessary. if actual >= empty_lines { return Ok(()); } for _ in actual..empty_lines { empty_line().fmt(f)?; } } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/comments/node_key.rs
crates/ruff_python_formatter/src/comments/node_key.rs
use ruff_python_ast::AnyNodeRef; use std::fmt::{Debug, Formatter}; use std::hash::{Hash, Hasher}; /// Used as key into the [`MultiMap`](super::MultiMap) storing the comments per node by /// [`Comments`](super::Comments). /// /// Implements equality and hashing based on the address of the [`AnyNodeRef`] to get fast and cheap /// hashing/equality comparison. #[derive(Copy, Clone)] pub(super) struct NodeRefEqualityKey<'a> { node: AnyNodeRef<'a>, } impl<'a> NodeRefEqualityKey<'a> { /// Creates a key for a node reference. pub(super) const fn from_ref(node: AnyNodeRef<'a>) -> Self { Self { node } } /// Returns the underlying node. pub(super) fn node(&self) -> AnyNodeRef<'_> { self.node } } impl Debug for NodeRefEqualityKey<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { self.node.fmt(f) } } impl PartialEq for NodeRefEqualityKey<'_> { fn eq(&self, other: &Self) -> bool { self.node.ptr_eq(other.node) } } impl Eq for NodeRefEqualityKey<'_> {} impl Hash for NodeRefEqualityKey<'_> { fn hash<H: Hasher>(&self, state: &mut H) { self.node.as_ptr().hash(state); } } impl<'a> From<AnyNodeRef<'a>> for NodeRefEqualityKey<'a> { fn from(value: AnyNodeRef<'a>) -> Self { NodeRefEqualityKey::from_ref(value) } } #[cfg(test)] mod tests { use crate::comments::node_key::NodeRefEqualityKey; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::AtomicNodeIndex; use ruff_python_ast::StmtContinue; use ruff_text_size::TextRange; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; fn hash(key: NodeRefEqualityKey) -> u64 { let mut h = DefaultHasher::default(); key.hash(&mut h); h.finish() } #[test] fn equality() { let continue_statement = StmtContinue { range: TextRange::default(), node_index: AtomicNodeIndex::NONE, }; let ref_a = NodeRefEqualityKey::from_ref(AnyNodeRef::from(&continue_statement)); let ref_b = NodeRefEqualityKey::from_ref(AnyNodeRef::from(&continue_statement)); assert_eq!(ref_a, ref_b); assert_eq!(hash(ref_a), hash(ref_b)); } #[test] fn inequality() { let continue_statement = StmtContinue { range: TextRange::default(), node_index: AtomicNodeIndex::NONE, }; let boxed = Box::new(continue_statement.clone()); let ref_a = NodeRefEqualityKey::from_ref(AnyNodeRef::from(&continue_statement)); let ref_b = NodeRefEqualityKey::from_ref(AnyNodeRef::from(boxed.as_ref())); assert_ne!(ref_a, ref_b); assert_ne!(hash(ref_a), hash(ref_b)); } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/module/mod_module.rs
crates/ruff_python_formatter/src/module/mod_module.rs
use ruff_formatter::write; use ruff_python_ast::ModModule; use ruff_python_trivia::lines_after; use crate::FormatNodeRule; use crate::prelude::*; use crate::statement::suite::SuiteKind; #[derive(Default)] pub struct FormatModModule; impl FormatNodeRule<ModModule> for FormatModModule { fn fmt_fields(&self, item: &ModModule, f: &mut PyFormatter) -> FormatResult<()> { let ModModule { range, body, node_index: _, } = item; if body.is_empty() { // Only preserve an empty line if the source contains an empty line too. if !f.context().comments().has_leading(item) && lines_after(range.start(), f.context().source()) != 0 { empty_line().fmt(f) } else { Ok(()) } } else { write!( f, [ body.format().with_options(SuiteKind::TopLevel), // Trailing newline at the end of the file hard_line_break() ] ) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/module/mod_expression.rs
crates/ruff_python_formatter/src/module/mod_expression.rs
use ruff_python_ast::ModExpression; use crate::prelude::*; #[derive(Default)] pub struct FormatModExpression; impl FormatNodeRule<ModExpression> for FormatModExpression { fn fmt_fields(&self, item: &ModExpression, f: &mut PyFormatter) -> FormatResult<()> { let ModExpression { body, range: _, node_index: _, } = item; body.format().fmt(f) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/module/mod.rs
crates/ruff_python_formatter/src/module/mod.rs
use ruff_formatter::{FormatOwnedWithRule, FormatRefWithRule}; use ruff_python_ast::Mod; use crate::prelude::*; pub(crate) mod mod_expression; pub(crate) mod mod_module; #[derive(Default)] pub struct FormatMod; impl FormatRule<Mod, PyFormatContext<'_>> for FormatMod { fn fmt(&self, item: &Mod, f: &mut PyFormatter) -> FormatResult<()> { match item { Mod::Module(x) => x.format().fmt(f), Mod::Expression(x) => x.format().fmt(f), } } } impl<'ast> AsFormat<PyFormatContext<'ast>> for Mod { type Format<'a> = FormatRefWithRule<'a, Mod, FormatMod, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatMod) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for Mod { type Format = FormatOwnedWithRule<Mod, FormatMod, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatMod) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_match_star.rs
crates/ruff_python_formatter/src/pattern/pattern_match_star.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::PatternMatchStar; use crate::comments::dangling_comments; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternMatchStar; impl FormatNodeRule<PatternMatchStar> for FormatPatternMatchStar { fn fmt_fields(&self, item: &PatternMatchStar, f: &mut PyFormatter) -> FormatResult<()> { let PatternMatchStar { name, .. } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); write!(f, [token("*"), dangling_comments(dangling)])?; if let Some(name) = name { write!(f, [name.format()]) } else { write!(f, [token("_")]) } } } impl NeedsParentheses for PatternMatchStar { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { // Doesn't matter what we return here because starred patterns can never be used // outside a sequence pattern. OptionalParentheses::Never } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_match_value.rs
crates/ruff_python_formatter/src/pattern/pattern_match_value.rs
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::PatternMatchValue; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses, Parentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternMatchValue; impl FormatNodeRule<PatternMatchValue> for FormatPatternMatchValue { fn fmt_fields(&self, item: &PatternMatchValue, f: &mut PyFormatter) -> FormatResult<()> { let PatternMatchValue { value, range: _, node_index: _, } = item; value.format().with_options(Parentheses::Never).fmt(f) } } impl NeedsParentheses for PatternMatchValue { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { self.value.needs_parentheses(parent, context) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_match_or.rs
crates/ruff_python_formatter/src/pattern/pattern_match_or.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::PatternMatchOr; use crate::comments::leading_comments; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, in_parentheses_only_group, in_parentheses_only_soft_line_break_or_space, }; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternMatchOr; impl FormatNodeRule<PatternMatchOr> for FormatPatternMatchOr { fn fmt_fields(&self, item: &PatternMatchOr, f: &mut PyFormatter) -> FormatResult<()> { let PatternMatchOr { range: _, node_index: _, patterns, } = item; let inner = format_with(|f: &mut PyFormatter| { let mut patterns = patterns.iter(); let comments = f.context().comments().clone(); let Some(first) = patterns.next() else { return Ok(()); }; first.format().fmt(f)?; for pattern in patterns { let leading_value_comments = comments.leading(pattern); // Format the expressions leading comments **before** the operator if leading_value_comments.is_empty() { write!(f, [in_parentheses_only_soft_line_break_or_space()])?; } else { write!( f, [hard_line_break(), leading_comments(leading_value_comments)] )?; } write!(f, [token("|"), space(), pattern.format()])?; } Ok(()) }); in_parentheses_only_group(&inner).fmt(f) } } impl NeedsParentheses for PatternMatchOr { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Multiline } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_match_class.rs
crates/ruff_python_formatter/src/pattern/pattern_match_class.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::PatternMatchClass; use crate::comments::dangling_comments; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternMatchClass; impl FormatNodeRule<PatternMatchClass> for FormatPatternMatchClass { fn fmt_fields(&self, item: &PatternMatchClass, f: &mut PyFormatter) -> FormatResult<()> { let PatternMatchClass { range: _, node_index: _, cls, arguments, } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); write!( f, [ cls.format(), dangling_comments(dangling), arguments.format() ] ) } } impl NeedsParentheses for PatternMatchClass { fn needs_parentheses( &self, _parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { // If there are any comments outside of the class parentheses, break: // ```python // case ( // Pattern // # dangling // (...) // ): ... // ``` if context.comments().has_dangling(self) { OptionalParentheses::Always } else { OptionalParentheses::Never } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_arguments.rs
crates/ruff_python_formatter/src/pattern/pattern_arguments.rs
use ruff_formatter::write; use ruff_python_ast::{Pattern, PatternArguments}; use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::expression::parentheses::{Parentheses, empty_parenthesized, parenthesized}; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternArguments; impl FormatNodeRule<PatternArguments> for FormatPatternArguments { fn fmt_fields(&self, item: &PatternArguments, f: &mut PyFormatter) -> FormatResult<()> { // If there are no arguments, all comments are dangling: // ```python // case Point2D( # dangling // # dangling // ) // ``` if item.patterns.is_empty() && item.keywords.is_empty() { let comments = f.context().comments().clone(); let dangling = comments.dangling(item); return write!(f, [empty_parenthesized("(", dangling, ")")]); } let all_arguments = format_with(|f: &mut PyFormatter| { let source = f.context().source(); let mut joiner = f.join_comma_separated(item.end()); match item.patterns.as_slice() { [pattern] if item.keywords.is_empty() => { let parentheses = if is_single_argument_parenthesized(pattern, item.end(), source) { Parentheses::Always } else { // Note: no need to handle opening-parenthesis comments, since // an opening-parenthesis comment implies that the argument is // parenthesized. Parentheses::Never }; joiner.entry(pattern, &pattern.format().with_options(parentheses)); } patterns => { joiner .entries(patterns.iter().map(|pattern| { ( pattern, pattern.format().with_options(Parentheses::Preserve), ) })) .nodes(&item.keywords); } } joiner.finish() }); // If the arguments are non-empty, then a dangling comment indicates a comment on the // same line as the opening parenthesis, e.g.: // ```python // case Point2D( # dangling // ... // ) // ``` let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(item); write!( f, [parenthesized("(", &group(&all_arguments), ")") .with_dangling_comments(dangling_comments)] ) } } /// Returns `true` if the pattern (which is the only argument to a /// [`PatternMatchClass`](ruff_python_ast::PatternMatchClass)) is parenthesized. /// Used to avoid falsely assuming that `x` is parenthesized in cases like: /// ```python /// case Point2D(x): ... /// ``` fn is_single_argument_parenthesized(pattern: &Pattern, call_end: TextSize, source: &str) -> bool { let mut has_seen_r_paren = false; for token in SimpleTokenizer::new(source, TextRange::new(pattern.end(), call_end)).skip_trivia() { match token.kind() { SimpleTokenKind::RParen => { if has_seen_r_paren { return true; } has_seen_r_paren = true; } // Skip over any trailing comma SimpleTokenKind::Comma => continue, _ => { // Passed the arguments break; } } } false }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_match_as.rs
crates/ruff_python_formatter/src/pattern/pattern_match_as.rs
use ruff_formatter::write; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::PatternMatchAs; use crate::comments::dangling_comments; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternMatchAs; impl FormatNodeRule<PatternMatchAs> for FormatPatternMatchAs { fn fmt_fields(&self, item: &PatternMatchAs, f: &mut PyFormatter) -> FormatResult<()> { let PatternMatchAs { range: _, node_index: _, pattern, name, } = item; let comments = f.context().comments().clone(); if let Some(name) = name { if let Some(pattern) = pattern { pattern.format().fmt(f)?; if comments.has_trailing(pattern.as_ref()) { write!(f, [hard_line_break()])?; } else { write!(f, [space()])?; } write!(f, [token("as")])?; let trailing_as_comments = comments.dangling(item); if trailing_as_comments.is_empty() { write!(f, [space()])?; } else if trailing_as_comments .iter() .all(|comment| comment.line_position().is_own_line()) { write!(f, [hard_line_break()])?; } write!(f, [dangling_comments(trailing_as_comments)])?; } name.format().fmt(f) } else { debug_assert!(pattern.is_none()); token("_").fmt(f) } } } impl NeedsParentheses for PatternMatchAs { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { if self.name.is_some() { OptionalParentheses::Multiline } else { OptionalParentheses::BestFit } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/mod.rs
crates/ruff_python_formatter/src/pattern/mod.rs
use ruff_formatter::{FormatOwnedWithRule, FormatRefWithRule, FormatRule, FormatRuleWithOptions}; use ruff_python_ast::{AnyNodeRef, Expr, PatternMatchAs}; use ruff_python_ast::{MatchCase, Pattern}; use ruff_python_trivia::CommentRanges; use ruff_python_trivia::{ BackwardsTokenizer, SimpleToken, SimpleTokenKind, first_non_trivia_token, }; use ruff_text_size::Ranged; use std::cmp::Ordering; use crate::builders::parenthesize_if_expands; use crate::context::{NodeLevel, WithNodeLevel}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, Parentheses, optional_parentheses, parenthesized, }; use crate::prelude::*; use crate::preview::is_avoid_parens_for_long_as_captures_enabled; pub(crate) mod pattern_arguments; pub(crate) mod pattern_keyword; pub(crate) mod pattern_match_as; pub(crate) mod pattern_match_class; pub(crate) mod pattern_match_mapping; pub(crate) mod pattern_match_or; pub(crate) mod pattern_match_sequence; pub(crate) mod pattern_match_singleton; pub(crate) mod pattern_match_star; pub(crate) mod pattern_match_value; #[derive(Copy, Clone, PartialEq, Eq, Default)] pub struct FormatPattern { parentheses: Parentheses, } impl FormatRuleWithOptions<Pattern, PyFormatContext<'_>> for FormatPattern { type Options = Parentheses; fn with_options(mut self, options: Self::Options) -> Self { self.parentheses = options; self } } impl FormatRule<Pattern, PyFormatContext<'_>> for FormatPattern { fn fmt(&self, pattern: &Pattern, f: &mut PyFormatter) -> FormatResult<()> { let format_pattern = format_with(|f| match pattern { Pattern::MatchValue(pattern) => pattern.format().fmt(f), Pattern::MatchSingleton(pattern) => pattern.format().fmt(f), Pattern::MatchSequence(pattern) => pattern.format().fmt(f), Pattern::MatchMapping(pattern) => pattern.format().fmt(f), Pattern::MatchClass(pattern) => pattern.format().fmt(f), Pattern::MatchStar(pattern) => pattern.format().fmt(f), Pattern::MatchAs(pattern) => pattern.format().fmt(f), Pattern::MatchOr(pattern) => pattern.format().fmt(f), }); let parenthesize = match self.parentheses { Parentheses::Preserve => is_pattern_parenthesized( pattern, f.context().comments().ranges(), f.context().source(), ), Parentheses::Always => true, Parentheses::Never => false, }; if parenthesize { let comments = f.context().comments().clone(); // Any comments on the open parenthesis. // // For example, `# comment` in: // ```python // ( # comment // 1 // ) // ``` let open_parenthesis_comment = comments .leading(pattern) .first() .filter(|comment| comment.line_position().is_end_of_line()); parenthesized("(", &format_pattern, ")") .with_dangling_comments( open_parenthesis_comment .map(std::slice::from_ref) .unwrap_or_default(), ) .fmt(f) } else { format_pattern.fmt(f) } } } impl<'ast> AsFormat<PyFormatContext<'ast>> for Pattern { type Format<'a> = FormatRefWithRule<'a, Pattern, FormatPattern, PyFormatContext<'ast>>; fn format(&self) -> Self::Format<'_> { FormatRefWithRule::new(self, FormatPattern::default()) } } impl<'ast> IntoFormat<PyFormatContext<'ast>> for Pattern { type Format = FormatOwnedWithRule<Pattern, FormatPattern, PyFormatContext<'ast>>; fn into_format(self) -> Self::Format { FormatOwnedWithRule::new(self, FormatPattern::default()) } } fn is_pattern_parenthesized( pattern: &Pattern, comment_ranges: &CommentRanges, contents: &str, ) -> bool { // First test if there's a closing parentheses because it tends to be cheaper. if matches!( first_non_trivia_token(pattern.end(), contents), Some(SimpleToken { kind: SimpleTokenKind::RParen, .. }) ) { matches!( BackwardsTokenizer::up_to(pattern.start(), contents, comment_ranges) .skip_trivia() .next(), Some(SimpleToken { kind: SimpleTokenKind::LParen, .. }) ) } else { false } } impl NeedsParentheses for Pattern { fn needs_parentheses( &self, parent: AnyNodeRef, context: &PyFormatContext, ) -> OptionalParentheses { match self { Pattern::MatchValue(pattern) => pattern.needs_parentheses(parent, context), Pattern::MatchSingleton(pattern) => pattern.needs_parentheses(parent, context), Pattern::MatchSequence(pattern) => pattern.needs_parentheses(parent, context), Pattern::MatchMapping(pattern) => pattern.needs_parentheses(parent, context), Pattern::MatchClass(pattern) => pattern.needs_parentheses(parent, context), Pattern::MatchStar(pattern) => pattern.needs_parentheses(parent, context), Pattern::MatchAs(pattern) => pattern.needs_parentheses(parent, context), Pattern::MatchOr(pattern) => pattern.needs_parentheses(parent, context), } } } pub(crate) fn maybe_parenthesize_pattern<'a>( pattern: &'a Pattern, case: &'a MatchCase, ) -> MaybeParenthesizePattern<'a> { MaybeParenthesizePattern { pattern, case } } #[derive(Debug)] pub(crate) struct MaybeParenthesizePattern<'a> { pattern: &'a Pattern, case: &'a MatchCase, } impl Format<PyFormatContext<'_>> for MaybeParenthesizePattern<'_> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { let MaybeParenthesizePattern { pattern, case } = self; let comments = f.context().comments(); let pattern_comments = comments.leading_dangling_trailing(*pattern); // If the pattern has comments, we always want to preserve the parentheses. This also // ensures that we correctly handle parenthesized comments, and don't need to worry about // them in the implementation below. if pattern_comments.has_leading() || pattern_comments.has_trailing_own_line() { return pattern.format().with_options(Parentheses::Always).fmt(f); } let needs_parentheses = pattern.needs_parentheses(AnyNodeRef::from(*case), f.context()); match needs_parentheses { OptionalParentheses::Always => { pattern.format().with_options(Parentheses::Always).fmt(f) } OptionalParentheses::Never => pattern.format().with_options(Parentheses::Never).fmt(f), OptionalParentheses::Multiline => { if can_pattern_omit_optional_parentheses(pattern, f.context()) { optional_parentheses(&pattern.format().with_options(Parentheses::Never)).fmt(f) } else { parenthesize_if_expands(&pattern.format().with_options(Parentheses::Never)) .fmt(f) } } OptionalParentheses::BestFit => { if pattern_comments.has_trailing() { pattern.format().with_options(Parentheses::Always).fmt(f) } else { // The group id is necessary because the nested expressions may reference it. let group_id = f.group_id("optional_parentheses"); let f = &mut WithNodeLevel::new(NodeLevel::Expression(Some(group_id)), f); best_fit_parenthesize(&pattern.format().with_options(Parentheses::Never)) .with_group_id(Some(group_id)) .fmt(f) } } } } } /// This function is very similar to /// [`can_omit_optional_parentheses`](crate::expression::can_omit_optional_parentheses) /// with the only difference that it is for patterns and not expressions. /// /// The base idea of the omit optional parentheses layout is to prefer using parentheses of sub-patterns /// when splitting the pattern over introducing new patterns. For example, prefer splitting the sequence pattern in /// `a | [b, c]` over splitting before the `|` operator. /// /// The layout is only applied when the parenthesized pattern is the first or last item in the pattern. /// For example, the layout isn't used for `a | [b, c] | d` because that would look weird. pub(crate) fn can_pattern_omit_optional_parentheses( pattern: &Pattern, context: &PyFormatContext, ) -> bool { let mut visitor = CanOmitOptionalParenthesesVisitor::default(); visitor.visit_pattern(pattern, context); if !visitor.any_parenthesized_expressions { // Only use the more complex IR if there's a parenthesized pattern that can be split before // splitting other patterns. E.g. split the sequence pattern before the string literal `"a" "b" | [a, b, c, d]`. false } else if visitor.max_precedence_count > 1 { false } else { // It's complicated fn has_parentheses_and_is_non_empty(pattern: &Pattern, context: &PyFormatContext) -> bool { let has_own_non_empty = match pattern { Pattern::MatchValue(_) | Pattern::MatchSingleton(_) | Pattern::MatchStar(_) | Pattern::MatchOr(_) => false, Pattern::MatchAs(PatternMatchAs { pattern, .. }) => match pattern { Some(pattern) => { is_avoid_parens_for_long_as_captures_enabled(context) && has_parentheses_and_is_non_empty(pattern, context) } None => false, }, Pattern::MatchSequence(sequence) => { !sequence.patterns.is_empty() || context.comments().has_dangling(pattern) } Pattern::MatchMapping(mapping) => { !mapping.patterns.is_empty() || context.comments().has_dangling(pattern) } Pattern::MatchClass(class) => !class.arguments.patterns.is_empty(), }; if has_own_non_empty { true } else { // If the pattern has no own parentheses or it is empty (e.g. ([])), check for surrounding parentheses (that should be preserved). is_pattern_parenthesized(pattern, context.comments().ranges(), context.source()) } } visitor .last .is_some_and(|last| has_parentheses_and_is_non_empty(last, context)) || visitor .first .pattern() .is_some_and(|first| has_parentheses_and_is_non_empty(first, context)) } } #[derive(Debug, Default)] struct CanOmitOptionalParenthesesVisitor<'input> { max_precedence: OperatorPrecedence, max_precedence_count: usize, any_parenthesized_expressions: bool, last: Option<&'input Pattern>, first: First<'input>, } impl<'a> CanOmitOptionalParenthesesVisitor<'a> { fn visit_pattern(&mut self, pattern: &'a Pattern, context: &PyFormatContext) { match pattern { Pattern::MatchSequence(_) | Pattern::MatchMapping(_) => { self.any_parenthesized_expressions = true; } Pattern::MatchValue(value) => match &*value.value { Expr::StringLiteral(_) | Expr::BytesLiteral(_) | // F-strings are allowed according to python's grammar but fail with a syntax error at runtime. // That's why we need to support them for formatting. Expr::FString(_) | Expr::TString(_)| Expr::NumberLiteral(_) | Expr::Attribute(_) | Expr::UnaryOp(_) => { // require no state update other than visit_pattern does. } // `case 4+3j:` or `case 4-3j: // Cannot contain arbitrary expressions. Limited to complex numbers. Expr::BinOp(_) => { self.update_max_precedence(OperatorPrecedence::Additive, 1); } _ => { debug_assert!( false, "Unsupported expression in pattern match value: {:?}", value.value ); } }, Pattern::MatchClass(_) => { self.any_parenthesized_expressions = true; // The pattern doesn't start with a parentheses pattern, but with the class's identifier. self.first.set_if_none(First::Token); } Pattern::MatchAs(PatternMatchAs { pattern, .. }) => { if let Some(pattern) = pattern && is_avoid_parens_for_long_as_captures_enabled(context) { self.visit_sub_pattern(pattern, context); } } Pattern::MatchStar(_) | Pattern::MatchSingleton(_) => {} Pattern::MatchOr(or_pattern) => { self.update_max_precedence( OperatorPrecedence::Or, or_pattern.patterns.len().saturating_sub(1), ); for pattern in &or_pattern.patterns { self.visit_sub_pattern(pattern, context); } } } } fn visit_sub_pattern(&mut self, pattern: &'a Pattern, context: &PyFormatContext) { self.last = Some(pattern); // Rule only applies for non-parenthesized patterns. if is_pattern_parenthesized(pattern, context.comments().ranges(), context.source()) { self.any_parenthesized_expressions = true; } else { self.visit_pattern(pattern, context); } self.first.set_if_none(First::Pattern(pattern)); } fn update_max_precedence(&mut self, precedence: OperatorPrecedence, count: usize) { match self.max_precedence.cmp(&precedence) { Ordering::Less => { self.max_precedence_count = count; self.max_precedence = precedence; } Ordering::Equal => { self.max_precedence_count += count; } Ordering::Greater => {} } } } #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Default)] enum OperatorPrecedence { #[default] None, Additive, Or, } #[derive(Copy, Clone, Debug, Default)] enum First<'a> { #[default] None, /// Pattern starts with a non-parentheses token. E.g. `*x` Token, Pattern(&'a Pattern), } impl<'a> First<'a> { #[inline] fn set_if_none(&mut self, first: First<'a>) { if matches!(self, First::None) { *self = first; } } fn pattern(self) -> Option<&'a Pattern> { match self { First::None | First::Token => None, First::Pattern(pattern) => Some(pattern), } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_match_sequence.rs
crates/ruff_python_formatter/src/pattern/pattern_match_sequence.rs
use ruff_formatter::{Format, FormatResult, format_args}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::PatternMatchSequence; use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, empty_parenthesized, optional_parentheses, parenthesized, }; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternMatchSequence; impl FormatNodeRule<PatternMatchSequence> for FormatPatternMatchSequence { fn fmt_fields(&self, item: &PatternMatchSequence, f: &mut PyFormatter) -> FormatResult<()> { let PatternMatchSequence { patterns, range, node_index: _, } = item; let comments = f.context().comments().clone(); let dangling = comments.dangling(item); let sequence_type = SequenceType::from_pattern(item, f.context().source()); match (patterns.as_slice(), sequence_type) { // If the sequence is empty, format the empty parentheses, along with any dangling // comments. ([], SequenceType::Tuple | SequenceType::TupleNoParens) => { return empty_parenthesized("(", dangling, ")").fmt(f); } ([], SequenceType::List) => return empty_parenthesized("[", dangling, "]").fmt(f), // A single-element tuple should always be parenthesized, and the trailing comma // should never cause it to expand. ([elt], SequenceType::Tuple | SequenceType::TupleNoParens) => { return parenthesized("(", &format_args![elt.format(), token(",")], ")") .with_dangling_comments(dangling) .fmt(f); } _ => {} } let items = format_with(|f| { f.join_comma_separated(range.end()) .nodes(patterns.iter()) .finish() }); match sequence_type { SequenceType::Tuple => parenthesized("(", &items, ")") .with_dangling_comments(dangling) .fmt(f), SequenceType::List => parenthesized("[", &items, "]") .with_dangling_comments(dangling) .fmt(f), SequenceType::TupleNoParens => optional_parentheses(&items).fmt(f), } } } impl NeedsParentheses for PatternMatchSequence { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) enum SequenceType { /// A list literal, e.g., `[1, 2, 3]`. List, /// A parenthesized tuple literal, e.g., `(1, 2, 3)`. Tuple, /// A tuple literal without parentheses, e.g., `1, 2, 3`. TupleNoParens, } impl SequenceType { pub(crate) fn from_pattern(pattern: &PatternMatchSequence, source: &str) -> SequenceType { let before_first_pattern = &source[TextRange::new( pattern.start(), pattern .patterns .first() .map(Ranged::start) .unwrap_or(pattern.end()), )]; let after_last_pattern = &source[TextRange::new( pattern.start(), pattern .patterns .first() .map(Ranged::end) .unwrap_or(pattern.end()), )]; if before_first_pattern.starts_with('[') && !after_last_pattern.ends_with(',') { SequenceType::List } else if before_first_pattern.starts_with('(') { // If the pattern is empty, it must be a parenthesized tuple with no members. (This // branch exists to differentiate between a tuple with and without its own parentheses, // but a tuple without its own parentheses must have at least one member.) let Some(elt) = pattern.patterns.first() else { return SequenceType::Tuple; }; // Count the number of open parentheses between the start of the pattern and the first // element, and the number of close parentheses between the first element and its // trailing comma. If the number of open parentheses is greater than the number of close // parentheses, // the pattern is parenthesized. For example, here, we have two parentheses before the // first element, and one after it: // ```python // ((a), b, c) // ``` // // This algorithm successfully avoids false positives for cases like: // ```python // (a), b, c // ``` let open_parentheses_count = SimpleTokenizer::new(source, TextRange::new(pattern.start(), elt.start())) .skip_trivia() .filter(|token| token.kind() == SimpleTokenKind::LParen) .count(); // Count the number of close parentheses. let close_parentheses_count = SimpleTokenizer::new(source, TextRange::new(elt.end(), elt.end())) .skip_trivia() .take_while(|token| token.kind() != SimpleTokenKind::Comma) .filter(|token| token.kind() == SimpleTokenKind::RParen) .count(); if open_parentheses_count > close_parentheses_count { SequenceType::Tuple } else { SequenceType::TupleNoParens } } else { SequenceType::TupleNoParens } } pub(crate) fn is_parenthesized(self) -> bool { matches!(self, SequenceType::List | SequenceType::Tuple) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_match_singleton.rs
crates/ruff_python_formatter/src/pattern/pattern_match_singleton.rs
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::{PatternMatchSingleton, Singleton}; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternMatchSingleton; impl FormatNodeRule<PatternMatchSingleton> for FormatPatternMatchSingleton { fn fmt_fields(&self, item: &PatternMatchSingleton, f: &mut PyFormatter) -> FormatResult<()> { match item.value { Singleton::None => token("None").fmt(f), Singleton::True => token("True").fmt(f), Singleton::False => token("False").fmt(f), } } } impl NeedsParentheses for PatternMatchSingleton { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::BestFit } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_match_mapping.rs
crates/ruff_python_formatter/src/pattern/pattern_match_mapping.rs
use ruff_formatter::{format_args, write}; use ruff_python_ast::AnyNodeRef; use ruff_python_ast::PatternMatchMapping; use ruff_python_ast::{Expr, Identifier, Pattern}; use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange}; use crate::comments::{SourceComment, leading_comments, trailing_comments}; use crate::expression::parentheses::{ NeedsParentheses, OptionalParentheses, empty_parenthesized, parenthesized, }; use crate::prelude::*; #[derive(Default)] pub struct FormatPatternMatchMapping; impl FormatNodeRule<PatternMatchMapping> for FormatPatternMatchMapping { fn fmt_fields(&self, item: &PatternMatchMapping, f: &mut PyFormatter) -> FormatResult<()> { let PatternMatchMapping { keys, patterns, rest, range: _, node_index: _, } = item; debug_assert_eq!(keys.len(), patterns.len()); let comments = f.context().comments().clone(); let dangling = comments.dangling(item); if keys.is_empty() && rest.is_none() { return empty_parenthesized("{", dangling, "}").fmt(f); } // This node supports three kinds of dangling comments. Most of the complexity originates // with the rest pattern (`{**rest}`), since we can have comments around the `**`, but // also, the `**rest` itself is not a node (it's an identifier), so comments that trail it // are _also_ dangling. // // Specifically, we have these three sources of dangling comments: // ```python // { # "open parenthesis comment" // key: pattern, // ** # end-of-line "double star comment" // # own-line "double star comment" // rest # end-of-line "after rest comment" // # own-line "after rest comment" // } // ``` let (open_parenthesis_comments, double_star_comments, after_rest_comments) = if let Some((double_star, rest)) = find_double_star(item, f.context().source()) { let (open_parenthesis_comments, dangling) = dangling.split_at(dangling.partition_point(|comment| { comment.line_position().is_end_of_line() && comment.start() < double_star.start() })); let (double_star_comments, after_rest_comments) = dangling .split_at(dangling.partition_point(|comment| comment.start() < rest.start())); ( open_parenthesis_comments, double_star_comments, after_rest_comments, ) } else { (dangling, [].as_slice(), [].as_slice()) }; let format_pairs = format_with(|f| { let mut joiner = f.join_comma_separated(item.end()); for (key, pattern) in keys.iter().zip(patterns) { let key_pattern_pair = KeyPatternPair { key, pattern }; joiner.entry(&key_pattern_pair, &key_pattern_pair); } if let Some(identifier) = rest { let rest_pattern = RestPattern { identifier, comments: double_star_comments, }; joiner.entry(&rest_pattern, &rest_pattern); } joiner.finish()?; trailing_comments(after_rest_comments).fmt(f) }); parenthesized("{", &format_pairs, "}") .with_dangling_comments(open_parenthesis_comments) .fmt(f) } } impl NeedsParentheses for PatternMatchMapping { fn needs_parentheses( &self, _parent: AnyNodeRef, _context: &PyFormatContext, ) -> OptionalParentheses { OptionalParentheses::Never } } /// A struct to format the `rest` element of a [`PatternMatchMapping`] (e.g., `{**rest}`). #[derive(Debug)] struct RestPattern<'a> { identifier: &'a Identifier, comments: &'a [SourceComment], } impl Ranged for RestPattern<'_> { fn range(&self) -> TextRange { self.identifier.range() } } impl Format<PyFormatContext<'_>> for RestPattern<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { write!( f, [ leading_comments(self.comments), token("**"), self.identifier.format() ] ) } } /// A struct to format a key-pattern pair of a [`PatternMatchMapping`] (e.g., `{key: pattern}`). #[derive(Debug)] struct KeyPatternPair<'a> { key: &'a Expr, pattern: &'a Pattern, } impl Ranged for KeyPatternPair<'_> { fn range(&self) -> TextRange { TextRange::new(self.key.start(), self.pattern.end()) } } impl Format<PyFormatContext<'_>> for KeyPatternPair<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { write!( f, [group(&format_args![ self.key.format(), token(":"), space(), self.pattern.format() ])] ) } } /// Given a [`PatternMatchMapping`], finds the range of the `**` element in the `rest` pattern, /// if it exists. fn find_double_star(pattern: &PatternMatchMapping, source: &str) -> Option<(TextRange, TextRange)> { let PatternMatchMapping { keys: _, patterns, rest, range: _, node_index: _, } = pattern; // If there's no `rest` element, there's no `**`. let rest = rest.as_ref()?; let mut tokenizer = SimpleTokenizer::starts_at(patterns.last().map_or(pattern.start(), Ranged::end), source); let double_star = tokenizer.find(|token| token.kind() == SimpleTokenKind::DoubleStar)?; Some((double_star.range(), rest.range())) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/pattern/pattern_keyword.rs
crates/ruff_python_formatter/src/pattern/pattern_keyword.rs
use crate::prelude::*; use ruff_formatter::write; use ruff_python_ast::PatternKeyword; #[derive(Default)] pub struct FormatPatternKeyword; impl FormatNodeRule<PatternKeyword> for FormatPatternKeyword { fn fmt_fields(&self, item: &PatternKeyword, f: &mut PyFormatter) -> FormatResult<()> { let PatternKeyword { range: _, node_index: _, attr, pattern, } = item; write!(f, [attr.format(), token("="), pattern.format()]) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/other/parameters.rs
crates/ruff_python_formatter/src/other/parameters.rs
use ruff_formatter::{FormatRuleWithOptions, format_args, write}; use ruff_python_ast::{AnyNodeRef, Parameters}; use ruff_python_trivia::{CommentLinePosition, SimpleToken, SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextRange, TextSize}; use crate::comments::{ SourceComment, dangling_comments, dangling_open_parenthesis_comments, leading_comments, leading_node_comments, trailing_comments, }; use crate::context::{NodeLevel, WithNodeLevel}; use crate::expression::parentheses::empty_parenthesized; use crate::prelude::*; #[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] pub enum ParametersParentheses { /// By default, parameters will always preserve their surrounding parentheses. #[default] Preserve, /// Handle special cases where parentheses should never be used. /// /// An example where parentheses are never used for parameters would be with lambda /// expressions. The following is invalid syntax: /// ```python /// lambda (x, y, z): ... /// ``` /// Instead the lambda here should be: /// ```python /// lambda x, y, z: ... /// ``` Never, } #[derive(Default)] pub struct FormatParameters { parentheses: ParametersParentheses, } impl FormatRuleWithOptions<Parameters, PyFormatContext<'_>> for FormatParameters { type Options = ParametersParentheses; fn with_options(mut self, options: Self::Options) -> Self { self.parentheses = options; self } } impl FormatNodeRule<Parameters> for FormatParameters { fn fmt_fields(&self, item: &Parameters, f: &mut PyFormatter) -> FormatResult<()> { let Parameters { range: _, node_index: _, posonlyargs, args, vararg, kwonlyargs, kwarg, } = item; let (slash, star) = find_parameter_separators(f.context().source(), item); let comments = f.context().comments().clone(); let dangling = comments.dangling(item); // First dangling comment: trailing the opening parenthesis, e.g.: // ```python // def f( # comment // x, // y, // z, // ): ... // TODO(charlie): We already identified this comment as such in placement.rs. Consider // labeling it as such. See: https://github.com/astral-sh/ruff/issues/5247. let parenthesis_comments_end = usize::from(dangling.first().is_some_and(|comment| { if comment.line_position().is_end_of_line() { // Ensure that there are no tokens between the open bracket and the comment. let mut lexer = SimpleTokenizer::new( f.context().source(), TextRange::new(item.start(), comment.start()), ) .skip_trivia() .skip_while(|t| { matches!( t.kind(), SimpleTokenKind::LParen | SimpleTokenKind::LBrace | SimpleTokenKind::LBracket ) }); if lexer.next().is_none() { return true; } } false })); // Separate into (dangling comments on the open parenthesis) and (dangling comments on the // argument separators, e.g., `*` or `/`). let (parenthesis_dangling, parameters_dangling) = dangling.split_at(parenthesis_comments_end); let format_inner = format_with(|f: &mut PyFormatter| { let separator = format_with(|f: &mut PyFormatter| { token(",").fmt(f)?; if f.context().node_level().is_parenthesized() { soft_line_break_or_space().fmt(f) } else { space().fmt(f) } }); let mut joiner = f.join_with(separator); let mut last_node: Option<AnyNodeRef> = None; for parameter_with_default in posonlyargs { joiner.entry(&parameter_with_default.format()); last_node = Some(parameter_with_default.into()); } // Second dangling comment: trailing the slash, e.g.: // ```python // def f( // x, // /, # comment // y, // z, // ): ... let slash_comments_end = if posonlyargs.is_empty() { 0 } else { let slash_comments_end = parameters_dangling.partition_point(|comment| { let assignment = assign_argument_separator_comment_placement( slash.as_ref(), star.as_ref(), comment.range(), comment.line_position(), ) .expect("Unexpected dangling comment type in function parameters"); matches!( assignment, ArgumentSeparatorCommentLocation::SlashLeading | ArgumentSeparatorCommentLocation::SlashTrailing ) }); joiner.entry(&CommentsAroundText { text: "/", comments: &parameters_dangling[..slash_comments_end], }); slash_comments_end }; for parameter_with_default in args { joiner.entry(&parameter_with_default.format()); last_node = Some(parameter_with_default.into()); } // kw only args need either a `*args` ahead of them capturing all var args or a `*` // pseudo-argument capturing all fields. We can also have `*args` without any kwargs // afterwards. if let Some(vararg) = vararg { joiner.entry(&format_args![ leading_node_comments(vararg.as_ref()), token("*"), vararg.format() ]); last_node = Some(vararg.as_ref().into()); } else if !kwonlyargs.is_empty() { // Given very strange comment placement, comments here may not actually have been // marked as `StarLeading`/`StarTrailing`, but that's fine since we still produce // a stable formatting in this case // ```python // def f42( // a, // / # 1 // # 2 // , # 3 // # 4 // * # 5 // , # 6 // c, // ): // pass // ``` joiner.entry(&CommentsAroundText { text: "*", comments: &parameters_dangling[slash_comments_end..], }); } for parameter_with_default in kwonlyargs { joiner.entry(&parameter_with_default.format()); last_node = Some(parameter_with_default.into()); } if let Some(kwarg) = kwarg { joiner.entry(&format_args![ leading_node_comments(kwarg.as_ref()), token("**"), kwarg.format() ]); last_node = Some(kwarg.as_ref().into()); } joiner.finish()?; // Functions use the regular magic trailing comma logic, lambdas may or may not have // a trailing comma but it's just preserved without any magic. // ```python // # Add magic trailing comma if its expands // def f(a): pass // # Expands if magic trailing comma setting is respect, otherwise remove the comma // def g(a,): pass // # Never expands // x1 = lambda y: 1 // # Never expands, the comma is always preserved // x2 = lambda y,: 1 // ``` if self.parentheses == ParametersParentheses::Never { // For lambdas (no parentheses), preserve the trailing comma. It doesn't // behave like a magic trailing comma, it's just preserved if has_trailing_comma(item, last_node, f.context().source()) { write!(f, [token(",")])?; } } else { write!(f, [if_group_breaks(&token(","))])?; if f.options().magic_trailing_comma().is_respect() && has_trailing_comma(item, last_node, f.context().source()) { // Make the magic trailing comma expand the group write!(f, [hard_line_break()])?; } } Ok(()) }); let num_parameters = item.len(); if self.parentheses == ParametersParentheses::Never { write!(f, [group(&format_inner), dangling_comments(dangling)]) } else if num_parameters == 0 { let mut f = WithNodeLevel::new(NodeLevel::ParenthesizedExpression, f); // No parameters, format any dangling comments between `()` write!(f, [empty_parenthesized("(", dangling, ")")]) } else if num_parameters == 1 && posonlyargs.is_empty() && kwonlyargs.is_empty() { // If we have a single argument, avoid the inner group, to ensure that we insert a // trailing comma if the outer group breaks. let mut f = WithNodeLevel::new(NodeLevel::ParenthesizedExpression, f); write!( f, [ token("("), dangling_open_parenthesis_comments(parenthesis_dangling), soft_block_indent(&format_inner), token(")") ] ) } else { // Intentionally avoid `parenthesized`, which groups the entire formatted contents. // We want parameters to be grouped alongside return types, one level up, so we // format them "inline" here. let mut f = WithNodeLevel::new(NodeLevel::ParenthesizedExpression, f); write!( f, [ token("("), dangling_open_parenthesis_comments(parenthesis_dangling), soft_block_indent(&group(&format_inner)), token(")") ] ) } } } struct CommentsAroundText<'a> { text: &'static str, comments: &'a [SourceComment], } impl Format<PyFormatContext<'_>> for CommentsAroundText<'_> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { if self.comments.is_empty() { token(self.text).fmt(f) } else { // There might be own line comments in trailing, but those are weird and we can kinda // ignore them // ```python // def f42( // a, // # leading comment (own line) // / # first trailing comment (end-of-line) // # trailing own line comment // , // c, // ): // ``` let (leading, trailing) = self.comments.split_at( self.comments .partition_point(|comment| comment.line_position().is_own_line()), ); write!( f, [ leading_comments(leading), token(self.text), trailing_comments(trailing) ] ) } } } /// `/` and `*` in a function signature /// /// ```text /// def f(arg_a, /, arg_b, *, arg_c): pass /// ^ ^ ^ ^ ^ ^ slash preceding end /// ^ ^ ^ ^ ^ slash (a separator) /// ^ ^ ^ ^ slash following start /// ^ ^ ^ star preceding end /// ^ ^ star (a separator) /// ^ star following start /// ``` #[derive(Debug)] pub(crate) struct ParameterSeparator { /// The end of the last node or separator before this separator pub(crate) preceding_end: TextSize, /// The range of the separator itself pub(crate) separator: TextRange, /// The start of the first node or separator following this separator pub(crate) following_start: TextSize, } /// Finds slash and star in `f(a, /, b, *, c)` or `lambda a, /, b, *, c: 1`. /// /// Returns the location of the slash and star separators, if any. pub(crate) fn find_parameter_separators( contents: &str, parameters: &Parameters, ) -> (Option<ParameterSeparator>, Option<ParameterSeparator>) { // We only compute preceding_end and token location here since following_start depends on the // star location, but the star location depends on slash's position let slash = if let Some(preceding_end) = parameters.posonlyargs.last().map(Ranged::end) { // ```text // def f(a1=1, a2=2, /, a3, a4): pass // ^^^^^^^^^^^ the range (defaults) // def f(a1, a2, /, a3, a4): pass // ^^^^^^^^^^^^ the range (no default) // ``` let range = TextRange::new(preceding_end, parameters.end()); let mut tokens = SimpleTokenizer::new(contents, range).skip_trivia(); let comma = tokens .next() .expect("The function definition can't end here"); debug_assert!(comma.kind() == SimpleTokenKind::Comma, "{comma:?}"); let slash = tokens .next() .expect("The function definition can't end here"); debug_assert!(slash.kind() == SimpleTokenKind::Slash, "{slash:?}"); Some((preceding_end, slash.range)) } else { None }; // If we have a vararg we have a node that the comments attach to let star = if parameters.vararg.is_some() { // When the vararg is present the comments attach there and we don't need to do manual // formatting None } else if let Some(first_keyword_argument) = parameters.kwonlyargs.first() { // Check in that order: // * `f(a, /, b, *, c)` and `f(a=1, /, b=2, *, c)` // * `f(a, /, *, b)` // * `f(*, b)` (else branch) let after_parameters = parameters .args .last() .map(|arg| arg.range.end()) .or(slash.map(|(_, slash)| slash.end())); if let Some(preceding_end) = after_parameters { let range = TextRange::new(preceding_end, parameters.end()); let mut tokens = SimpleTokenizer::new(contents, range).skip_trivia(); let comma = tokens .next() .expect("The function definition can't end here"); debug_assert!(comma.kind() == SimpleTokenKind::Comma, "{comma:?}"); let star = tokens .next() .expect("The function definition can't end here"); debug_assert!(star.kind() == SimpleTokenKind::Star, "{star:?}"); Some(ParameterSeparator { preceding_end, separator: star.range, following_start: first_keyword_argument.start(), }) } else { let mut tokens = SimpleTokenizer::new(contents, parameters.range).skip_trivia(); let lparen_or_star = tokens .next() .expect("The function definition can't end here"); // In a function definition, the first token should always be a `(`; in a lambda // definition, it _can't_ be a `(`. let star = if lparen_or_star.kind == SimpleTokenKind::LParen { tokens .next() .expect("The function definition can't end here") } else { lparen_or_star }; debug_assert!(star.kind() == SimpleTokenKind::Star, "{star:?}"); Some(ParameterSeparator { preceding_end: parameters.start(), separator: star.range, following_start: first_keyword_argument.start(), }) } } else { None }; // Now that we have star, compute how long slash trailing comments can go // Check in that order: // * `f(a, /, b)` // * `f(a, /, *b)` // * `f(a, /, *, b)` // * `f(a, /, *, **b)` // * `f(a, /)` let slash_following_start = parameters .args .first() .map(Ranged::start) .or(parameters.vararg.as_ref().map(|first| first.start())) .or(star.as_ref().map(|star| star.separator.start())) .or(parameters.kwarg.as_deref().map(Ranged::start)) .unwrap_or(parameters.end()); let slash = slash.map(|(preceding_end, slash)| ParameterSeparator { preceding_end, separator: slash, following_start: slash_following_start, }); (slash, star) } /// Locates positional only parameters separator `/` or the keywords only parameters /// separator `*` comments. /// /// ```python /// def test( /// a, /// # Positional only parameters after here /// /, # trailing positional argument comment. /// b, /// ): /// pass /// ``` /// or /// ```python /// def f( /// a="", /// # Keyword only parameters only after here /// *, # trailing keyword argument comment. /// b="", /// ): /// pass /// ``` /// or /// ```python /// def f( /// a, /// # positional only comment, leading /// /, # positional only comment, trailing /// b, /// # keyword only comment, leading /// *, # keyword only comment, trailing /// c, /// ): /// pass /// ``` /// Notably, the following is possible: /// ```python /// def f32( /// a, /// # positional only comment, leading /// /, # positional only comment, trailing /// # keyword only comment, leading /// *, # keyword only comment, trailing /// c, /// ): /// pass /// ``` /// /// ## Background /// /// ```text /// def f(a1, a2): pass /// ^^^^^^ parameters (args) /// ``` /// Use a star to separate keyword only parameters: /// ```text /// def f(a1, a2, *, a3, a4): pass /// ^^^^^^ parameters (args) /// ^^^^^^ keyword only parameters (kwargs) /// ``` /// Use a slash to separate positional only parameters. Note that this changes the parameters left /// of the slash while the star change the parameters right of it: /// ```text /// def f(a1, a2, /, a3, a4): pass /// ^^^^^^ positional only parameters (posonlyargs) /// ^^^^^^ parameters (args) /// ``` /// You can combine both: /// ```text /// def f(a1, a2, /, a3, a4, *, a5, a6): pass /// ^^^^^^ positional only parameters (posonlyargs) /// ^^^^^^ parameters (args) /// ^^^^^^ keyword only parameters (kwargs) /// ``` /// They can all have defaults, meaning that the preceding node ends at the default instead of the /// argument itself: /// ```text /// def f(a1=1, a2=2, /, a3=3, a4=4, *, a5=5, a6=6): pass /// ^ ^ ^ ^ ^ ^ defaults /// ^^^^^^^^^^ positional only parameters (posonlyargs) /// ^^^^^^^^^^ parameters (args) /// ^^^^^^^^^^ keyword only parameters (kwargs) /// ``` /// An especially difficult case is having no regular parameters, so comments from both slash and /// star will attach to either a2 or a3 and the next token is incorrect. /// ```text /// def f(a1, a2, /, *, a3, a4): pass /// ^^^^^^ positional only parameters (posonlyargs) /// ^^^^^^ keyword only parameters (kwargs) /// ``` pub(crate) fn assign_argument_separator_comment_placement( slash: Option<&ParameterSeparator>, star: Option<&ParameterSeparator>, comment_range: TextRange, text_position: CommentLinePosition, ) -> Option<ArgumentSeparatorCommentLocation> { if let Some(ParameterSeparator { preceding_end, separator: slash, following_start, }) = slash { // ```python // def f( // # start too early // a, # not own line // # this is the one // /, # too late (handled later) // b, // ) // ``` if comment_range.start() > *preceding_end && comment_range.start() < slash.start() && text_position.is_own_line() { return Some(ArgumentSeparatorCommentLocation::SlashLeading); } // ```python // def f( // a, // # too early (handled above) // /, # this is the one // # not end-of-line // b, // ) // ``` if comment_range.start() > slash.end() && comment_range.start() < *following_start && text_position.is_end_of_line() { return Some(ArgumentSeparatorCommentLocation::SlashTrailing); } } if let Some(ParameterSeparator { preceding_end, separator: star, following_start, }) = star { // ```python // def f( // # start too early // a, # not own line // # this is the one // *, # too late (handled later) // b, // ) // ``` if comment_range.start() > *preceding_end && comment_range.start() < star.start() && text_position.is_own_line() { return Some(ArgumentSeparatorCommentLocation::StarLeading); } // ```python // def f( // a, // # too early (handled above) // *, # this is the one // # not end-of-line // b, // ) // ``` if comment_range.start() > star.end() && comment_range.start() < *following_start && text_position.is_end_of_line() { return Some(ArgumentSeparatorCommentLocation::StarTrailing); } } None } /// ```python /// def f( /// a, /// # before slash /// /, # after slash /// b, /// # before star /// *, # after star /// c, /// ): /// pass /// ``` #[derive(Debug)] pub(crate) enum ArgumentSeparatorCommentLocation { SlashLeading, SlashTrailing, StarLeading, StarTrailing, } fn has_trailing_comma( parameters: &Parameters, last_node: Option<AnyNodeRef>, source: &str, ) -> bool { // No nodes, no trailing comma let Some(last_node) = last_node else { return false; }; let ends_with_pos_only_argument_separator = !parameters.posonlyargs.is_empty() && parameters.args.is_empty() && parameters.vararg.is_none() && parameters.kwonlyargs.is_empty() && parameters.kwarg.is_none(); let mut tokens = SimpleTokenizer::starts_at(last_node.end(), source).skip_trivia(); // `def a(b, c, /): ... ` // The slash lacks its own node if ends_with_pos_only_argument_separator { let comma = tokens.next(); assert!( matches!( comma, Some(SimpleToken { kind: SimpleTokenKind::Comma, .. }) ), "The last positional only argument must be separated by a `,` from the positional only parameters separator `/` but found '{comma:?}'." ); let slash = tokens.next(); assert!( matches!( slash, Some(SimpleToken { kind: SimpleTokenKind::Slash, .. }) ), "The positional argument separator must be present for a function that has positional only parameters but found '{slash:?}'." ); } tokens .next() .expect("There must be a token after the argument list") .kind() == SimpleTokenKind::Comma }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/other/elif_else_clause.rs
crates/ruff_python_formatter/src/other/elif_else_clause.rs
use ruff_python_ast::ElifElseClause; use crate::prelude::*; use crate::statement::stmt_if::format_elif_else_clause; use crate::statement::suite::SuiteKind; /// Note that this implementation misses the leading newlines before the leading comments because /// it does not have access to the last node of the previous branch. The `StmtIf` therefore doesn't /// call this but `format_elif_else_clause` directly. #[derive(Default)] pub struct FormatElifElseClause; impl FormatNodeRule<ElifElseClause> for FormatElifElseClause { fn fmt_fields(&self, item: &ElifElseClause, f: &mut PyFormatter) -> FormatResult<()> { format_elif_else_clause( item, f, None, SuiteKind::Other { // For stability, we can't insert an empty line if we don't know if the outer suite // also does. last_suite_in_statement: true, }, ) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/other/decorator.rs
crates/ruff_python_formatter/src/other/decorator.rs
use ruff_formatter::write; use ruff_python_ast::Decorator; use crate::comments::SourceComment; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::{has_skip_comment, prelude::*}; #[derive(Default)] pub struct FormatDecorator; impl FormatNodeRule<Decorator> for FormatDecorator { fn fmt_fields(&self, item: &Decorator, f: &mut PyFormatter) -> FormatResult<()> { let Decorator { expression, range: _, node_index: _, } = item; write!( f, [ token("@"), maybe_parenthesize_expression(expression, item, Parenthesize::Optional) ] ) } fn is_suppressed( &self, trailing_comments: &[SourceComment], context: &PyFormatContext, ) -> bool { has_skip_comment(trailing_comments, context.source()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/other/with_item.rs
crates/ruff_python_formatter/src/other/with_item.rs
use ruff_formatter::{FormatRuleWithOptions, write}; use ruff_python_ast::WithItem; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::{ Parentheses, Parenthesize, is_expression_parenthesized, parenthesized, }; use crate::prelude::*; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum WithItemLayout { /// A with item that is the `with`s only context manager and its context expression is parenthesized. /// /// ```python /// with ( /// a + b /// ) as b: /// ... /// ``` /// /// This layout is used independent of the target version. SingleParenthesizedContextManager, /// A with item that is the `with`s only context manager and it has no `target`. /// /// ```python /// with a + b: /// ... /// ``` /// /// In this case, use [`maybe_parenthesize_expression`] to get the same formatting as when /// formatting any other statement with a clause header. /// /// This layout is only used for Python 3.9+. /// /// Be careful that [`Self::SingleParenthesizedContextManager`] and this layout are compatible because /// removing optional parentheses or adding parentheses will make the formatter pick the opposite layout /// the second time the file gets formatted. SingleWithoutTarget, /// This layout is used when the target python version doesn't support parenthesized context managers and /// it's either a single, unparenthesized with item or multiple items. /// /// ```python /// with a + b: /// ... /// /// with a, b: /// ... /// ``` Python38OrOlder { single: bool }, /// A with item where the `with` formatting adds parentheses around all context managers if necessary. /// /// ```python /// with ( /// a, /// b, /// ): pass /// ``` /// /// This layout is generally used when the target version is Python 3.9 or newer, but it is used /// for Python 3.8 if the with item has a leading or trailing comment. /// /// ```python /// with ( /// # leading /// a // ): ... /// ``` ParenthesizedContextManagers { single: bool }, } #[derive(Default)] pub struct FormatWithItem { layout: WithItemLayout, } impl Default for WithItemLayout { fn default() -> Self { WithItemLayout::ParenthesizedContextManagers { single: false } } } impl FormatRuleWithOptions<WithItem, PyFormatContext<'_>> for FormatWithItem { type Options = WithItemLayout; fn with_options(self, options: Self::Options) -> Self { Self { layout: options } } } impl FormatNodeRule<WithItem> for FormatWithItem { fn fmt_fields(&self, item: &WithItem, f: &mut PyFormatter) -> FormatResult<()> { let WithItem { range: _, node_index: _, context_expr, optional_vars, } = item; let comments = f.context().comments().clone(); let trailing_as_comments = comments.dangling(item); // WARNING: The `is_parenthesized` returns false-positives // if the `with` has a single item without a target. // E.g., it returns `true` for `with (a)` even though the parentheses // belong to the with statement and not the expression but it can't determine that. let is_parenthesized = is_expression_parenthesized( context_expr.into(), f.context().comments().ranges(), f.context().source(), ); match self.layout { // Remove the parentheses of the `with_items` if the with statement adds parentheses WithItemLayout::ParenthesizedContextManagers { single } => { // ...except if the with item is parenthesized and it's not the only with item or it has a target. // Then use the context expression as a preferred breaking point. let prefer_breaking_context_expression = (optional_vars.is_some() || !single) && is_parenthesized; if prefer_breaking_context_expression { maybe_parenthesize_expression( context_expr, item, Parenthesize::IfBreaksParenthesizedNested, ) .fmt(f)?; } else { context_expr .format() .with_options(Parentheses::Never) .fmt(f)?; } } WithItemLayout::SingleParenthesizedContextManager | WithItemLayout::SingleWithoutTarget => { write!( f, [maybe_parenthesize_expression( context_expr, item, Parenthesize::IfBreaks )] )?; } WithItemLayout::Python38OrOlder { single } => { let parenthesize = if single || is_parenthesized { Parenthesize::IfBreaks } else { Parenthesize::IfRequired }; write!( f, [maybe_parenthesize_expression( context_expr, item, parenthesize )] )?; } } if let Some(optional_vars) = optional_vars { write!(f, [space(), token("as"), space()])?; if trailing_as_comments.is_empty() { write!(f, [optional_vars.format()])?; } else { write!( f, [parenthesized( "(", &optional_vars.format().with_options(Parentheses::Never), ")", ) .with_dangling_comments(trailing_as_comments)] )?; } } Ok(()) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/other/except_handler_except_handler.rs
crates/ruff_python_formatter/src/other/except_handler_except_handler.rs
use ruff_formatter::FormatRuleWithOptions; use ruff_formatter::write; use ruff_python_ast::{ExceptHandlerExceptHandler, Expr, PythonVersion}; use crate::expression::expr_tuple::TupleParentheses; use crate::expression::maybe_parenthesize_expression; use crate::expression::parentheses::Parenthesize; use crate::prelude::*; use crate::preview::is_remove_parens_around_except_types_enabled; use crate::statement::clause::{ClauseHeader, clause}; use crate::statement::suite::SuiteKind; #[derive(Copy, Clone, Default)] pub(crate) enum ExceptHandlerKind { #[default] Regular, Starred, } #[derive(Default)] pub struct FormatExceptHandlerExceptHandler { pub(crate) except_handler_kind: ExceptHandlerKind, pub(crate) last_suite_in_statement: bool, } impl FormatRuleWithOptions<ExceptHandlerExceptHandler, PyFormatContext<'_>> for FormatExceptHandlerExceptHandler { type Options = FormatExceptHandlerExceptHandler; fn with_options(mut self, options: Self::Options) -> Self { self.except_handler_kind = options.except_handler_kind; self.last_suite_in_statement = options.last_suite_in_statement; self } } impl FormatNodeRule<ExceptHandlerExceptHandler> for FormatExceptHandlerExceptHandler { fn fmt_fields( &self, item: &ExceptHandlerExceptHandler, f: &mut PyFormatter, ) -> FormatResult<()> { let except_handler_kind = self.except_handler_kind; let ExceptHandlerExceptHandler { range: _, node_index: _, type_, name, body, } = item; let comments_info = f.context().comments().clone(); let dangling_comments = comments_info.dangling(item); write!( f, [clause( ClauseHeader::ExceptHandler(item), &format_with(|f: &mut PyFormatter| { write!( f, [ token("except"), match except_handler_kind { ExceptHandlerKind::Regular => None, ExceptHandlerKind::Starred => Some(token("*")), } ] )?; match type_.as_deref() { // For tuples of exception types without an `as` name and on 3.14+, the // parentheses are optional. // // ```py // try: // ... // except BaseException, Exception: # Ok // ... // ``` Some(Expr::Tuple(tuple)) if f.options().target_version() >= PythonVersion::PY314 && is_remove_parens_around_except_types_enabled(f.context()) && name.is_none() => { write!( f, [ space(), tuple.format().with_options(TupleParentheses::NeverPreserve) ] )?; } Some(type_) => { write!( f, [ space(), maybe_parenthesize_expression( type_, item, Parenthesize::IfBreaks ) ] )?; if let Some(name) = name { write!(f, [space(), token("as"), space(), name.format()])?; } } _ => {} } Ok(()) }), dangling_comments, body, SuiteKind::other(self.last_suite_in_statement), )] ) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/other/string_literal.rs
crates/ruff_python_formatter/src/other/string_literal.rs
use ruff_formatter::FormatRuleWithOptions; use ruff_python_ast::StringLiteral; use crate::QuoteStyle; use crate::prelude::*; use crate::string::{StringNormalizer, docstring}; #[derive(Default)] pub struct FormatStringLiteral { layout: StringLiteralKind, } impl FormatRuleWithOptions<StringLiteral, PyFormatContext<'_>> for FormatStringLiteral { type Options = StringLiteralKind; fn with_options(mut self, layout: StringLiteralKind) -> Self { self.layout = layout; self } } /// The kind of a string literal. #[derive(Copy, Clone, Debug, Default)] pub enum StringLiteralKind { /// A normal string literal e.g., `"foo"`. #[default] String, /// A string literal used as a docstring. Docstring, } impl StringLiteralKind { /// Checks if this string literal is a docstring. pub(crate) const fn is_docstring(self) -> bool { matches!(self, StringLiteralKind::Docstring) } } impl FormatNodeRule<StringLiteral> for FormatStringLiteral { fn fmt_fields(&self, item: &StringLiteral, f: &mut PyFormatter) -> FormatResult<()> { let quote_style = f.options().quote_style(); let quote_style = if self.layout.is_docstring() && !quote_style.is_preserve() { // Per PEP 8 and PEP 257, always prefer double quotes for docstrings, // except when using quote-style=preserve QuoteStyle::Double } else { quote_style }; let normalized = StringNormalizer::from_context(f.context()) .with_preferred_quote_style(quote_style) .normalize(item.into()); if self.layout.is_docstring() { docstring::format(&normalized, f) } else { normalized.fmt(f) } } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/other/arguments.rs
crates/ruff_python_formatter/src/other/arguments.rs
use ruff_formatter::{FormatContext, write}; use ruff_python_ast::{ArgOrKeyword, Arguments, Expr, StringFlags, StringLike}; use ruff_python_trivia::{PythonWhitespace, SimpleTokenKind, SimpleTokenizer}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use crate::expression::expr_generator::GeneratorExpParentheses; use crate::expression::is_expression_huggable; use crate::expression::parentheses::{Parentheses, empty_parenthesized, parenthesized}; use crate::other::commas; use crate::prelude::*; use crate::string::StringLikeExtensions; #[derive(Default)] pub struct FormatArguments; impl FormatNodeRule<Arguments> for FormatArguments { fn fmt_fields(&self, item: &Arguments, f: &mut PyFormatter) -> FormatResult<()> { let Arguments { range, args, keywords, node_index: _, } = item; // We have a case with `f()` without any argument, which is a special case because we can // have a comment with no node attachment inside: // ```python // f( // # This call has a dangling comment. // ) // ``` if args.is_empty() && keywords.is_empty() { let comments = f.context().comments().clone(); let dangling = comments.dangling(item); return write!(f, [empty_parenthesized("(", dangling, ")")]); } let all_arguments = format_with(|f: &mut PyFormatter| { let source = f.context().source(); let mut joiner = f.join_comma_separated(range.end()); match args.as_ref() { [arg] if keywords.is_empty() => { match arg { Expr::Generator(generator_exp) => joiner.entry( generator_exp, &generator_exp .format() .with_options(GeneratorExpParentheses::Preserve), ), other => { let parentheses = if is_single_argument_parenthesized(arg, range.end(), source) { Parentheses::Always } else { // Note: no need to handle opening-parenthesis comments, since // an opening-parenthesis comment implies that the argument is // parenthesized. Parentheses::Never }; joiner.entry(other, &other.format().with_options(parentheses)) } }; } _ => { for arg_or_keyword in item.arguments_source_order() { match arg_or_keyword { ArgOrKeyword::Arg(arg) => { joiner.entry(arg, &arg.format()); } ArgOrKeyword::Keyword(keyword) => { joiner.entry(keyword, &keyword.format()); } } } } } joiner.finish() }); // If the arguments are non-empty, then a dangling comment indicates a comment on the // same line as the opening parenthesis, e.g.: // ```python // f( # This call has a dangling comment. // a, // b, // c, // ) let comments = f.context().comments().clone(); let dangling_comments = comments.dangling(item); write!( f, [ // The outer group is for things like: // ```python // get_collection( // hey_this_is_a_very_long_call, // it_has_funny_attributes_asdf_asdf, // too_long_for_the_line, // really=True, // ) // ``` // The inner group is for things like: // ```python // get_collection( // hey_this_is_a_very_long_call, it_has_funny_attributes_asdf_asdf, really=True // ) // ``` parenthesized("(", &group(&all_arguments), ")") .with_hugging(is_arguments_huggable(item, f.context())) .with_dangling_comments(dangling_comments) ] ) } } fn is_single_argument_parenthesized(argument: &Expr, call_end: TextSize, source: &str) -> bool { let mut has_seen_r_paren = false; for token in SimpleTokenizer::new(source, TextRange::new(argument.end(), call_end)).skip_trivia() { match token.kind() { SimpleTokenKind::RParen => { if has_seen_r_paren { return true; } has_seen_r_paren = true; } // Skip over any trailing comma SimpleTokenKind::Comma => continue, _ => { // Passed the arguments break; } } } false } /// Returns `true` if the arguments can hug directly to the enclosing parentheses in the call, as /// in Black's `hug_parens_with_braces_and_square_brackets` preview style behavior. /// /// For example, in preview style, given: /// ```python /// func([1, 2, 3,]) /// ``` /// /// We want to format it as: /// ```python /// func([ /// 1, /// 2, /// 3, /// ]) /// ``` /// /// As opposed to: /// ```python /// func( /// [ /// 1, /// 2, /// 3, /// ] /// ) /// ``` /// /// Hugging should only be applied to single-argument collections, like lists, or starred versions /// of those collections. fn is_arguments_huggable(arguments: &Arguments, context: &PyFormatContext) -> bool { // Find the lone argument or `**kwargs` keyword. let arg = match (arguments.args.as_ref(), arguments.keywords.as_ref()) { ([arg], []) => arg, ([], [keyword]) if keyword.arg.is_none() && !context.comments().has(keyword) => { &keyword.value } _ => return false, }; // If the expression itself isn't huggable, then we can't hug it. if !(is_expression_huggable(arg, context) || StringLike::try_from(arg) .is_ok_and(|string| is_huggable_string_argument(string, arguments, context))) { return false; } // If the expression has leading or trailing comments, then we can't hug it. let comments = context.comments().leading_dangling_trailing(arg); if comments.has_leading() || comments.has_trailing() { return false; } let options = context.options(); // If the expression has a trailing comma, then we can't hug it. if options.magic_trailing_comma().is_respect() && commas::has_magic_trailing_comma(TextRange::new(arg.end(), arguments.end()), context) { return false; } true } /// Returns `true` if `string` is a multiline string that is not implicitly concatenated and there's no /// newline between the opening parentheses of arguments and the quotes of the string: /// /// ```python /// # Hug this string /// call("""test /// multiline""") /// /// # Don't hug because there's a newline between the opening parentheses and the quotes: /// call( /// """" /// test /// """" /// ) /// ``` fn is_huggable_string_argument( string: StringLike, arguments: &Arguments, context: &PyFormatContext, ) -> bool { if string.is_implicit_concatenated() || !string.is_multiline(context) || !string .parts() .next() .is_some_and(|part| part.flags().is_triple_quoted()) { return false; } let between_parens_range = TextRange::new(arguments.start() + '('.text_len(), string.start()); let between_parens = &context.source()[between_parens_range]; !between_parens.trim_whitespace_end().ends_with(['\n', '\r']) }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false
astral-sh/ruff
https://github.com/astral-sh/ruff/blob/8464aca795bc3580ca15fcb52b21616939cea9a9/crates/ruff_python_formatter/src/other/f_string.rs
crates/ruff_python_formatter/src/other/f_string.rs
use super::interpolated_string_element::FormatInterpolatedStringElement; use crate::other::interpolated_string::{InterpolatedStringContext, InterpolatedStringLayout}; use crate::prelude::*; use crate::string::{StringNormalizer, StringQuotes}; use ruff_formatter::write; use ruff_python_ast::{FString, StringFlags}; /// Formats an f-string which is part of a larger f-string expression. /// /// For example, this would be used to format the f-string part in `"foo" f"bar {x}"` /// or the standalone f-string in `f"foo {x} bar"`. #[derive(Default)] pub struct FormatFString; impl FormatNodeRule<FString> for FormatFString { fn fmt_fields(&self, item: &FString, f: &mut PyFormatter) -> FormatResult<()> { let normalizer = StringNormalizer::from_context(f.context()); let string_kind = normalizer.choose_quotes(item.into()).flags(); let context = InterpolatedStringContext::new( string_kind, InterpolatedStringLayout::from_interpolated_string_elements( &item.elements, f.context().source(), ), ); // Starting prefix and quote let quotes = StringQuotes::from(string_kind); write!(f, [string_kind.prefix(), quotes])?; for element in &item.elements { FormatInterpolatedStringElement::new(element, context).fmt(f)?; } // Ending quote quotes.fmt(f) } }
rust
MIT
8464aca795bc3580ca15fcb52b21616939cea9a9
2026-01-04T15:31:59.413821Z
false