Add parenthesized flag to ExprTuple and ExprGenerator (#9614)

This commit is contained in:
Micha Reiser 2024-02-26 16:35:20 +01:00 committed by GitHub
parent ab4bd71755
commit 77c5561646
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
65 changed files with 391 additions and 139 deletions

View file

@ -134,6 +134,7 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
elts, elts,
ctx, ctx,
range: _, range: _,
parenthesized: _,
}) })
| Expr::List(ast::ExprList { | Expr::List(ast::ExprList {
elts, elts,
@ -1451,6 +1452,7 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
generators, generators,
elt: _, elt: _,
range: _, range: _,
parenthesized: _,
}, },
) => { ) => {
if checker.enabled(Rule::UnnecessaryListIndexLookup) { if checker.enabled(Rule::UnnecessaryListIndexLookup) {

View file

@ -1007,6 +1007,7 @@ where
elt, elt,
generators, generators,
range: _, range: _,
parenthesized: _,
}) => { }) => {
self.visit_generators(generators); self.visit_generators(generators);
self.visit_expr(elt); self.visit_expr(elt);
@ -1327,6 +1328,7 @@ where
elts, elts,
ctx, ctx,
range: _, range: _,
parenthesized: _,
}) = slice.as_ref() }) = slice.as_ref()
{ {
let mut iter = elts.iter(); let mut iter = elts.iter();

View file

@ -109,6 +109,7 @@ fn type_pattern(elts: Vec<&Expr>) -> Expr {
elts: elts.into_iter().cloned().collect(), elts: elts.into_iter().cloned().collect(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
} }
.into() .into()
} }

View file

@ -173,6 +173,7 @@ pub(crate) fn multiple_starts_ends_with(checker: &mut Checker, expr: &Expr) {
.collect(), .collect(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}); });
let node1 = Expr::Name(ast::ExprName { let node1 = Expr::Name(ast::ExprName {
id: arg_name.into(), id: arg_name.into(),

View file

@ -72,6 +72,7 @@ pub(crate) fn unnecessary_literal_union<'a>(checker: &mut Checker, expr: &'a Exp
elts, elts,
range: _, range: _,
ctx: _, ctx: _,
parenthesized: _,
}) = slice.as_ref() }) = slice.as_ref()
{ {
for expr in elts { for expr in elts {
@ -123,6 +124,7 @@ pub(crate) fn unnecessary_literal_union<'a>(checker: &mut Checker, expr: &'a Exp
elts: literal_exprs.into_iter().cloned().collect(), elts: literal_exprs.into_iter().cloned().collect(),
range: TextRange::default(), range: TextRange::default(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
parenthesized: true,
})), })),
range: TextRange::default(), range: TextRange::default(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
@ -148,6 +150,7 @@ pub(crate) fn unnecessary_literal_union<'a>(checker: &mut Checker, expr: &'a Exp
elts, elts,
range: TextRange::default(), range: TextRange::default(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
parenthesized: true,
})), })),
range: TextRange::default(), range: TextRange::default(),
ctx: ExprContext::Load, ctx: ExprContext::Load,

View file

@ -130,6 +130,7 @@ pub(crate) fn unnecessary_type_union<'a>(checker: &mut Checker, union: &'a Expr)
.collect(), .collect(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
})), })),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
@ -151,6 +152,7 @@ pub(crate) fn unnecessary_type_union<'a>(checker: &mut Checker, union: &'a Expr)
elts: exprs.into_iter().cloned().collect(), elts: exprs.into_iter().cloned().collect(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
})), })),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),

View file

@ -337,6 +337,7 @@ fn check_names(checker: &mut Checker, decorator: &Decorator, expr: &Expr) {
.collect(), .collect(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}); });
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("({})", checker.generator().expr(&node)), format!("({})", checker.generator().expr(&node)),
@ -444,6 +445,7 @@ fn check_names(checker: &mut Checker, decorator: &Decorator, expr: &Expr) {
elts: elts.clone(), elts: elts.clone(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}); });
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement( diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("({})", checker.generator().expr(&node)), format!("({})", checker.generator().expr(&node)),

View file

@ -428,6 +428,7 @@ pub(crate) fn duplicate_isinstance_call(checker: &mut Checker, expr: &Expr) {
.collect(), .collect(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}; };
let node1 = ast::ExprName { let node1 = ast::ExprName {
id: "isinstance".into(), id: "isinstance".into(),
@ -543,6 +544,7 @@ pub(crate) fn compare_with_tuple(checker: &mut Checker, expr: &Expr) {
elts: comparators.into_iter().map(Clone::clone).collect(), elts: comparators.into_iter().map(Clone::clone).collect(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}; };
let node1 = ast::ExprName { let node1 = ast::ExprName {
id: id.into(), id: id.into(),
@ -718,7 +720,7 @@ fn get_short_circuit_edit(
generator.expr(expr) generator.expr(expr)
}; };
Edit::range_replacement( Edit::range_replacement(
if matches!(expr, Expr::Tuple(ast::ExprTuple { elts, ctx: _, range: _}) if !elts.is_empty()) if matches!(expr, Expr::Tuple(ast::ExprTuple { elts, ctx: _, range: _, parenthesized: _}) if !elts.is_empty())
{ {
format!("({content})") format!("({content})")
} else { } else {

View file

@ -382,6 +382,7 @@ fn return_stmt(id: &str, test: &Expr, target: &Expr, iter: &Expr, generator: Gen
range: TextRange::default(), range: TextRange::default(),
}], }],
range: TextRange::default(), range: TextRange::default(),
parenthesized: false,
}; };
let node1 = ast::ExprName { let node1 = ast::ExprName {
id: id.into(), id: id.into(),

View file

@ -305,6 +305,7 @@ fn assignment_targets_from_expr<'a>(
ctx: ExprContext::Store, ctx: ExprContext::Store,
elts, elts,
range: _, range: _,
parenthesized: _,
}) => Box::new( }) => Box::new(
elts.iter() elts.iter()
.flat_map(|elt| assignment_targets_from_expr(elt, dummy_variable_rgx)), .flat_map(|elt| assignment_targets_from_expr(elt, dummy_variable_rgx)),

View file

@ -145,6 +145,7 @@ pub(crate) fn repeated_equality_comparison(checker: &mut Checker, bool_op: &ast:
elts: comparators.iter().copied().cloned().collect(), elts: comparators.iter().copied().cloned().collect(),
range: TextRange::default(), range: TextRange::default(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
parenthesized: true,
})]), })]),
range: bool_op.range(), range: bool_op.range(),
})), })),

View file

