Move is_tuple_parenthesized from the formatter to ruff_python_ast (#9533)

This allows it to be used in the linter as well as the formatter. It
will be useful in #9474
This commit is contained in:
Alex Waygood 2024-01-15 16:10:40 +00:00 committed by GitHub
parent 64aac5d526
commit a1e65a92bd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 38 additions and 40 deletions

View file

@ -8,6 +8,7 @@ use std::slice::{Iter, IterMut};
use itertools::Itertools;
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::{int, LiteralExpressionRef};
@ -1801,6 +1802,37 @@ impl From<ExprTuple> for Expr {
}
}
impl ExprTuple {
/// Return `true` if a tuple is parenthesized in the source code.
pub fn is_parenthesized(&self, source: &str) -> bool {
let Some(elt) = self.elts.first() else {
return true;
};
// Count the number of open parentheses between the start of the tuple and the first element.
let open_parentheses_count =
SimpleTokenizer::new(source, TextRange::new(self.start(), elt.start()))
.skip_trivia()
.filter(|token| token.kind() == SimpleTokenKind::LParen)
.count();
if open_parentheses_count == 0 {
return false;
}
// Count the number of parentheses between the end of the first element and its trailing comma.
let close_parentheses_count =
SimpleTokenizer::new(source, TextRange::new(elt.end(), self.end()))
.skip_trivia()
.take_while(|token| token.kind() != SimpleTokenKind::Comma)
.filter(|token| token.kind() == SimpleTokenKind::RParen)
.count();
// If the number of open parentheses is greater than the number of close parentheses, the tuple
// is parenthesized.
open_parentheses_count > close_parentheses_count
}
}
/// See also [Slice](https://docs.python.org/3/library/ast.html#ast.Slice)
#[derive(Clone, Debug, PartialEq)]
pub struct ExprSlice {