@ -127,6 +127,7 @@ fn tuple_diagnostic(checker: &mut Checker, tuple: &ast::ExprTuple, aliases: &[&E
elts: remaining, elts: remaining,
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}; };
format!("({})", checker.generator().expr(&node.into())) format!("({})", checker.generator().expr(&node.into()))
}; };

View file

@ -141,6 +141,7 @@ fn tuple_diagnostic(checker: &mut Checker, tuple: &ast::ExprTuple, aliases: &[&E
elts: remaining, elts: remaining,
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}; };
format!("({})", checker.generator().expr(&node.into())) format!("({})", checker.generator().expr(&node.into()))
}; };

View file

@ -127,6 +127,7 @@ pub(crate) fn non_pep695_type_alias(checker: &mut Checker, stmt: &StmtAnnAssign)
range: TextRange::default(), range: TextRange::default(),
elts: constraints.into_iter().cloned().collect(), elts: constraints.into_iter().cloned().collect(),
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
parenthesized: true,
}))) })))
} }
None => None, None => None,

View file

@ -347,6 +347,7 @@ fn make_suggestion(group: &AppendGroup, generator: Generator) -> String {
elts, elts,
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}; };
// Make `var.extend`. // Make `var.extend`.
// NOTE: receiver is the same for all appends and that's why we can take the first. // NOTE: receiver is the same for all appends and that's why we can take the first.

View file

@ -162,6 +162,7 @@ fn concatenate_expressions(expr: &Expr) -> Option<(Expr, Type)> {
elts: new_elts, elts: new_elts,
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
} }
.into(), .into(),
}; };

View file

@ -116,6 +116,7 @@ pub(crate) fn never_union(checker: &mut Checker, expr: &Expr) {
elts, elts,
ctx: _, ctx: _,
range: _, range: _,
parenthesized: _,
}) = slice.as_ref() }) = slice.as_ref()
else { else {
return; return;
@ -157,6 +158,7 @@ pub(crate) fn never_union(checker: &mut Checker, expr: &Expr) {
elts: rest, elts: rest,
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
})), })),
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),

View file

@ -134,23 +134,23 @@ impl InferredMemberType {
/// single-line tuple literals *can* be unparenthesized. /// single-line tuple literals *can* be unparenthesized.
/// We keep the original AST node around for the /// We keep the original AST node around for the
/// Tuple variant so that this can be queried later. /// Tuple variant so that this can be queried later.
#[derive(Debug)] #[derive(Copy, Clone, Debug)]
pub(super) enum SequenceKind<'a> { pub(super) enum SequenceKind {
List, List,
Set, Set,
Tuple(&'a ast::ExprTuple), Tuple { parenthesized: bool },
} }
impl SequenceKind<'_> { impl SequenceKind {
// N.B. We only need the source code for the Tuple variant here, // N.B. We only need the source code for the Tuple variant here,
// but if you already have a `Locator` instance handy, // but if you already have a `Locator` instance handy,
// getting the source code is very cheap. // getting the source code is very cheap.
fn surrounding_brackets(&self, source: &str) -> (&'static str, &'static str) { fn surrounding_brackets(self) -> (&'static str, &'static str) {
match self { match self {
Self::List => ("[", "]"), Self::List => ("[", "]"),
Self::Set => ("{", "}"), Self::Set => ("{", "}"),
Self::Tuple(ast_node) => { Self::Tuple { parenthesized } => {
if ast_node.is_parenthesized(source) { if parenthesized {
("(", ")") ("(", ")")
} else { } else {
("", "") ("", "")
@ -159,19 +159,19 @@ impl SequenceKind<'_> {
} }
} }
const fn opening_token_for_multiline_definition(&self) -> TokenKind { const fn opening_token_for_multiline_definition(self) -> TokenKind {
match self { match self {
Self::List => TokenKind::Lsqb, Self::List => TokenKind::Lsqb,
Self::Set => TokenKind::Lbrace, Self::Set => TokenKind::Lbrace,
Self::Tuple(_) => TokenKind::Lpar, Self::Tuple { .. } => TokenKind::Lpar,
} }
} }
const fn closing_token_for_multiline_definition(&self) -> TokenKind { const fn closing_token_for_multiline_definition(self) -> TokenKind {
match self { match self {
Self::List => TokenKind::Rsqb, Self::List => TokenKind::Rsqb,
Self::Set => TokenKind::Rbrace, Self::Set => TokenKind::Rbrace,
Self::Tuple(_) => TokenKind::Rpar, Self::Tuple { .. } => TokenKind::Rpar,
} }
} }
} }
@ -217,7 +217,7 @@ impl<'a> SequenceElements<'a> {
/// that can be inserted into the /// that can be inserted into the
/// source code as a `range_replacement` autofix. /// source code as a `range_replacement` autofix.
pub(super) fn sort_single_line_elements_sequence( pub(super) fn sort_single_line_elements_sequence(
kind: &SequenceKind, kind: SequenceKind,
elts: &[ast::Expr], elts: &[ast::Expr],
elements: &[&str], elements: &[&str],
locator: &Locator, locator: &Locator,
@ -225,7 +225,7 @@ pub(super) fn sort_single_line_elements_sequence(
) -> String { ) -> String {
let element_pairs = SequenceElements::new(elements, elts); let element_pairs = SequenceElements::new(elements, elts);
let last_item_index = element_pairs.last_item_index(); let last_item_index = element_pairs.last_item_index();
let (opening_paren, closing_paren) = kind.surrounding_brackets(locator.contents()); let (opening_paren, closing_paren) = kind.surrounding_brackets();
let mut result = String::from(opening_paren); let mut result = String::from(opening_paren);
// We grab the original source-code ranges using `locator.slice()` // We grab the original source-code ranges using `locator.slice()`
// rather than using the expression generator, as this approach allows // rather than using the expression generator, as this approach allows
@ -334,7 +334,7 @@ impl MultilineStringSequenceValue {
/// Return `None` if the analysis fails for whatever reason. /// Return `None` if the analysis fails for whatever reason.
pub(super) fn from_source_range( pub(super) fn from_source_range(
range: TextRange, range: TextRange,
kind: &SequenceKind, kind: SequenceKind,
locator: &Locator, locator: &Locator,
) -> Option<MultilineStringSequenceValue> { ) -> Option<MultilineStringSequenceValue> {
// Parse the multiline string sequence using the raw tokens. // Parse the multiline string sequence using the raw tokens.
@ -486,7 +486,7 @@ impl Ranged for MultilineStringSequenceValue {
/// in the original source code. /// in the original source code.
fn collect_string_sequence_lines( fn collect_string_sequence_lines(
range: TextRange, range: TextRange,
kind: &SequenceKind, kind: SequenceKind,
locator: &Locator, locator: &Locator,
) -> Option<(Vec<StringSequenceLine>, bool)> { ) -> Option<(Vec<StringSequenceLine>, bool)> {
// These first two variables are used for keeping track of state // These first two variables are used for keeping track of state

View file

@ -152,9 +152,13 @@ fn sort_dunder_all(checker: &mut Checker, target: &ast::Expr, node: &ast::Expr)
let (elts, range, kind) = match node { let (elts, range, kind) = match node {
ast::Expr::List(ast::ExprList { elts, range, .. }) => (elts, *range, SequenceKind::List), ast::Expr::List(ast::ExprList { elts, range, .. }) => (elts, *range, SequenceKind::List),
ast::Expr::Tuple(tuple_node @ ast::ExprTuple { elts, range, .. }) => { ast::Expr::Tuple(tuple_node @ ast::ExprTuple { elts, range, .. }) => (
(elts, *range, SequenceKind::Tuple(tuple_node)) elts,
} *range,
SequenceKind::Tuple {
parenthesized: tuple_node.parenthesized,
},
),
_ => return, _ => return,
}; };
@ -166,7 +170,7 @@ fn sort_dunder_all(checker: &mut Checker, target: &ast::Expr, node: &ast::Expr)
let mut diagnostic = Diagnostic::new(UnsortedDunderAll, range); let mut diagnostic = Diagnostic::new(UnsortedDunderAll, range);
if let SortClassification::UnsortedAndMaybeFixable { items } = elts_analysis { if let SortClassification::UnsortedAndMaybeFixable { items } = elts_analysis {
if let Some(fix) = create_fix(range, elts, &items, &kind, checker) { if let Some(fix) = create_fix(range, elts, &items, kind, checker) {
diagnostic.set_fix(fix); diagnostic.set_fix(fix);
} }
} }
@ -187,7 +191,7 @@ fn create_fix(
range: TextRange, range: TextRange,
elts: &[ast::Expr], elts: &[ast::Expr],
string_items: &[&str], string_items: &[&str],
kind: &SequenceKind, kind: SequenceKind,
checker: &Checker, checker: &Checker,
) -> Option<Fix> { ) -> Option<Fix> {
let locator = checker.locator(); let locator = checker.locator();

View file

@ -157,7 +157,9 @@ impl<'a> StringLiteralDisplay<'a> {
} }
} }
ast::Expr::Tuple(tuple_node @ ast::ExprTuple { elts, range, .. }) => { ast::Expr::Tuple(tuple_node @ ast::ExprTuple { elts, range, .. }) => {
let display_kind = DisplayKind::Sequence(SequenceKind::Tuple(tuple_node)); let display_kind = DisplayKind::Sequence(SequenceKind::Tuple {
parenthesized: tuple_node.parenthesized,
});
Self { Self {
elts: Cow::Borrowed(elts), elts: Cow::Borrowed(elts),
range: *range, range: *range,
@ -211,7 +213,7 @@ impl<'a> StringLiteralDisplay<'a> {
(DisplayKind::Sequence(sequence_kind), true) => { (DisplayKind::Sequence(sequence_kind), true) => {
let analyzed_sequence = MultilineStringSequenceValue::from_source_range( let analyzed_sequence = MultilineStringSequenceValue::from_source_range(
self.range(), self.range(),
sequence_kind, *sequence_kind,
locator, locator,
)?; )?;
assert_eq!(analyzed_sequence.len(), self.elts.len()); assert_eq!(analyzed_sequence.len(), self.elts.len());
@ -220,7 +222,7 @@ impl<'a> StringLiteralDisplay<'a> {
// Sorting multiline dicts is unsupported // Sorting multiline dicts is unsupported
(DisplayKind::Dict { .. }, true) => return None, (DisplayKind::Dict { .. }, true) => return None,
(DisplayKind::Sequence(sequence_kind), false) => sort_single_line_elements_sequence( (DisplayKind::Sequence(sequence_kind), false) => sort_single_line_elements_sequence(
sequence_kind, *sequence_kind,
&self.elts, &self.elts,
items, items,
locator, locator,
@ -242,7 +244,7 @@ impl<'a> StringLiteralDisplay<'a> {
/// Python provides for builtin containers. /// Python provides for builtin containers.
#[derive(Debug)] #[derive(Debug)]
enum DisplayKind<'a> { enum DisplayKind<'a> {
Sequence(SequenceKind<'a>), Sequence(SequenceKind),
Dict { values: &'a [ast::Expr] }, Dict { values: &'a [ast::Expr] },
} }

View file

@ -977,6 +977,7 @@ impl<'a> From<&'a ast::Expr> for ComparableExpr<'a> {
elt, elt,
generators, generators,
range: _, range: _,
parenthesized: _,
}) => Self::GeneratorExp(ExprGeneratorExp { }) => Self::GeneratorExp(ExprGeneratorExp {
elt: elt.into(), elt: elt.into(),
generators: generators.iter().map(Into::into).collect(), generators: generators.iter().map(Into::into).collect(),
@ -1072,6 +1073,7 @@ impl<'a> From<&'a ast::Expr> for ComparableExpr<'a> {
elts, elts,
ctx: _, ctx: _,
range: _, range: _,
parenthesized: _,
}) => Self::Tuple(ExprTuple { }) => Self::Tuple(ExprTuple {
elts: elts.iter().map(Into::into).collect(), elts: elts.iter().map(Into::into).collect(),
}), }),

View file

@ -183,6 +183,7 @@ pub fn any_over_expr(expr: &Expr, func: &dyn Fn(&Expr) -> bool) -> bool {
elt, elt,
generators, generators,
range: _, range: _,
parenthesized: _,
}) => { }) => {
any_over_expr(elt, func) any_over_expr(elt, func)
|| generators.iter().any(|generator| { || generators.iter().any(|generator| {
@ -1423,6 +1424,7 @@ pub fn pep_604_union(elts: &[Expr]) -> Expr {
elts: vec![], elts: vec![],
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}), }),
[Expr::Tuple(ast::ExprTuple { elts, .. })] => pep_604_union(elts), [Expr::Tuple(ast::ExprTuple { elts, .. })] => pep_604_union(elts),
[elt] => elt.clone(), [elt] => elt.clone(),
@ -1457,6 +1459,7 @@ pub fn typing_union(elts: &[Expr], binding: String) -> Expr {
elts: vec![], elts: vec![],
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true,
}), }),
[Expr::Tuple(ast::ExprTuple { elts, .. })] => typing_union(elts, binding), [Expr::Tuple(ast::ExprTuple { elts, .. })] => typing_union(elts, binding),
[elt] => elt.clone(), [elt] => elt.clone(),

View file

@ -2430,6 +2430,7 @@ impl AstNode for ast::ExprGeneratorExp {
elt, elt,
generators, generators,
range: _, range: _,
parenthesized: _,
} = self; } = self;
visitor.visit_expr(elt); visitor.visit_expr(elt);
for comprehension in generators { for comprehension in generators {
@ -3256,6 +3257,7 @@ impl AstNode for ast::ExprTuple {
elts, elts,
ctx: _, ctx: _,
range: _, range: _,
parenthesized: _,
} = self; } = self;
for expr in elts { for expr in elts {

View file

@ -8,7 +8,6 @@ use std::slice::{Iter, IterMut};
use itertools::Itertools; use itertools::Itertools;
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange, TextSize}; use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::{int, LiteralExpressionRef}; use crate::{int, LiteralExpressionRef};
@ -842,6 +841,7 @@ pub struct ExprGeneratorExp {
pub range: TextRange, pub range: TextRange,
pub elt: Box<Expr>, pub elt: Box<Expr>,
pub generators: Vec<Comprehension>, pub generators: Vec<Comprehension>,
pub parenthesized: bool,
} }
impl From<ExprGeneratorExp> for Expr { impl From<ExprGeneratorExp> for Expr {
@ -1796,6 +1796,9 @@ pub struct ExprTuple {
pub range: TextRange, pub range: TextRange,
pub elts: Vec<Expr>, pub elts: Vec<Expr>,
pub ctx: ExprContext, pub ctx: ExprContext,
/// Whether the tuple is parenthesized in the source code.
pub parenthesized: bool,
} }
impl From<ExprTuple> for Expr { impl From<ExprTuple> for Expr {
@ -1804,37 +1807,6 @@ 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) /// See also [Slice](https://docs.python.org/3/library/ast.html#ast.Slice)
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct ExprSlice { pub struct ExprSlice {
@ -3911,7 +3883,7 @@ mod tests {
assert_eq!(std::mem::size_of::<ExprDictComp>(), 48); assert_eq!(std::mem::size_of::<ExprDictComp>(), 48);
assert_eq!(std::mem::size_of::<ExprEllipsisLiteral>(), 8); assert_eq!(std::mem::size_of::<ExprEllipsisLiteral>(), 8);
assert_eq!(std::mem::size_of::<ExprFString>(), 48); assert_eq!(std::mem::size_of::<ExprFString>(), 48);
assert_eq!(std::mem::size_of::<ExprGeneratorExp>(), 40); assert_eq!(std::mem::size_of::<ExprGeneratorExp>(), 48);
assert_eq!(std::mem::size_of::<ExprIfExp>(), 32); assert_eq!(std::mem::size_of::<ExprIfExp>(), 32);
assert_eq!(std::mem::size_of::<ExprIpyEscapeCommand>(), 32); assert_eq!(std::mem::size_of::<ExprIpyEscapeCommand>(), 32);
assert_eq!(std::mem::size_of::<ExprLambda>(), 24); assert_eq!(std::mem::size_of::<ExprLambda>(), 24);

View file

@ -441,6 +441,7 @@ pub fn walk_expr<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, expr: &'a Expr) {
elt, elt,
generators, generators,
range: _, range: _,
parenthesized: _,
}) => { }) => {
for comprehension in generators { for comprehension in generators {
visitor.visit_comprehension(comprehension); visitor.visit_comprehension(comprehension);
@ -539,6 +540,7 @@ pub fn walk_expr<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, expr: &'a Expr) {
elts, elts,
ctx, ctx,
range: _, range: _,
parenthesized: _,
}) => { }) => {
for expr in elts { for expr in elts {
visitor.visit_expr(expr); visitor.visit_expr(expr);

View file

@ -428,6 +428,7 @@ pub fn walk_expr<V: Transformer + ?Sized>(visitor: &V, expr: &mut Expr) {
elt, elt,
generators, generators,
range: _, range: _,
parenthesized: _,
}) => { }) => {
for comprehension in generators { for comprehension in generators {
visitor.visit_comprehension(comprehension); visitor.visit_comprehension(comprehension);
@ -528,6 +529,7 @@ pub fn walk_expr<V: Transformer + ?Sized>(visitor: &V, expr: &mut Expr) {
elts, elts,
ctx, ctx,
range: _, range: _,
parenthesized: _,
}) => { }) => {
for expr in elts { for expr in elts {
visitor.visit_expr(expr); visitor.visit_expr(expr);

View file

@ -970,6 +970,7 @@ impl<'a> Generator<'a> {
Expr::GeneratorExp(ast::ExprGeneratorExp { Expr::GeneratorExp(ast::ExprGeneratorExp {
elt, elt,
generators, generators,
parenthesized: _,
range: _, range: _,
}) => { }) => {
self.p("("); self.p("(");
@ -1037,6 +1038,7 @@ impl<'a> Generator<'a> {
elt, elt,
generators, generators,
range: _, range: _,
parenthesized: _,
})], })],
[], [],
) = (arguments.args.as_ref(), arguments.keywords.as_ref()) ) = (arguments.args.as_ref(), arguments.keywords.as_ref())

View file

@ -12,7 +12,6 @@ use ruff_source_file::Locator;
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use crate::comments::visitor::{CommentPlacement, DecoratedComment}; use crate::comments::visitor::{CommentPlacement, DecoratedComment};
use crate::expression::expr_generator_exp::is_generator_parenthesized;
use crate::expression::expr_slice::{assign_comment_in_slice, ExprSliceCommentSection}; use crate::expression::expr_slice::{assign_comment_in_slice, ExprSliceCommentSection};
use crate::other::parameters::{ use crate::other::parameters::{
assign_argument_separator_comment_placement, find_parameter_separators, assign_argument_separator_comment_placement, find_parameter_separators,
@ -315,12 +314,11 @@ fn handle_enclosed_comment<'a>(
| AnyNodeRef::ExprSet(_) | AnyNodeRef::ExprSet(_)
| AnyNodeRef::ExprListComp(_) | AnyNodeRef::ExprListComp(_)
| AnyNodeRef::ExprSetComp(_) => handle_bracketed_end_of_line_comment(comment, locator), | AnyNodeRef::ExprSetComp(_) => handle_bracketed_end_of_line_comment(comment, locator),
AnyNodeRef::ExprTuple(tuple) if tuple.is_parenthesized(locator.contents()) => { AnyNodeRef::ExprTuple(ast::ExprTuple {
handle_bracketed_end_of_line_comment(comment, locator) parenthesized: true,
} ..
AnyNodeRef::ExprGeneratorExp(generator) }) => handle_bracketed_end_of_line_comment(comment, locator),
if is_generator_parenthesized(generator, locator.contents()) => AnyNodeRef::ExprGeneratorExp(generator) if generator.parenthesized => {
{
handle_bracketed_end_of_line_comment(comment, locator) handle_bracketed_end_of_line_comment(comment, locator)
} }
_ => CommentPlacement::Default(comment), _ => CommentPlacement::Default(comment),

View file

@ -1,8 +1,6 @@
use ruff_formatter::{format_args, write, FormatRuleWithOptions}; use ruff_formatter::{format_args, write, FormatRuleWithOptions};
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::AnyNodeRef;
use ruff_python_ast::ExprGeneratorExp; use ruff_python_ast::ExprGeneratorExp;
use ruff_python_trivia::{SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange};
use crate::comments::SourceComment; use crate::comments::SourceComment;
use crate::expression::parentheses::{parenthesized, NeedsParentheses, OptionalParentheses}; use crate::expression::parentheses::{parenthesized, NeedsParentheses, OptionalParentheses};
@ -42,6 +40,7 @@ impl FormatNodeRule<ExprGeneratorExp> for FormatExprGeneratorExp {
range: _, range: _,
elt, elt,
generators, generators,
parenthesized: is_parenthesized,
} = item; } = item;
let joined = format_with(|f| { let joined = format_with(|f| {
@ -55,7 +54,7 @@ impl FormatNodeRule<ExprGeneratorExp> for FormatExprGeneratorExp {
if self.parentheses == GeneratorExpParentheses::Preserve if self.parentheses == GeneratorExpParentheses::Preserve
&& dangling.is_empty() && dangling.is_empty()
&& !is_generator_parenthesized(item, f.context().source()) && !is_parenthesized
{ {
write!( write!(
f, f,
@ -101,37 +100,3 @@ impl NeedsParentheses for ExprGeneratorExp {
} }
} }
} }
/// Return `true` if a generator is parenthesized in the source code.
pub(crate) fn is_generator_parenthesized(generator: &ExprGeneratorExp, source: &str) -> bool {
// Count the number of open parentheses between the start of the generator and the first element.
let open_parentheses_count = SimpleTokenizer::new(
source,
TextRange::new(generator.start(), generator.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 generator and its trailing comma.
let close_parentheses_count = SimpleTokenizer::new(
source,
TextRange::new(
generator.elt.end(),
generator
.generators
.first()
.map_or(generator.end(), Ranged::start),
),
)
.skip_trivia()
.filter(|token| token.kind() == SimpleTokenKind::RParen)
.count();
// If the number of open parentheses is greater than the number of close parentheses, the
// generator is parenthesized.
open_parentheses_count > close_parentheses_count
}

View file

@ -116,6 +116,7 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
elts, elts,
ctx: _, ctx: _,
range: _, range: _,
parenthesized: is_parenthesized,
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
@ -136,7 +137,7 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
return empty_parenthesized("(", dangling, ")").fmt(f); return empty_parenthesized("(", dangling, ")").fmt(f);
} }
[single] => match self.parentheses { [single] => match self.parentheses {
TupleParentheses::Preserve if !item.is_parenthesized(f.context().source()) => { TupleParentheses::Preserve if !is_parenthesized => {
write!(f, [single.format(), token(",")]) write!(f, [single.format(), token(",")])
} }
_ => _ =>
@ -152,7 +153,7 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
// //
// Unlike other expression parentheses, tuple parentheses are part of the range of the // Unlike other expression parentheses, tuple parentheses are part of the range of the
// tuple itself. // tuple itself.
_ if item.is_parenthesized(f.context().source()) _ if *is_parenthesized
&& !(self.parentheses == TupleParentheses::NeverPreserve && !(self.parentheses == TupleParentheses::NeverPreserve
&& dangling.is_empty()) => && dangling.is_empty()) =>
{ {

View file

@ -14,7 +14,6 @@ use ruff_text_size::Ranged;
use crate::builders::parenthesize_if_expands; use crate::builders::parenthesize_if_expands;
use crate::comments::{leading_comments, trailing_comments, LeadingDanglingTrailingComments}; use crate::comments::{leading_comments, trailing_comments, LeadingDanglingTrailingComments};
use crate::context::{NodeLevel, WithNodeLevel}; use crate::context::{NodeLevel, WithNodeLevel};
use crate::expression::expr_generator_exp::is_generator_parenthesized;
use crate::expression::parentheses::{ use crate::expression::parentheses::{
is_expression_parenthesized, optional_parentheses, parenthesized, NeedsParentheses, is_expression_parenthesized, optional_parentheses, parenthesized, NeedsParentheses,
OptionalParentheses, Parentheses, Parenthesize, OptionalParentheses, Parentheses, Parenthesize,
@ -661,15 +660,16 @@ impl<'input> CanOmitOptionalParenthesesVisitor<'input> {
return; return;
} }
Expr::Tuple(tuple) if tuple.is_parenthesized(self.context.source()) => { Expr::Tuple(ast::ExprTuple {
parenthesized: true,
..
}) => {
self.any_parenthesized_expressions = true; self.any_parenthesized_expressions = true;
// The values are always parenthesized, don't visit. // The values are always parenthesized, don't visit.
return; return;
} }
Expr::GeneratorExp(generator) Expr::GeneratorExp(generator) if generator.parenthesized => {
if is_generator_parenthesized(generator, self.context.source()) =>
{
self.any_parenthesized_expressions = true; self.any_parenthesized_expressions = true;
// The values are always parenthesized, don't visit. // The values are always parenthesized, don't visit.
return; return;
@ -1035,11 +1035,7 @@ pub(crate) fn has_own_parentheses(
Some(OwnParentheses::NonEmpty) Some(OwnParentheses::NonEmpty)
} }
Expr::GeneratorExp(generator) Expr::GeneratorExp(generator) if generator.parenthesized => Some(OwnParentheses::NonEmpty),
if is_generator_parenthesized(generator, context.source()) =>
{
Some(OwnParentheses::NonEmpty)
}
// These expressions must contain _some_ child or trivia token in order to be non-empty. // These expressions must contain _some_ child or trivia token in order to be non-empty.
Expr::List(ast::ExprList { elts, .. }) | Expr::Set(ast::ExprSet { elts, .. }) => { Expr::List(ast::ExprList { elts, .. }) | Expr::Set(ast::ExprSet { elts, .. }) => {
@ -1050,7 +1046,12 @@ pub(crate) fn has_own_parentheses(
} }
} }
Expr::Tuple(tuple) if tuple.is_parenthesized(context.source()) => { Expr::Tuple(
tuple @ ast::ExprTuple {
parenthesized: true,
..
},
) => {
if !tuple.elts.is_empty() || context.comments().has_dangling(AnyNodeRef::from(expr)) { if !tuple.elts.is_empty() || context.comments().has_dangling(AnyNodeRef::from(expr)) {
Some(OwnParentheses::NonEmpty) Some(OwnParentheses::NonEmpty)
} else { } else {

View file

@ -3,10 +3,16 @@ use ruff_python_ast::{self as ast, Expr, ExprContext};
pub(crate) fn set_context(expr: Expr, ctx: ExprContext) -> Expr { pub(crate) fn set_context(expr: Expr, ctx: ExprContext) -> Expr {
match expr { match expr {
Expr::Name(ast::ExprName { id, range, .. }) => ast::ExprName { range, id, ctx }.into(), Expr::Name(ast::ExprName { id, range, .. }) => ast::ExprName { range, id, ctx }.into(),
Expr::Tuple(ast::ExprTuple { elts, range, .. }) => ast::ExprTuple { Expr::Tuple(ast::ExprTuple {
elts,
range,
parenthesized: is_parenthesized,
ctx: _,
}) => ast::ExprTuple {
elts: elts.into_iter().map(|elt| set_context(elt, ctx)).collect(), elts: elts.into_iter().map(|elt| set_context(elt, ctx)).collect(),
range, range,
ctx, ctx,
parenthesized: is_parenthesized,
} }
.into(), .into(),

View file

@ -1505,4 +1505,20 @@ u"foo" f"bar {baz} really" u"bar" "no"
let parse_ast = parse_suite(r#"x = "\N{BACKSPACE}another cool trick""#).unwrap(); let parse_ast = parse_suite(r#"x = "\N{BACKSPACE}another cool trick""#).unwrap();
insta::assert_debug_snapshot!(parse_ast); insta::assert_debug_snapshot!(parse_ast);
} }
#[test]
fn test_tuple() {
let parse_ast = parse_suite(
r#"
a,b
(a,b)
()
(a,)
((a,b))
"#
.trim(),
)
.unwrap();
insta::assert_debug_snapshot!(parse_ast);
}
} }

View file

@ -483,7 +483,8 @@ MatchStatement: ast::Stmt = {
ast::ExprTuple { ast::ExprTuple {
elts: vec![subject.into()], elts: vec![subject.into()],
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (tuple_location..tuple_end_location).into() range: (tuple_location..tuple_end_location).into(),
parenthesized: false
}, },
)), )),
cases, cases,
@ -506,7 +507,8 @@ MatchStatement: ast::Stmt = {
ast::ExprTuple { ast::ExprTuple {
elts, elts,
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (tuple_location..tuple_end_location).into() range: (tuple_location..tuple_end_location).into(),
parenthesized: false
}, },
)), )),
cases, cases,
@ -1573,6 +1575,7 @@ SubscriptList: crate::parser::ParenthesizedExpr = {
elts: vec![s1.into()], elts: vec![s1.into()],
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: false
}.into() }.into()
}, },
<location:@L> <elts:TwoOrMoreSep<Subscript, ",">> ","? <end_location:@R> => { <location:@L> <elts:TwoOrMoreSep<Subscript, ",">> ","? <end_location:@R> => {
@ -1581,6 +1584,7 @@ SubscriptList: crate::parser::ParenthesizedExpr = {
elts, elts,
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: false
}.into() }.into()
} }
}; };
@ -1726,7 +1730,12 @@ Atom<Goal>: crate::parser::ParenthesizedExpr = {
} }
} else { } else {
let elts = elts.into_iter().map(ast::Expr::from).collect(); let elts = elts.into_iter().map(ast::Expr::from).collect();
ast::ExprTuple { elts, ctx: ast::ExprContext::Load, range: (location..end_location).into() }.into() ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: (location..end_location).into(),
parenthesized: true
}.into()
} }
}, },
<location:@L> "(" <left:(<OneOrMore<Test<"all">>> ",")?> <mid:NamedOrStarExpr> <right:("," <TestOrStarNamedExpr>)*> <trailing_comma:","?> ")" <end_location:@R> =>? { <location:@L> "(" <left:(<OneOrMore<Test<"all">>> ",")?> <mid:NamedOrStarExpr> <right:("," <TestOrStarNamedExpr>)*> <trailing_comma:","?> ")" <end_location:@R> =>? {
@ -1743,13 +1752,19 @@ Atom<Goal>: crate::parser::ParenthesizedExpr = {
}) })
} else { } else {
let elts = left.into_iter().flatten().chain([mid]).chain(right).map(ast::Expr::from).collect(); let elts = left.into_iter().flatten().chain([mid]).chain(right).map(ast::Expr::from).collect();
Ok(ast::ExprTuple { elts, ctx: ast::ExprContext::Load, range: (location..end_location).into() }.into()) Ok(ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: (location..end_location).into(),
parenthesized: true
}.into())
} }
}, },
<location:@L> "(" ")" <end_location:@R> => ast::ExprTuple { <location:@L> "(" ")" <end_location:@R> => ast::ExprTuple {
elts: Vec::new(), elts: Vec::new(),
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: true
}.into(), }.into(),
<location:@L> "(" <e:YieldExpr> ")" <end_location:@R> => crate::parser::ParenthesizedExpr { <location:@L> "(" <e:YieldExpr> ")" <end_location:@R> => crate::parser::ParenthesizedExpr {
expr: e.into(), expr: e.into(),
@ -1759,6 +1774,7 @@ Atom<Goal>: crate::parser::ParenthesizedExpr = {
elt: Box::new(elt.into()), elt: Box::new(elt.into()),
generators, generators,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: true
}.into(), }.into(),
"(" <location:@L> "**" <e:Expression<"all">> ")" <end_location:@R> =>? { "(" <location:@L> "**" <e:Expression<"all">> ")" <end_location:@R> =>? {
Err(LexicalError::new( Err(LexicalError::new(
@ -1852,7 +1868,12 @@ GenericList<Element>: crate::parser::ParenthesizedExpr = {
} }
} else { } else {
let elts = elts.into_iter().map(ast::Expr::from).collect(); let elts = elts.into_iter().map(ast::Expr::from).collect();
ast::ExprTuple { elts, ctx: ast::ExprContext::Load, range: (location..end_location).into() }.into() ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: (location..end_location).into(),
parenthesized: false
}.into()
} }
} }
} }
@ -1904,7 +1925,8 @@ FunctionArgument: (Option<(TextSize, TextSize, Option<ast::Identifier>)>, ast::E
ast::ExprGeneratorExp { ast::ExprGeneratorExp {
elt: Box::new(elt.into()), elt: Box::new(elt.into()),
generators, generators,
range: (location..end_location).into() range: (location..end_location).into(),
parenthesized: false
} }
), ),
None => elt.into(), None => elt.into(),

View file

@ -1,5 +1,5 @@
// auto-generated: "lalrpop 0.20.0" // auto-generated: "lalrpop 0.20.0"
// sha3: 8c85e4bbac54760ed8be03b56a428d76e14d18e6dbde62b424d0b2b5e8e65dbe // sha3: d64ca7ff27121baee9d7a1b4d0f341932391a365fe75f115987b05bf2aaf538e
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use ruff_python_ast::{self as ast, Int, IpyEscapeKind}; use ruff_python_ast::{self as ast, Int, IpyEscapeKind};
use crate::{ use crate::{
@ -33938,7 +33938,8 @@ fn __action86<
ast::ExprTuple { ast::ExprTuple {
elts: vec![subject.into()], elts: vec![subject.into()],
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (tuple_location..tuple_end_location).into() range: (tuple_location..tuple_end_location).into(),
parenthesized: false
}, },
)), )),
cases, cases,
@ -33982,7 +33983,8 @@ fn __action87<
ast::ExprTuple { ast::ExprTuple {
elts, elts,
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (tuple_location..tuple_end_location).into() range: (tuple_location..tuple_end_location).into(),
parenthesized: false
}, },
)), )),
cases, cases,
@ -36227,6 +36229,7 @@ fn __action208<
elts: vec![s1.into()], elts: vec![s1.into()],
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: false
}.into() }.into()
} }
} }
@ -36249,6 +36252,7 @@ fn __action209<
elts, elts,
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: false
}.into() }.into()
} }
} }
@ -36796,7 +36800,8 @@ fn __action242<
ast::ExprGeneratorExp { ast::ExprGeneratorExp {
elt: Box::new(elt.into()), elt: Box::new(elt.into()),
generators, generators,
range: (location..end_location).into() range: (location..end_location).into(),
parenthesized: false
} }
), ),
None => elt.into(), None => elt.into(),
@ -37049,7 +37054,12 @@ fn __action259<
} }
} else { } else {
let elts = elts.into_iter().map(ast::Expr::from).collect(); let elts = elts.into_iter().map(ast::Expr::from).collect();
ast::ExprTuple { elts, ctx: ast::ExprContext::Load, range: (location..end_location).into() }.into() ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: (location..end_location).into(),
parenthesized: false
}.into()
} }
} }
} }
@ -37103,7 +37113,12 @@ fn __action262<
} }
} else { } else {
let elts = elts.into_iter().map(ast::Expr::from).collect(); let elts = elts.into_iter().map(ast::Expr::from).collect();
ast::ExprTuple { elts, ctx: ast::ExprContext::Load, range: (location..end_location).into() }.into() ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: (location..end_location).into(),
parenthesized: false
}.into()
} }
} }
} }
@ -41292,7 +41307,12 @@ fn __action553<
} }
} else { } else {
let elts = elts.into_iter().map(ast::Expr::from).collect(); let elts = elts.into_iter().map(ast::Expr::from).collect();
ast::ExprTuple { elts, ctx: ast::ExprContext::Load, range: (location..end_location).into() }.into() ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: (location..end_location).into(),
parenthesized: true
}.into()
} }
} }
} }
@ -41327,7 +41347,12 @@ fn __action554<
}) })
} else { } else {
let elts = left.into_iter().flatten().chain([mid]).chain(right).map(ast::Expr::from).collect(); let elts = left.into_iter().flatten().chain([mid]).chain(right).map(ast::Expr::from).collect();
Ok(ast::ExprTuple { elts, ctx: ast::ExprContext::Load, range: (location..end_location).into() }.into()) Ok(ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: (location..end_location).into(),
parenthesized: true
}.into())
} }
} }
} }
@ -41348,6 +41373,7 @@ fn __action555<
elts: Vec::new(), elts: Vec::new(),
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: true
}.into() }.into()
} }
@ -41388,6 +41414,7 @@ fn __action557<
elt: Box::new(elt.into()), elt: Box::new(elt.into()),
generators, generators,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: true
}.into() }.into()
} }
@ -42025,7 +42052,12 @@ fn __action596<
}) })
} else { } else {
let elts = left.into_iter().flatten().chain([mid]).chain(right).map(ast::Expr::from).collect(); let elts = left.into_iter().flatten().chain([mid]).chain(right).map(ast::Expr::from).collect();
Ok(ast::ExprTuple { elts, ctx: ast::ExprContext::Load, range: (location..end_location).into() }.into()) Ok(ast::ExprTuple {
elts,
ctx: ast::ExprContext::Load,
range: (location..end_location).into(),
parenthesized: true
}.into())
} }
} }
} }
@ -42046,6 +42078,7 @@ fn __action597<
elts: Vec::new(), elts: Vec::new(),
ctx: ast::ExprContext::Load, ctx: ast::ExprContext::Load,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: true
}.into() }.into()
} }
@ -42086,6 +42119,7 @@ fn __action599<
elt: Box::new(elt.into()), elt: Box::new(elt.into()),
generators, generators,
range: (location..end_location).into(), range: (location..end_location).into(),
parenthesized: true
}.into() }.into()
} }

View file

@ -55,6 +55,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -44,6 +44,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
body: [ body: [

View file

@ -60,6 +60,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -65,6 +65,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
ifs: [], ifs: [],

View file

@ -45,6 +45,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -65,6 +65,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
ifs: [], ifs: [],

View file

@ -33,6 +33,7 @@ expression: parse_ast
), ),
], ],
ctx: Store, ctx: Store,
parenthesized: true,
}, },
), ),
], ],
@ -66,6 +67,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -58,6 +58,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -27,6 +27,7 @@ expression: parse_ast
), ),
], ],
ctx: Store, ctx: Store,
parenthesized: true,
}, },
), ),
], ],
@ -60,6 +61,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -54,6 +54,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -57,6 +57,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -35,6 +35,7 @@ Ok(
), ),
], ],
ctx: Store, ctx: Store,
parenthesized: true,
}, },
), ),
], ],
@ -68,6 +69,7 @@ Ok(
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -111,6 +111,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
debug_text: None, debug_text: None,
@ -501,6 +502,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
debug_text: Some( debug_text: Some(

View file

@ -146,12 +146,14 @@ Call(
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
ifs: [], ifs: [],
is_async: false, is_async: false,
}, },
], ],
parenthesized: false,
}, },
), ),
], ],

View file

@ -469,6 +469,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
cases: [ cases: [
@ -521,6 +522,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
cases: [ cases: [
@ -573,6 +575,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
cases: [ cases: [

View file

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "parse_suite(source, \"<test>\").unwrap()" expression: parse_suite(source).unwrap()
--- ---
[ [
Expr( Expr(
@ -52,6 +52,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
}, },
@ -105,6 +106,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
}, },
@ -385,6 +387,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
range: 298..300, range: 298..300,
elts: [], elts: [],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
], ],
@ -425,6 +428,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
range: 329..331, range: 329..331,
elts: [], elts: [],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
], ],
@ -505,6 +509,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
ctx: Load, ctx: Load,
@ -548,6 +553,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
ctx: Load, ctx: Load,

View file

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "parse_suite(source, \"<test>\").unwrap()" expression: parse_suite(source).unwrap()
--- ---
[ [
With( With(
@ -171,6 +171,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: Some( optional_vars: Some(
@ -220,6 +221,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: Some( optional_vars: Some(

View file

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "parse_suite(source, \"<test>\").unwrap()" expression: parse_suite(source).unwrap()
--- ---
[ [
ClassDef( ClassDef(
@ -143,6 +143,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
), ),

View file

@ -35,6 +35,7 @@ ListComp(
), ),
], ],
ctx: Store, ctx: Store,
parenthesized: false,
}, },
), ),
iter: Name( iter: Name(

View file

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "parse_suite(source, \"<test>\").unwrap()" expression: parse_suite(source).unwrap()
--- ---
[ [
FunctionDef( FunctionDef(
@ -254,6 +254,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
), ),

View file

@ -33,5 +33,6 @@ GeneratorExp(
is_async: false, is_async: false,
}, },
], ],
parenthesized: true,
}, },
) )

View file

@ -52,5 +52,6 @@ GeneratorExp(
is_async: false, is_async: false,
}, },
], ],
parenthesized: true,
}, },
) )

View file

@ -59,5 +59,6 @@ GeneratorExp(
is_async: false, is_async: false,
}, },
], ],
parenthesized: true,
}, },
) )

View file

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "parse_suite(source, \"<test>\").unwrap()" expression: parse_suite(source).unwrap()
--- ---
[ [
Assign( Assign(
@ -27,6 +27,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Store, ctx: Store,
parenthesized: false,
}, },
), ),
], ],
@ -52,6 +53,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
}, },

View file

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "parse_suite(source, \"<test>\").unwrap()" expression: parse_suite(source).unwrap()
--- ---
[ [
TypeAlias( TypeAlias(
@ -354,6 +354,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },
@ -438,6 +439,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },
@ -484,6 +486,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
), ),
@ -537,6 +540,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
}, },

View file

@ -1659,6 +1659,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
cases: [ cases: [
@ -2148,6 +2149,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
cases: [ cases: [
@ -3287,6 +3289,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
cases: [ cases: [
@ -3385,6 +3388,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
cases: [ cases: [
@ -3466,6 +3470,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
cases: [ cases: [
@ -3542,6 +3547,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
cases: [ cases: [
@ -3635,6 +3641,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
cases: [ cases: [

View file

@ -66,6 +66,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
ctx: Load, ctx: Load,
@ -128,6 +129,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
ctx: Store, ctx: Store,
@ -188,6 +190,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
ctx: Load, ctx: Load,
@ -253,6 +256,7 @@ expression: parse_ast
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
ctx: Load, ctx: Load,

View file

@ -0,0 +1,124 @@
---
source: crates/ruff_python_parser/src/parser.rs
expression: parse_ast
---
[
Expr(
StmtExpr {
range: 0..3,
value: Tuple(
ExprTuple {
range: 0..3,
elts: [
Name(
ExprName {
range: 0..1,
id: "a",
ctx: Load,
},
),
Name(
ExprName {
range: 2..3,
id: "b",
ctx: Load,
},
),
],
ctx: Load,
parenthesized: false,
},
),
},
),
Expr(
StmtExpr {
range: 4..9,
value: Tuple(
ExprTuple {
range: 4..9,
elts: [
Name(
ExprName {
range: 5..6,
id: "a",
ctx: Load,
},
),
Name(
ExprName {
range: 7..8,
id: "b",
ctx: Load,
},
),
],
ctx: Load,
parenthesized: true,
},
),
},
),
Expr(
StmtExpr {
range: 10..12,
value: Tuple(
ExprTuple {
range: 10..12,
elts: [],
ctx: Load,
parenthesized: true,
},
),
},
),
Expr(
StmtExpr {
range: 13..17,
value: Tuple(
ExprTuple {
range: 13..17,
elts: [
Name(
ExprName {
range: 14..15,
id: "a",
ctx: Load,
},
),
],
ctx: Load,
parenthesized: true,
},
),
},
),
Expr(
StmtExpr {
range: 18..25,
value: Tuple(
ExprTuple {
range: 19..24,
elts: [
Name(
ExprName {
range: 20..21,
id: "a",
ctx: Load,
},
),
Name(
ExprName {
range: 22..23,
id: "b",
ctx: Load,
},
),
],
ctx: Load,
parenthesized: true,
},
),
},
),
]

View file

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "parse_suite(source, \"<test>\").unwrap()" expression: parse_suite(source).unwrap()
--- ---
[ [
Expr( Expr(
@ -52,6 +52,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
}, },
@ -105,6 +106,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
}, },
@ -385,6 +387,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
range: 283..285, range: 283..285,
elts: [], elts: [],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
], ],
@ -425,6 +428,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
range: 312..314, range: 312..314,
elts: [], elts: [],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
], ],
@ -505,6 +509,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: false,
}, },
), ),
ctx: Load, ctx: Load,
@ -548,6 +553,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
ctx: Load, ctx: Load,

View file

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "parse_suite(source, \"<test>\").unwrap()" expression: parse_suite(source).unwrap()
--- ---
[ [
With( With(
@ -275,6 +275,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
range: 133..135, range: 133..135,
elts: [], elts: [],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: None, optional_vars: None,
@ -301,6 +302,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
range: 147..149, range: 147..149,
elts: [], elts: [],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: Some( optional_vars: Some(
@ -433,6 +435,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: Some( optional_vars: Some(
@ -523,6 +526,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: Some( optional_vars: Some(
@ -571,6 +575,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: None, optional_vars: None,
@ -611,6 +616,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: Some( optional_vars: Some(
@ -667,6 +673,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: None, optional_vars: None,
@ -715,6 +722,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: Some( optional_vars: Some(
@ -876,6 +884,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: None, optional_vars: None,
@ -943,6 +952,7 @@ expression: "parse_suite(source, \"<test>\").unwrap()"
), ),
], ],
ctx: Load, ctx: Load,
parenthesized: true,
}, },
), ),
optional_vars: Some( optional_vars: Some(