Skip to main content

ruff_python_ast/
nodes.rs

1#![allow(clippy::derive_partial_eq_without_eq)]
2
3use crate::AtomicNodeIndex;
4use crate::generated::{
5    ExprBytesLiteral, ExprCall, ExprCompare, ExprDict, ExprFString, ExprList, ExprName, ExprSet,
6    ExprStringLiteral, ExprTString, ExprTuple, PatternMatchAs, PatternMatchOr, StmtClassDef,
7    StmtImportFrom,
8};
9use std::borrow::Cow;
10use std::fmt;
11use std::fmt::Debug;
12use std::iter::{FusedIterator, Once};
13use std::ops::{Deref, DerefMut};
14use std::slice::{Iter, IterMut};
15use std::sync::OnceLock;
16
17use bitflags::bitflags;
18use thin_vec::ThinVec;
19
20use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
21
22use crate::str_prefix::{
23    AnyStringPrefix, ByteStringPrefix, FStringPrefix, StringLiteralPrefix, TStringPrefix,
24};
25use crate::{
26    Expr, ExprRef, InterpolatedStringElement, LiteralExpressionRef, OperatorPrecedence, Pattern,
27    PythonVersion, Stmt, TypeParam, int,
28    name::Name,
29    str::{Quote, TripleQuotes},
30};
31
32impl StmtClassDef {
33    /// Return an iterator over the bases of the class.
34    pub fn bases(&self) -> &[Expr] {
35        match &self.arguments {
36            Some(arguments) => &arguments.args,
37            None => &[],
38        }
39    }
40
41    /// Return an iterator over the metaclass keywords of the class.
42    pub fn keywords(&self) -> &[Keyword] {
43        match &self.arguments {
44            Some(arguments) => &arguments.keywords,
45            None => &[],
46        }
47    }
48}
49
50impl StmtImportFrom {
51    /// Returns `true` if this import statement is a `__future__` import for the given Python version.
52    ///
53    /// In Python < 3.13, relative imports from `.__future__` are treated as future imports.
54    /// In Python >= 3.13, only absolute imports (`level == 0`) from `__future__` are treated as
55    /// future imports.
56    pub fn is_future_import(&self, target_version: PythonVersion) -> bool {
57        self.module.as_deref() == Some("__future__")
58            && (self.level == 0 || target_version < PythonVersion::PY313)
59    }
60}
61
62#[derive(Clone, Debug, PartialEq)]
63#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
64pub struct ElifElseClause {
65    pub range: TextRange,
66    pub node_index: AtomicNodeIndex,
67    pub test: Option<Expr>,
68    pub body: Suite,
69}
70
71impl Expr {
72    /// Returns `true` if the expression is a literal expression.
73    ///
74    /// A literal expression is either a string literal, bytes literal,
75    /// integer, float, complex number, boolean, `None`, or ellipsis (`...`).
76    pub fn is_literal_expr(&self) -> bool {
77        matches!(
78            self,
79            Expr::StringLiteral(_)
80                | Expr::BytesLiteral(_)
81                | Expr::NumberLiteral(_)
82                | Expr::BooleanLiteral(_)
83                | Expr::NoneLiteral(_)
84                | Expr::EllipsisLiteral(_)
85        )
86    }
87
88    /// Returns [`LiteralExpressionRef`] if the expression is a literal expression.
89    pub fn as_literal_expr(&self) -> Option<LiteralExpressionRef<'_>> {
90        match self {
91            Expr::StringLiteral(expr) => Some(LiteralExpressionRef::StringLiteral(expr)),
92            Expr::BytesLiteral(expr) => Some(LiteralExpressionRef::BytesLiteral(expr)),
93            Expr::NumberLiteral(expr) => Some(LiteralExpressionRef::NumberLiteral(expr)),
94            Expr::BooleanLiteral(expr) => Some(LiteralExpressionRef::BooleanLiteral(expr)),
95            Expr::NoneLiteral(expr) => Some(LiteralExpressionRef::NoneLiteral(expr)),
96            Expr::EllipsisLiteral(expr) => Some(LiteralExpressionRef::EllipsisLiteral(expr)),
97            _ => None,
98        }
99    }
100
101    /// Return the value expression after peeling off any nested named expressions.
102    ///
103    /// For example, this returns the `x` expression for both `x` and `(y := x)`.
104    pub fn expression_value(&self) -> &Self {
105        let mut expr = self;
106        while let Expr::Named(named) = expr {
107            expr = &named.value;
108        }
109        expr
110    }
111
112    /// Return the [`OperatorPrecedence`] of this expression
113    pub fn precedence(&self) -> OperatorPrecedence {
114        OperatorPrecedence::from(self)
115    }
116}
117
118impl ExprCompare {
119    /// Returns the initial operand (`a` in `a < b <= c`).
120    ///
121    /// # Panics
122    ///
123    /// Panics if there are no operands. The parser always produces at least two operands,
124    /// synthesizing an invalid name expression for a missing operand during error recovery.
125    pub fn first_operand(&self) -> &Expr {
126        self.operands
127            .first()
128            .expect("A comparison has a left operand")
129    }
130
131    /// Returns the right operand of the first comparison (`b` in `a < b <= c`).
132    ///
133    /// # Panics
134    ///
135    /// Panics if there are fewer than two operands. See [`Self::first_operand`].
136    pub fn second_operand(&self) -> &Expr {
137        self.operands
138            .get(1)
139            .expect("A comparison has a right operand")
140    }
141
142    /// Returns the first comparison operator (`<` in `a < b <= c`).
143    ///
144    /// # Panics
145    ///
146    /// Panics if there are no operators. The parser always produces at least one operator.
147    pub fn first_operator(&self) -> CmpOp {
148        *self.ops.first().expect("A comparison has an operator")
149    }
150
151    /// Returns all operands after the initial operand (`[b, c]` in `a < b <= c`).
152    ///
153    /// # Panics
154    ///
155    /// Panics if there are no operands. See [`Self::first_operand`].
156    pub fn comparators(&self) -> &[Expr] {
157        &self.operands[1..]
158    }
159
160    /// Returns `(left, operator, right)` if there is exactly one operator and two operands.
161    pub fn as_single(&self) -> Option<(&Expr, &CmpOp, &Expr)> {
162        match (&*self.operands, &*self.ops) {
163            ([left, right], [op]) => Some((left, op, right)),
164            _ => None,
165        }
166    }
167
168    /// Iterates over each comparison as `(left, operator, right)`.
169    ///
170    /// For `a < b <= c`, yields `(a, <, b)` followed by `(b, <=, c)`.
171    pub fn iter(
172        &self,
173    ) -> impl DoubleEndedIterator<Item = (&Expr, &CmpOp, &Expr)> + ExactSizeIterator {
174        self.operands
175            .iter()
176            .zip(self.ops.iter())
177            .zip(self.operands.iter().skip(1))
178            .map(|((left, op), right)| (left, op, right))
179    }
180}
181
182impl ExprRef<'_> {
183    /// See [`Expr::is_literal_expr`].
184    pub fn is_literal_expr(&self) -> bool {
185        matches!(
186            self,
187            ExprRef::StringLiteral(_)
188                | ExprRef::BytesLiteral(_)
189                | ExprRef::NumberLiteral(_)
190                | ExprRef::BooleanLiteral(_)
191                | ExprRef::NoneLiteral(_)
192                | ExprRef::EllipsisLiteral(_)
193        )
194    }
195
196    pub fn precedence(&self) -> OperatorPrecedence {
197        OperatorPrecedence::from(*self)
198    }
199}
200
201/// Represents an item in a [dictionary literal display][1].
202///
203/// Consider the following Python dictionary literal:
204/// ```python
205/// {key1: value1, **other_dictionary}
206/// ```
207///
208/// In our AST, this would be represented using an `ExprDict` node containing
209/// two `DictItem` nodes inside it:
210/// ```ignore
211/// [
212///     DictItem {
213///         key: Some(Expr::Name(ExprName { id: "key1" })),
214///         value: Expr::Name(ExprName { id: "value1" }),
215///     },
216///     DictItem {
217///         key: None,
218///         value: Expr::Name(ExprName { id: "other_dictionary" }),
219///     }
220/// ]
221/// ```
222///
223/// [1]: https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries
224#[derive(Debug, Clone, PartialEq)]
225#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
226pub struct DictItem {
227    pub key: Option<Expr>,
228    pub value: Expr,
229}
230
231impl DictItem {
232    fn key(&self) -> Option<&Expr> {
233        self.key.as_ref()
234    }
235
236    fn value(&self) -> &Expr {
237        &self.value
238    }
239}
240
241impl Ranged for DictItem {
242    fn range(&self) -> TextRange {
243        TextRange::new(
244            self.key.as_ref().map_or(self.value.start(), Ranged::start),
245            self.value.end(),
246        )
247    }
248}
249
250impl ExprDict {
251    /// Returns an `Iterator` over the AST nodes representing the
252    /// dictionary's keys.
253    pub fn iter_keys(&self) -> DictKeyIterator<'_> {
254        DictKeyIterator::new(&self.items)
255    }
256
257    /// Returns an `Iterator` over the AST nodes representing the
258    /// dictionary's values.
259    pub fn iter_values(&self) -> DictValueIterator<'_> {
260        DictValueIterator::new(&self.items)
261    }
262
263    /// Returns the AST node representing the *n*th key of this
264    /// dictionary.
265    ///
266    /// Panics: If the index `n` is out of bounds.
267    pub fn key(&self, n: usize) -> Option<&Expr> {
268        self.items[n].key()
269    }
270
271    /// Returns the AST node representing the *n*th value of this
272    /// dictionary.
273    ///
274    /// Panics: If the index `n` is out of bounds.
275    pub fn value(&self, n: usize) -> &Expr {
276        self.items[n].value()
277    }
278
279    pub fn iter(&self) -> std::slice::Iter<'_, DictItem> {
280        self.items.iter()
281    }
282
283    pub fn len(&self) -> usize {
284        self.items.len()
285    }
286
287    pub fn is_empty(&self) -> bool {
288        self.items.is_empty()
289    }
290}
291
292impl<'a> IntoIterator for &'a ExprDict {
293    type IntoIter = std::slice::Iter<'a, DictItem>;
294    type Item = &'a DictItem;
295
296    fn into_iter(self) -> Self::IntoIter {
297        self.iter()
298    }
299}
300
301#[derive(Debug, Clone)]
302pub struct DictKeyIterator<'a> {
303    items: Iter<'a, DictItem>,
304}
305
306impl<'a> DictKeyIterator<'a> {
307    fn new(items: &'a [DictItem]) -> Self {
308        Self {
309            items: items.iter(),
310        }
311    }
312
313    pub fn is_empty(&self) -> bool {
314        self.len() == 0
315    }
316}
317
318impl<'a> Iterator for DictKeyIterator<'a> {
319    type Item = Option<&'a Expr>;
320
321    fn next(&mut self) -> Option<Self::Item> {
322        self.items.next().map(DictItem::key)
323    }
324
325    fn last(mut self) -> Option<Self::Item> {
326        self.next_back()
327    }
328
329    fn size_hint(&self) -> (usize, Option<usize>) {
330        self.items.size_hint()
331    }
332}
333
334impl DoubleEndedIterator for DictKeyIterator<'_> {
335    fn next_back(&mut self) -> Option<Self::Item> {
336        self.items.next_back().map(DictItem::key)
337    }
338}
339
340impl FusedIterator for DictKeyIterator<'_> {}
341impl ExactSizeIterator for DictKeyIterator<'_> {}
342
343#[derive(Debug, Clone)]
344pub struct DictValueIterator<'a> {
345    items: Iter<'a, DictItem>,
346}
347
348impl<'a> DictValueIterator<'a> {
349    fn new(items: &'a [DictItem]) -> Self {
350        Self {
351            items: items.iter(),
352        }
353    }
354
355    pub fn is_empty(&self) -> bool {
356        self.len() == 0
357    }
358}
359
360impl<'a> Iterator for DictValueIterator<'a> {
361    type Item = &'a Expr;
362
363    fn next(&mut self) -> Option<Self::Item> {
364        self.items.next().map(DictItem::value)
365    }
366
367    fn last(mut self) -> Option<Self::Item> {
368        self.next_back()
369    }
370
371    fn size_hint(&self) -> (usize, Option<usize>) {
372        self.items.size_hint()
373    }
374}
375
376impl DoubleEndedIterator for DictValueIterator<'_> {
377    fn next_back(&mut self) -> Option<Self::Item> {
378        self.items.next_back().map(DictItem::value)
379    }
380}
381
382impl FusedIterator for DictValueIterator<'_> {}
383impl ExactSizeIterator for DictValueIterator<'_> {}
384
385impl ExprSet {
386    pub fn iter(&self) -> std::slice::Iter<'_, Expr> {
387        self.elts.iter()
388    }
389
390    pub fn len(&self) -> usize {
391        self.elts.len()
392    }
393
394    pub fn is_empty(&self) -> bool {
395        self.elts.is_empty()
396    }
397}
398
399impl<'a> IntoIterator for &'a ExprSet {
400    type IntoIter = std::slice::Iter<'a, Expr>;
401    type Item = &'a Expr;
402
403    fn into_iter(self) -> Self::IntoIter {
404        self.iter()
405    }
406}
407
408#[derive(Clone, Debug, PartialEq)]
409#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
410pub struct InterpolatedStringFormatSpec {
411    pub range: TextRange,
412    pub node_index: AtomicNodeIndex,
413    pub elements: InterpolatedStringElements,
414}
415
416/// See also [FormattedValue](https://docs.python.org/3/library/ast.html#ast.FormattedValue)
417#[derive(Clone, Debug, PartialEq)]
418#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
419pub struct InterpolatedElement {
420    pub range: TextRange,
421    pub node_index: AtomicNodeIndex,
422    pub expression: Box<Expr>,
423    pub debug_text: Option<DebugText>,
424    pub conversion: ConversionFlag,
425    pub format_spec: Option<Box<InterpolatedStringFormatSpec>>,
426}
427
428/// An `FStringLiteralElement` with an empty `value` is an invalid f-string element.
429#[derive(Clone, Debug, PartialEq)]
430#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
431pub struct InterpolatedStringLiteralElement {
432    pub range: TextRange,
433    pub node_index: AtomicNodeIndex,
434    pub value: Box<str>,
435}
436
437impl InterpolatedStringLiteralElement {
438    pub fn is_valid(&self) -> bool {
439        !self.value.is_empty()
440    }
441}
442
443impl Deref for InterpolatedStringLiteralElement {
444    type Target = str;
445
446    fn deref(&self) -> &Self::Target {
447        &self.value
448    }
449}
450
451/// Transforms a value prior to formatting it.
452#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, is_macro::Is)]
453#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
454#[repr(i8)]
455#[expect(clippy::cast_possible_wrap)]
456pub enum ConversionFlag {
457    /// No conversion
458    None = -1, // CPython uses -1
459    /// Converts by calling `str(<value>)`.
460    Str = b's' as i8,
461    /// Converts by calling `ascii(<value>)`.
462    Ascii = b'a' as i8,
463    /// Converts by calling `repr(<value>)`.
464    Repr = b'r' as i8,
465}
466
467impl ConversionFlag {
468    pub fn to_byte(&self) -> Option<u8> {
469        match self {
470            Self::None => None,
471            flag => Some(*flag as u8),
472        }
473    }
474    pub fn to_char(&self) -> Option<char> {
475        Some(self.to_byte()? as char)
476    }
477}
478
479/// The debug text of a self-documenting f-string expression (e.g., `f"{x=}"`).
480///
481/// Stores the concatenation of leading text, expression source, and trailing text as a single
482/// [`CompactString`], with byte offsets to split them. The offsets are needed because the leading
483/// and trailing portions can contain non-whitespace characters (grouping parentheses, comments in
484/// triple-quoted f-strings) that cannot be distinguished from expression content by scanning.
485///
486/// [`CompactString`]: compact_str::CompactString
487#[derive(Clone, PartialEq, Eq, Hash)]
488#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
489pub struct DebugText {
490    /// The full text between the `{` and the conversion / `format_spec` / `}`.
491    text: compact_str::CompactString,
492    /// Byte offset where the expression source begins.
493    expression_start: u32,
494    /// Byte offset where the expression source ends.
495    expression_end: u32,
496}
497
498impl std::fmt::Debug for DebugText {
499    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
500        f.debug_struct("DebugText")
501            .field("leading", &self.leading())
502            .field("expression", &self.expression())
503            .field("trailing", &self.trailing())
504            .finish()
505    }
506}
507
508impl DebugText {
509    pub fn new(leading: &str, expression: &str, trailing: &str) -> Self {
510        let expression_start = leading.text_len().to_u32();
511        let expression_end = expression_start + expression.text_len().to_u32();
512        let mut buf = compact_str::CompactString::with_capacity(
513            leading.len() + expression.len() + trailing.len(),
514        );
515        buf.push_str(leading);
516        buf.push_str(expression);
517        buf.push_str(trailing);
518        Self {
519            text: buf,
520            expression_start,
521            expression_end,
522        }
523    }
524
525    /// The full debug text between the `{` and the conversion / `format_spec` / `}`.
526    pub fn as_str(&self) -> &str {
527        &self.text
528    }
529
530    /// The text between the `{` and the expression node.
531    pub fn leading(&self) -> &str {
532        &self.text[..self.expression_start as usize]
533    }
534
535    /// The source text of the expression (e.g., `0x0` in `f"{0x0=}"`).
536    pub fn expression(&self) -> &str {
537        &self.text[self.expression_start as usize..self.expression_end as usize]
538    }
539
540    /// The text between the expression and the conversion, the `format_spec`, or the `}`.
541    pub fn trailing(&self) -> &str {
542        &self.text[self.expression_end as usize..]
543    }
544}
545
546impl ExprFString {
547    /// Returns the single [`FString`] if the f-string isn't implicitly concatenated, [`None`]
548    /// otherwise.
549    pub const fn as_single_part_fstring(&self) -> Option<&FString> {
550        match &self.value.inner {
551            FStringValueInner::Single(fstring) => Some(fstring),
552            FStringValueInner::Concatenated(_) => None,
553        }
554    }
555}
556
557/// The value representing an [`ExprFString`].
558#[derive(Clone, Debug, PartialEq)]
559#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
560pub struct FStringValue {
561    inner: FStringValueInner,
562}
563
564impl FStringValue {
565    /// Creates a new f-string literal with a single [`FString`] part.
566    pub fn single(value: FString) -> Self {
567        Self {
568            inner: FStringValueInner::Single(value),
569        }
570    }
571
572    /// Creates a new f-string with the given values that represents an implicitly
573    /// concatenated f-string.
574    ///
575    /// # Panics
576    ///
577    /// Panics if `values` has less than 2 elements.
578    /// Use [`FStringValue::single`] instead.
579    pub fn concatenated(values: Vec<FStringPart>) -> Self {
580        assert!(
581            values.len() > 1,
582            "Use `FStringValue::single` to create single-part f-strings"
583        );
584        Self {
585            inner: FStringValueInner::Concatenated(values),
586        }
587    }
588
589    /// Returns `true` if the f-string is implicitly concatenated, `false` otherwise.
590    pub fn is_implicit_concatenated(&self) -> bool {
591        matches!(self.inner, FStringValueInner::Concatenated(_))
592    }
593
594    /// Returns an iterator over the parts of this f-string, in source order.
595    pub fn iter(&self) -> FStringParts<'_> {
596        match &self.inner {
597            FStringValueInner::Single(fstring) => FStringParts::Single(std::iter::once(fstring)),
598            FStringValueInner::Concatenated(parts) => FStringParts::Concatenated(parts.iter()),
599        }
600    }
601
602    /// Returns a mutable iterator over the parts of this f-string, in source order.
603    pub fn iter_mut(&mut self) -> FStringPartsMut<'_> {
604        match &mut self.inner {
605            FStringValueInner::Single(fstring) => FStringPartsMut::Single(std::iter::once(fstring)),
606            FStringValueInner::Concatenated(parts) => {
607                FStringPartsMut::Concatenated(parts.iter_mut())
608            }
609        }
610    }
611
612    /// Returns an iterator over the [`StringLiteral`] parts contained in this value.
613    ///
614    /// Note that this doesn't recurse into the f-string parts. For example,
615    ///
616    /// ```python
617    /// "foo" f"bar {x}" "baz" f"qux"
618    /// ```
619    ///
620    /// Here, the string literal parts returned would be `"foo"` and `"baz"`.
621    pub fn literals(&self) -> impl Iterator<Item = &StringLiteral> {
622        self.iter().filter_map(|part| match part {
623            FStringPartRef::Literal(literal) => Some(literal),
624            FStringPartRef::FString(_) => None,
625        })
626    }
627
628    /// Returns an iterator over the [`FString`] parts contained in this value.
629    ///
630    /// Note that this doesn't recurse into the f-string parts. For example,
631    ///
632    /// ```python
633    /// "foo" f"bar {x}" "baz" f"qux"
634    /// ```
635    ///
636    /// Here, the f-string parts returned would be `f"bar {x}"` and `f"qux"`.
637    pub fn f_strings(&self) -> impl Iterator<Item = &FString> {
638        self.iter().filter_map(|part| match part {
639            FStringPartRef::FString(fstring) => Some(fstring),
640            FStringPartRef::Literal(_) => None,
641        })
642    }
643
644    /// Returns an iterator over all the [`InterpolatedStringElement`] contained in this value.
645    ///
646    /// An f-string element is what makes up an [`FString`] i.e., it is either a
647    /// string literal or an expression. In the following example,
648    ///
649    /// ```python
650    /// "foo" f"bar {x}" "baz" f"qux"
651    /// ```
652    ///
653    /// The f-string elements returned would be string literal (`"bar "`),
654    /// expression (`x`) and string literal (`"qux"`).
655    pub fn elements(&self) -> impl Iterator<Item = &InterpolatedStringElement> {
656        self.f_strings().flat_map(|fstring| fstring.elements.iter())
657    }
658
659    /// Returns `true` if the node represents an empty f-string literal.
660    ///
661    /// Note that a [`FStringValue`] node will always have >= 1 [`FStringPart`]s inside it.
662    /// This method checks whether the value of the concatenated parts is equal to the empty
663    /// f-string, not whether the f-string has 0 parts inside it.
664    pub fn is_empty_literal(&self) -> bool {
665        match &self.inner {
666            FStringValueInner::Single(fstring) => fstring.elements.is_empty(),
667            FStringValueInner::Concatenated(fstring_parts) => {
668                fstring_parts.iter().all(FStringPart::is_empty_literal)
669            }
670        }
671    }
672}
673
674impl<'a> IntoIterator for &'a FStringValue {
675    type Item = FStringPartRef<'a>;
676    type IntoIter = FStringParts<'a>;
677
678    fn into_iter(self) -> Self::IntoIter {
679        self.iter()
680    }
681}
682
683impl<'a> IntoIterator for &'a mut FStringValue {
684    type Item = FStringPartMut<'a>;
685    type IntoIter = FStringPartsMut<'a>;
686    fn into_iter(self) -> Self::IntoIter {
687        self.iter_mut()
688    }
689}
690
691/// An internal representation of [`FStringValue`].
692#[derive(Clone, Debug, PartialEq)]
693#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
694enum FStringValueInner {
695    /// A single f-string i.e., `f"foo"`.
696    Single(FString),
697
698    /// An implicitly concatenated f-string i.e., `"foo" f"bar {x}"`.
699    Concatenated(Vec<FStringPart>),
700}
701
702/// An f-string part which is either a string literal or an f-string.
703#[derive(Clone, Debug, PartialEq, is_macro::Is)]
704#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
705pub enum FStringPart {
706    Literal(StringLiteral),
707    FString(FString),
708}
709
710impl FStringPart {
711    pub fn quote_style(&self) -> Quote {
712        FStringPartRef::from(self).quote_style()
713    }
714
715    pub fn is_empty_literal(&self) -> bool {
716        match &self {
717            FStringPart::Literal(string_literal) => string_literal.value.is_empty(),
718            FStringPart::FString(f_string) => f_string.elements.is_empty(),
719        }
720    }
721}
722
723impl Ranged for FStringPart {
724    fn range(&self) -> TextRange {
725        FStringPartRef::from(self).range()
726    }
727}
728
729/// A borrowed string literal or f-string part of an [`FStringValue`].
730#[derive(Copy, Clone, Debug, PartialEq)]
731pub enum FStringPartRef<'a> {
732    Literal(&'a StringLiteral),
733    FString(&'a FString),
734}
735
736impl FStringPartRef<'_> {
737    pub fn quote_style(self) -> Quote {
738        match self {
739            Self::Literal(literal) => literal.flags.quote_style(),
740            Self::FString(fstring) => fstring.flags.quote_style(),
741        }
742    }
743}
744
745impl<'a> From<&'a FStringPart> for FStringPartRef<'a> {
746    fn from(part: &'a FStringPart) -> Self {
747        match part {
748            FStringPart::Literal(literal) => Self::Literal(literal),
749            FStringPart::FString(fstring) => Self::FString(fstring),
750        }
751    }
752}
753
754impl Ranged for FStringPartRef<'_> {
755    fn range(&self) -> TextRange {
756        match self {
757            Self::Literal(literal) => literal.range(),
758            Self::FString(fstring) => fstring.range(),
759        }
760    }
761}
762
763/// A mutably borrowed string literal or f-string part of an [`FStringValue`].
764pub enum FStringPartMut<'a> {
765    Literal(&'a mut StringLiteral),
766    FString(&'a mut FString),
767}
768
769impl<'a> From<&'a mut FStringPart> for FStringPartMut<'a> {
770    fn from(part: &'a mut FStringPart) -> Self {
771        match part {
772            FStringPart::Literal(literal) => Self::Literal(literal),
773            FStringPart::FString(fstring) => Self::FString(fstring),
774        }
775    }
776}
777
778/// The iterator returned by [`FStringValue::iter`].
779#[derive(Clone)]
780pub enum FStringParts<'a> {
781    Single(Once<&'a FString>),
782    Concatenated(Iter<'a, FStringPart>),
783}
784
785impl<'a> Iterator for FStringParts<'a> {
786    type Item = FStringPartRef<'a>;
787
788    fn next(&mut self) -> Option<Self::Item> {
789        match self {
790            Self::Single(single) => single.next().map(FStringPartRef::FString),
791            Self::Concatenated(parts) => parts.next().map(FStringPartRef::from),
792        }
793    }
794
795    fn size_hint(&self) -> (usize, Option<usize>) {
796        match self {
797            Self::Single(single) => single.size_hint(),
798            Self::Concatenated(parts) => parts.size_hint(),
799        }
800    }
801}
802
803impl DoubleEndedIterator for FStringParts<'_> {
804    fn next_back(&mut self) -> Option<Self::Item> {
805        match self {
806            Self::Single(single) => single.next_back().map(FStringPartRef::FString),
807            Self::Concatenated(parts) => parts.next_back().map(FStringPartRef::from),
808        }
809    }
810}
811
812impl ExactSizeIterator for FStringParts<'_> {}
813impl FusedIterator for FStringParts<'_> {}
814
815/// The iterator returned by [`FStringValue::iter_mut`].
816pub enum FStringPartsMut<'a> {
817    Single(Once<&'a mut FString>),
818    Concatenated(IterMut<'a, FStringPart>),
819}
820
821impl<'a> Iterator for FStringPartsMut<'a> {
822    type Item = FStringPartMut<'a>;
823
824    fn next(&mut self) -> Option<Self::Item> {
825        match self {
826            Self::Single(single) => single.next().map(FStringPartMut::FString),
827            Self::Concatenated(parts) => parts.next().map(FStringPartMut::from),
828        }
829    }
830
831    fn size_hint(&self) -> (usize, Option<usize>) {
832        match self {
833            Self::Single(single) => single.size_hint(),
834            Self::Concatenated(parts) => parts.size_hint(),
835        }
836    }
837}
838
839impl DoubleEndedIterator for FStringPartsMut<'_> {
840    fn next_back(&mut self) -> Option<Self::Item> {
841        match self {
842            Self::Single(single) => single.next_back().map(FStringPartMut::FString),
843            Self::Concatenated(parts) => parts.next_back().map(FStringPartMut::from),
844        }
845    }
846}
847
848impl ExactSizeIterator for FStringPartsMut<'_> {}
849impl FusedIterator for FStringPartsMut<'_> {}
850
851impl ExprTString {
852    /// Returns the single [`TString`] if the t-string isn't implicitly concatenated, [`None`]
853    /// otherwise.
854    pub const fn as_single_part_tstring(&self) -> Option<&TString> {
855        match &self.value.inner {
856            TStringValueInner::Single(tstring) => Some(tstring),
857            TStringValueInner::Concatenated(_) => None,
858        }
859    }
860}
861
862/// The value representing an [`ExprTString`].
863#[derive(Clone, Debug, PartialEq)]
864#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
865pub struct TStringValue {
866    inner: TStringValueInner,
867}
868
869impl TStringValue {
870    /// Creates a new t-string literal with a single [`TString`] part.
871    pub fn single(value: TString) -> Self {
872        Self {
873            inner: TStringValueInner::Single(value),
874        }
875    }
876
877    /// Creates a new t-string with the given values that represents an implicitly
878    /// concatenated t-string.
879    ///
880    /// # Panics
881    ///
882    /// Panics if `values` has less than 2 elements.
883    /// Use [`TStringValue::single`] instead.
884    pub fn concatenated(values: Vec<TString>) -> Self {
885        assert!(
886            values.len() > 1,
887            "Use `TStringValue::single` to create single-part t-strings"
888        );
889        Self {
890            inner: TStringValueInner::Concatenated(values),
891        }
892    }
893
894    /// Returns `true` if the t-string is implicitly concatenated, `false` otherwise.
895    pub fn is_implicit_concatenated(&self) -> bool {
896        matches!(self.inner, TStringValueInner::Concatenated(_))
897    }
898
899    /// Returns a slice of all the [`TString`]s contained in this value.
900    pub fn as_slice(&self) -> &[TString] {
901        match &self.inner {
902            TStringValueInner::Single(part) => std::slice::from_ref(part),
903            TStringValueInner::Concatenated(parts) => parts,
904        }
905    }
906
907    /// Returns a mutable slice of all the [`TString`]s contained in this value.
908    fn as_mut_slice(&mut self) -> &mut [TString] {
909        match &mut self.inner {
910            TStringValueInner::Single(part) => std::slice::from_mut(part),
911            TStringValueInner::Concatenated(parts) => parts,
912        }
913    }
914
915    /// Returns an iterator over all the [`TString`]s contained in this value.
916    pub fn iter(&self) -> Iter<'_, TString> {
917        self.as_slice().iter()
918    }
919
920    /// Returns an iterator over all the [`TString`]s contained in this value
921    /// that allows modification.
922    pub fn iter_mut(&mut self) -> IterMut<'_, TString> {
923        self.as_mut_slice().iter_mut()
924    }
925
926    /// Returns an iterator over all the [`InterpolatedStringElement`] contained in this value.
927    ///
928    /// An interpolated string element is what makes up an [`TString`] i.e., it is either a
929    /// string literal or an interpolation. In the following example,
930    ///
931    /// ```python
932    /// t"foo" t"bar {x}" t"baz" t"qux"
933    /// ```
934    ///
935    /// The interpolated string elements returned would be string literal (`"bar "`),
936    /// interpolation (`x`) and string literal (`"qux"`).
937    pub fn elements(&self) -> impl Iterator<Item = &InterpolatedStringElement> {
938        self.iter().flat_map(|tstring| tstring.elements.iter())
939    }
940
941    /// Returns `true` if the node represents an empty t-string in the
942    /// sense that `__iter__` returns an empty iterable.
943    ///
944    /// Beware that empty t-strings are still truthy, i.e. `bool(t"") == True`.
945    ///
946    /// Note that a [`TStringValue`] node will always contain at least one
947    /// [`TString`] node. This method checks whether each of the constituent
948    /// t-strings (in an implicitly concatenated t-string) are empty
949    /// in the above sense.
950    pub fn is_empty_iterable(&self) -> bool {
951        match &self.inner {
952            TStringValueInner::Single(tstring) => tstring.is_empty(),
953            TStringValueInner::Concatenated(tstrings) => tstrings.iter().all(TString::is_empty),
954        }
955    }
956}
957
958impl<'a> IntoIterator for &'a TStringValue {
959    type Item = &'a TString;
960    type IntoIter = Iter<'a, TString>;
961
962    fn into_iter(self) -> Self::IntoIter {
963        self.iter()
964    }
965}
966
967impl<'a> IntoIterator for &'a mut TStringValue {
968    type Item = &'a mut TString;
969    type IntoIter = IterMut<'a, TString>;
970    fn into_iter(self) -> Self::IntoIter {
971        self.iter_mut()
972    }
973}
974
975/// An internal representation of [`TStringValue`].
976#[derive(Clone, Debug, PartialEq)]
977#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
978enum TStringValueInner {
979    /// A single t-string i.e., `t"foo"`.
980    Single(TString),
981
982    /// An implicitly concatenated t-string i.e., `t"foo" t"bar {x}"`.
983    Concatenated(Vec<TString>),
984}
985
986pub trait StringFlags: Copy {
987    /// Does the string use single or double quotes in its opener and closer?
988    fn quote_style(self) -> Quote;
989
990    fn triple_quotes(self) -> TripleQuotes;
991
992    fn prefix(self) -> AnyStringPrefix;
993
994    fn is_unclosed(self) -> bool;
995
996    /// Is the string triple-quoted, i.e.,
997    /// does it begin and end with three consecutive quote characters?
998    fn is_triple_quoted(self) -> bool {
999        self.triple_quotes().is_yes()
1000    }
1001
1002    /// A `str` representation of the quotes used to start and close.
1003    /// This does not include any prefixes the string has in its opener.
1004    fn quote_str(self) -> &'static str {
1005        match (self.triple_quotes(), self.quote_style()) {
1006            (TripleQuotes::Yes, Quote::Single) => "'''",
1007            (TripleQuotes::Yes, Quote::Double) => r#"""""#,
1008            (TripleQuotes::No, Quote::Single) => "'",
1009            (TripleQuotes::No, Quote::Double) => "\"",
1010        }
1011    }
1012
1013    /// The length of the quotes used to start and close the string.
1014    /// This does not include the length of any prefixes the string has
1015    /// in its opener.
1016    fn quote_len(self) -> TextSize {
1017        if self.is_triple_quoted() {
1018            TextSize::new(3)
1019        } else {
1020            TextSize::new(1)
1021        }
1022    }
1023
1024    /// The total length of the string's opener,
1025    /// i.e., the length of the prefixes plus the length
1026    /// of the quotes used to open the string.
1027    fn opener_len(self) -> TextSize {
1028        self.prefix().text_len() + self.quote_len()
1029    }
1030
1031    /// The total length of the string's closer.
1032    /// This is always equal to `self.quote_len()`, except when the string is unclosed,
1033    /// in which case the length is zero.
1034    fn closer_len(self) -> TextSize {
1035        if self.is_unclosed() {
1036            TextSize::default()
1037        } else {
1038            self.quote_len()
1039        }
1040    }
1041
1042    fn as_any_string_flags(self) -> AnyStringFlags {
1043        AnyStringFlags::new(self.prefix(), self.quote_style(), self.triple_quotes())
1044            .with_unclosed(self.is_unclosed())
1045    }
1046
1047    fn display_contents(self, contents: &str) -> DisplayFlags<'_> {
1048        DisplayFlags {
1049            flags: self.as_any_string_flags(),
1050            contents,
1051        }
1052    }
1053}
1054
1055pub struct DisplayFlags<'a> {
1056    flags: AnyStringFlags,
1057    contents: &'a str,
1058}
1059
1060impl std::fmt::Display for DisplayFlags<'_> {
1061    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1062        write!(
1063            f,
1064            "{prefix}{quote}{contents}{quote}",
1065            prefix = self.flags.prefix(),
1066            quote = self.flags.quote_str(),
1067            contents = self.contents
1068        )
1069    }
1070}
1071
1072bitflags! {
1073    #[derive(Default, Copy, Clone, PartialEq, Eq, Hash)]
1074    struct InterpolatedStringFlagsInner: u8 {
1075        /// The f-string uses double quotes (`"`) for its opener and closer.
1076        /// If this flag is not set, the f-string uses single quotes (`'`)
1077        /// for its opener and closer.
1078        const DOUBLE = 1 << 0;
1079
1080        /// The f-string is triple-quoted:
1081        /// it begins and ends with three consecutive quote characters.
1082        /// For example: `f"""{bar}"""`.
1083        const TRIPLE_QUOTED = 1 << 1;
1084
1085        /// The f-string has an `r` prefix, meaning it is a raw f-string
1086        /// with a lowercase 'r'. For example: `rf"{bar}"`
1087        const R_PREFIX_LOWER = 1 << 2;
1088
1089        /// The f-string has an `R` prefix, meaning it is a raw f-string
1090        /// with an uppercase 'r'. For example: `Rf"{bar}"`.
1091        /// See https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#r-strings-and-r-strings
1092        /// for why we track the casing of the `r` prefix,
1093        /// but not for any other prefix
1094        const R_PREFIX_UPPER = 1 << 3;
1095
1096        /// The f-string is unclosed, meaning it is missing a closing quote.
1097        /// For example: `f"{bar`
1098        const UNCLOSED = 1 << 4;
1099    }
1100}
1101
1102#[cfg(feature = "get-size")]
1103impl get_size2::GetSize for InterpolatedStringFlagsInner {}
1104
1105/// Flags that can be queried to obtain information
1106/// regarding the prefixes and quotes used for an f-string.
1107///
1108/// Note: This is identical to [`TStringFlags`] except that
1109/// the implementation of the `prefix` method of the
1110/// [`StringFlags`] trait returns a variant of
1111/// `AnyStringPrefix::Format`.
1112///
1113/// ## Notes on usage
1114///
1115/// If you're using a `Generator` from the `ruff_python_codegen` crate to generate a lint-rule fix
1116/// from an existing f-string literal, consider passing along the [`FString::flags`] field. If you
1117/// don't have an existing literal but have a `Checker` from the `ruff_linter` crate available,
1118/// consider using `Checker::default_fstring_flags` to create instances of this struct; this method
1119/// will properly handle nested f-strings. For usage that doesn't fit into one of these categories,
1120/// the public constructor [`FStringFlags::empty`] can be used.
1121#[derive(Copy, Clone, Eq, PartialEq, Hash)]
1122#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1123pub struct FStringFlags(InterpolatedStringFlagsInner);
1124
1125impl FStringFlags {
1126    /// Construct a new [`FStringFlags`] with **no flags set**.
1127    ///
1128    /// See [`FStringFlags::with_quote_style`], [`FStringFlags::with_triple_quotes`], and
1129    /// [`FStringFlags::with_prefix`] for ways of setting the quote style (single or double),
1130    /// enabling triple quotes, and adding prefixes (such as `r`), respectively.
1131    ///
1132    /// See the documentation for [`FStringFlags`] for additional caveats on this constructor, and
1133    /// situations in which alternative ways to construct this struct should be used, especially
1134    /// when writing lint rules.
1135    pub fn empty() -> Self {
1136        Self(InterpolatedStringFlagsInner::empty())
1137    }
1138
1139    #[must_use]
1140    pub fn with_quote_style(mut self, quote_style: Quote) -> Self {
1141        self.0.set(
1142            InterpolatedStringFlagsInner::DOUBLE,
1143            quote_style.is_double(),
1144        );
1145        self
1146    }
1147
1148    #[must_use]
1149    pub fn with_triple_quotes(mut self, triple_quotes: TripleQuotes) -> Self {
1150        self.0.set(
1151            InterpolatedStringFlagsInner::TRIPLE_QUOTED,
1152            triple_quotes.is_yes(),
1153        );
1154        self
1155    }
1156
1157    #[must_use]
1158    pub fn with_unclosed(mut self, unclosed: bool) -> Self {
1159        self.0.set(InterpolatedStringFlagsInner::UNCLOSED, unclosed);
1160        self
1161    }
1162
1163    #[must_use]
1164    pub fn with_prefix(mut self, prefix: FStringPrefix) -> Self {
1165        match prefix {
1166            FStringPrefix::Regular => Self(
1167                self.0
1168                    - InterpolatedStringFlagsInner::R_PREFIX_LOWER
1169                    - InterpolatedStringFlagsInner::R_PREFIX_UPPER,
1170            ),
1171            FStringPrefix::Raw { uppercase_r } => {
1172                self.0
1173                    .set(InterpolatedStringFlagsInner::R_PREFIX_UPPER, uppercase_r);
1174                self.0
1175                    .set(InterpolatedStringFlagsInner::R_PREFIX_LOWER, !uppercase_r);
1176                self
1177            }
1178        }
1179    }
1180
1181    pub const fn prefix(self) -> FStringPrefix {
1182        if self
1183            .0
1184            .contains(InterpolatedStringFlagsInner::R_PREFIX_LOWER)
1185        {
1186            debug_assert!(
1187                !self
1188                    .0
1189                    .contains(InterpolatedStringFlagsInner::R_PREFIX_UPPER)
1190            );
1191            FStringPrefix::Raw { uppercase_r: false }
1192        } else if self
1193            .0
1194            .contains(InterpolatedStringFlagsInner::R_PREFIX_UPPER)
1195        {
1196            FStringPrefix::Raw { uppercase_r: true }
1197        } else {
1198            FStringPrefix::Regular
1199        }
1200    }
1201}
1202
1203// TODO(dylan): the documentation about using
1204// `Checker::default_tstring_flags` is not yet
1205// correct. This method does not yet exist because
1206// introducing it would emit a dead code warning
1207// until we call it in lint rules.
1208/// Flags that can be queried to obtain information
1209/// regarding the prefixes and quotes used for an f-string.
1210///
1211/// Note: This is identical to [`FStringFlags`] except that
1212/// the implementation of the `prefix` method of the
1213/// [`StringFlags`] trait returns a variant of
1214/// `AnyStringPrefix::Template`.
1215///
1216/// ## Notes on usage
1217///
1218/// If you're using a `Generator` from the `ruff_python_codegen` crate to generate a lint-rule fix
1219/// from an existing t-string literal, consider passing along the [`FString::flags`] field. If you
1220/// don't have an existing literal but have a `Checker` from the `ruff_linter` crate available,
1221/// consider using `Checker::default_tstring_flags` to create instances of this struct; this method
1222/// will properly handle nested t-strings. For usage that doesn't fit into one of these categories,
1223/// the public constructor [`TStringFlags::empty`] can be used.
1224#[derive(Copy, Clone, Eq, PartialEq, Hash)]
1225#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1226pub struct TStringFlags(InterpolatedStringFlagsInner);
1227
1228impl TStringFlags {
1229    /// Construct a new [`TStringFlags`] with **no flags set**.
1230    ///
1231    /// See [`TStringFlags::with_quote_style`], [`TStringFlags::with_triple_quotes`], and
1232    /// [`TStringFlags::with_prefix`] for ways of setting the quote style (single or double),
1233    /// enabling triple quotes, and adding prefixes (such as `r`), respectively.
1234    ///
1235    /// See the documentation for [`TStringFlags`] for additional caveats on this constructor, and
1236    /// situations in which alternative ways to construct this struct should be used, especially
1237    /// when writing lint rules.
1238    pub fn empty() -> Self {
1239        Self(InterpolatedStringFlagsInner::empty())
1240    }
1241
1242    #[must_use]
1243    pub fn with_quote_style(mut self, quote_style: Quote) -> Self {
1244        self.0.set(
1245            InterpolatedStringFlagsInner::DOUBLE,
1246            quote_style.is_double(),
1247        );
1248        self
1249    }
1250
1251    #[must_use]
1252    pub fn with_triple_quotes(mut self, triple_quotes: TripleQuotes) -> Self {
1253        self.0.set(
1254            InterpolatedStringFlagsInner::TRIPLE_QUOTED,
1255            triple_quotes.is_yes(),
1256        );
1257        self
1258    }
1259
1260    #[must_use]
1261    pub fn with_unclosed(mut self, unclosed: bool) -> Self {
1262        self.0.set(InterpolatedStringFlagsInner::UNCLOSED, unclosed);
1263        self
1264    }
1265
1266    #[must_use]
1267    pub fn with_prefix(mut self, prefix: TStringPrefix) -> Self {
1268        match prefix {
1269            TStringPrefix::Regular => Self(
1270                self.0
1271                    - InterpolatedStringFlagsInner::R_PREFIX_LOWER
1272                    - InterpolatedStringFlagsInner::R_PREFIX_UPPER,
1273            ),
1274            TStringPrefix::Raw { uppercase_r } => {
1275                self.0
1276                    .set(InterpolatedStringFlagsInner::R_PREFIX_UPPER, uppercase_r);
1277                self.0
1278                    .set(InterpolatedStringFlagsInner::R_PREFIX_LOWER, !uppercase_r);
1279                self
1280            }
1281        }
1282    }
1283
1284    pub const fn prefix(self) -> TStringPrefix {
1285        if self
1286            .0
1287            .contains(InterpolatedStringFlagsInner::R_PREFIX_LOWER)
1288        {
1289            debug_assert!(
1290                !self
1291                    .0
1292                    .contains(InterpolatedStringFlagsInner::R_PREFIX_UPPER)
1293            );
1294            TStringPrefix::Raw { uppercase_r: false }
1295        } else if self
1296            .0
1297            .contains(InterpolatedStringFlagsInner::R_PREFIX_UPPER)
1298        {
1299            TStringPrefix::Raw { uppercase_r: true }
1300        } else {
1301            TStringPrefix::Regular
1302        }
1303    }
1304}
1305
1306impl StringFlags for FStringFlags {
1307    /// Return `true` if the f-string is triple-quoted, i.e.,
1308    /// it begins and ends with three consecutive quote characters.
1309    /// For example: `f"""{bar}"""`
1310    fn triple_quotes(self) -> TripleQuotes {
1311        if self.0.contains(InterpolatedStringFlagsInner::TRIPLE_QUOTED) {
1312            TripleQuotes::Yes
1313        } else {
1314            TripleQuotes::No
1315        }
1316    }
1317
1318    /// Return the quoting style (single or double quotes)
1319    /// used by the f-string's opener and closer:
1320    /// - `f"{"a"}"` -> `QuoteStyle::Double`
1321    /// - `f'{"a"}'` -> `QuoteStyle::Single`
1322    fn quote_style(self) -> Quote {
1323        if self.0.contains(InterpolatedStringFlagsInner::DOUBLE) {
1324            Quote::Double
1325        } else {
1326            Quote::Single
1327        }
1328    }
1329
1330    fn prefix(self) -> AnyStringPrefix {
1331        AnyStringPrefix::Format(self.prefix())
1332    }
1333
1334    fn is_unclosed(self) -> bool {
1335        self.0.intersects(InterpolatedStringFlagsInner::UNCLOSED)
1336    }
1337}
1338
1339impl fmt::Debug for FStringFlags {
1340    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1341        f.debug_struct("FStringFlags")
1342            .field("quote_style", &self.quote_style())
1343            .field("prefix", &self.prefix())
1344            .field("triple_quoted", &self.is_triple_quoted())
1345            .field("unclosed", &self.is_unclosed())
1346            .finish()
1347    }
1348}
1349
1350impl StringFlags for TStringFlags {
1351    /// Return `true` if the t-string is triple-quoted, i.e.,
1352    /// it begins and ends with three consecutive quote characters.
1353    /// For example: `t"""{bar}"""`
1354    fn triple_quotes(self) -> TripleQuotes {
1355        if self.0.contains(InterpolatedStringFlagsInner::TRIPLE_QUOTED) {
1356            TripleQuotes::Yes
1357        } else {
1358            TripleQuotes::No
1359        }
1360    }
1361
1362    /// Return the quoting style (single or double quotes)
1363    /// used by the t-string's opener and closer:
1364    /// - `t"{"a"}"` -> `QuoteStyle::Double`
1365    /// - `t'{"a"}'` -> `QuoteStyle::Single`
1366    fn quote_style(self) -> Quote {
1367        if self.0.contains(InterpolatedStringFlagsInner::DOUBLE) {
1368            Quote::Double
1369        } else {
1370            Quote::Single
1371        }
1372    }
1373
1374    fn prefix(self) -> AnyStringPrefix {
1375        AnyStringPrefix::Template(self.prefix())
1376    }
1377
1378    fn is_unclosed(self) -> bool {
1379        self.0.intersects(InterpolatedStringFlagsInner::UNCLOSED)
1380    }
1381}
1382
1383impl fmt::Debug for TStringFlags {
1384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1385        f.debug_struct("TStringFlags")
1386            .field("quote_style", &self.quote_style())
1387            .field("prefix", &self.prefix())
1388            .field("triple_quoted", &self.is_triple_quoted())
1389            .field("unclosed", &self.is_unclosed())
1390            .finish()
1391    }
1392}
1393
1394/// An AST node that represents a single f-string which is part of an [`ExprFString`].
1395#[derive(Clone, Debug, PartialEq)]
1396#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1397pub struct FString {
1398    pub range: TextRange,
1399    pub node_index: AtomicNodeIndex,
1400    pub elements: InterpolatedStringElements,
1401    pub flags: FStringFlags,
1402}
1403
1404impl From<FString> for Expr {
1405    fn from(payload: FString) -> Self {
1406        ExprFString {
1407            node_index: payload.node_index.clone(),
1408            range: payload.range,
1409            value: FStringValue::single(payload),
1410        }
1411        .into()
1412    }
1413}
1414
1415/// A newtype wrapper around a list of [`InterpolatedStringElement`].
1416#[derive(Clone, Default, PartialEq)]
1417#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1418pub struct InterpolatedStringElements(Box<[InterpolatedStringElement]>);
1419
1420impl InterpolatedStringElements {
1421    /// Returns an iterator over all the [`InterpolatedStringLiteralElement`] nodes contained in this f-string.
1422    pub fn literals(&self) -> impl Iterator<Item = &InterpolatedStringLiteralElement> {
1423        self.iter().filter_map(|element| element.as_literal())
1424    }
1425
1426    /// Returns an iterator over all the [`InterpolatedElement`] nodes contained in this f-string.
1427    pub fn interpolations(&self) -> impl Iterator<Item = &InterpolatedElement> {
1428        self.iter().filter_map(|element| element.as_interpolation())
1429    }
1430}
1431
1432impl From<Vec<InterpolatedStringElement>> for InterpolatedStringElements {
1433    fn from(elements: Vec<InterpolatedStringElement>) -> Self {
1434        InterpolatedStringElements(elements.into_boxed_slice())
1435    }
1436}
1437
1438impl<'a> IntoIterator for &'a InterpolatedStringElements {
1439    type IntoIter = Iter<'a, InterpolatedStringElement>;
1440    type Item = &'a InterpolatedStringElement;
1441
1442    fn into_iter(self) -> Self::IntoIter {
1443        self.iter()
1444    }
1445}
1446
1447impl<'a> IntoIterator for &'a mut InterpolatedStringElements {
1448    type IntoIter = IterMut<'a, InterpolatedStringElement>;
1449    type Item = &'a mut InterpolatedStringElement;
1450
1451    fn into_iter(self) -> Self::IntoIter {
1452        self.iter_mut()
1453    }
1454}
1455
1456impl Deref for InterpolatedStringElements {
1457    type Target = [InterpolatedStringElement];
1458
1459    fn deref(&self) -> &Self::Target {
1460        &self.0
1461    }
1462}
1463
1464impl DerefMut for InterpolatedStringElements {
1465    fn deref_mut(&mut self) -> &mut Self::Target {
1466        &mut self.0
1467    }
1468}
1469
1470impl fmt::Debug for InterpolatedStringElements {
1471    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1472        fmt::Debug::fmt(&self.0, f)
1473    }
1474}
1475
1476/// An AST node that represents a single t-string which is part of an [`ExprTString`].
1477#[derive(Clone, Debug, PartialEq)]
1478#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1479pub struct TString {
1480    pub range: TextRange,
1481    pub node_index: AtomicNodeIndex,
1482    pub elements: InterpolatedStringElements,
1483    pub flags: TStringFlags,
1484}
1485
1486impl TString {
1487    pub fn quote_style(&self) -> Quote {
1488        self.flags.quote_style()
1489    }
1490
1491    pub fn is_empty(&self) -> bool {
1492        self.elements.is_empty()
1493    }
1494}
1495
1496impl From<TString> for Expr {
1497    fn from(payload: TString) -> Self {
1498        ExprTString {
1499            node_index: payload.node_index.clone(),
1500            range: payload.range,
1501            value: TStringValue::single(payload),
1502        }
1503        .into()
1504    }
1505}
1506
1507impl ExprStringLiteral {
1508    /// Return `Some(literal)` if the string only consists of a single `StringLiteral` part
1509    /// (indicating that it is not implicitly concatenated). Otherwise, return `None`.
1510    pub fn as_single_part_string(&self) -> Option<&StringLiteral> {
1511        match &self.value.inner {
1512            StringLiteralValueInner::Single(value) => Some(value),
1513            StringLiteralValueInner::Concatenated(_) => None,
1514        }
1515    }
1516}
1517
1518impl Ranged for ExprCall {
1519    fn range(&self) -> TextRange {
1520        TextRange::new(self.range_start, self.arguments.end())
1521    }
1522}
1523
1524#[expect(
1525    clippy::missing_fields_in_debug,
1526    reason = "`range_start` is represented by the reconstructed `range` field"
1527)]
1528impl fmt::Debug for ExprCall {
1529    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1530        formatter
1531            .debug_struct("ExprCall")
1532            .field("node_index", &self.node_index)
1533            .field("range", &self.range())
1534            .field("func", &self.func)
1535            .field("arguments", &self.arguments)
1536            .finish()
1537    }
1538}
1539
1540/// The value representing a [`ExprStringLiteral`].
1541#[derive(Clone, Debug, PartialEq)]
1542#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1543pub struct StringLiteralValue {
1544    inner: StringLiteralValueInner,
1545}
1546
1547impl StringLiteralValue {
1548    /// Creates a new string literal with a single [`StringLiteral`] part.
1549    pub fn single(string: StringLiteral) -> Self {
1550        Self {
1551            inner: StringLiteralValueInner::Single(string),
1552        }
1553    }
1554
1555    /// Returns the [`StringLiteralFlags`] associated with this string literal.
1556    ///
1557    /// For an implicitly concatenated string, it returns the flags for the first literal.
1558    pub fn first_literal_flags(&self) -> StringLiteralFlags {
1559        self.iter()
1560            .next()
1561            .expect(
1562                "There should always be at least one string literal in an `ExprStringLiteral` node",
1563            )
1564            .flags
1565    }
1566
1567    /// Creates a new string literal with the given values that represents an
1568    /// implicitly concatenated strings.
1569    ///
1570    /// # Panics
1571    ///
1572    /// Panics if `strings` has less than 2 elements.
1573    /// Use [`StringLiteralValue::single`] instead.
1574    pub fn concatenated(strings: Vec<StringLiteral>) -> Self {
1575        assert!(
1576            strings.len() > 1,
1577            "Use `StringLiteralValue::single` to create single-part strings"
1578        );
1579        Self {
1580            inner: StringLiteralValueInner::Concatenated(Box::new(ConcatenatedStringLiteral {
1581                strings,
1582                value: OnceLock::new(),
1583            })),
1584        }
1585    }
1586
1587    /// Returns `true` if the string literal is implicitly concatenated.
1588    pub const fn is_implicit_concatenated(&self) -> bool {
1589        matches!(self.inner, StringLiteralValueInner::Concatenated(_))
1590    }
1591
1592    /// Returns `true` if the string literal has a `u` prefix, e.g. `u"foo"`.
1593    ///
1594    /// Although all strings in Python 3 are valid unicode (and the `u` prefix
1595    /// is only retained for backwards compatibility), these strings are known as
1596    /// "unicode strings".
1597    ///
1598    /// For an implicitly concatenated string, it returns `true` only if the first
1599    /// [`StringLiteral`] has the `u` prefix.
1600    pub fn is_unicode(&self) -> bool {
1601        self.iter()
1602            .next()
1603            .is_some_and(|part| part.flags.prefix().is_unicode())
1604    }
1605
1606    /// Returns a slice of all the [`StringLiteral`] parts contained in this value.
1607    pub fn as_slice(&self) -> &[StringLiteral] {
1608        match &self.inner {
1609            StringLiteralValueInner::Single(value) => std::slice::from_ref(value),
1610            StringLiteralValueInner::Concatenated(value) => value.strings.as_slice(),
1611        }
1612    }
1613
1614    /// Returns a mutable slice of all the [`StringLiteral`] parts contained in this value.
1615    fn as_mut_slice(&mut self) -> &mut [StringLiteral] {
1616        match &mut self.inner {
1617            StringLiteralValueInner::Single(value) => std::slice::from_mut(value),
1618            StringLiteralValueInner::Concatenated(value) => value.strings.as_mut_slice(),
1619        }
1620    }
1621
1622    /// Returns an iterator over all the [`StringLiteral`] parts contained in this value.
1623    pub fn iter(&self) -> Iter<'_, StringLiteral> {
1624        self.as_slice().iter()
1625    }
1626
1627    /// Returns an iterator over all the [`StringLiteral`] parts contained in this value
1628    /// that allows modification.
1629    pub fn iter_mut(&mut self) -> IterMut<'_, StringLiteral> {
1630        self.as_mut_slice().iter_mut()
1631    }
1632
1633    /// Returns `true` if the node represents an empty string.
1634    ///
1635    /// Note that a [`StringLiteralValue`] node will always have >=1 [`StringLiteral`] parts
1636    /// inside it. This method checks whether the value of the concatenated parts is equal
1637    /// to the empty string, not whether the string has 0 parts inside it.
1638    pub fn is_empty(&self) -> bool {
1639        self.len() == 0
1640    }
1641
1642    /// Returns the total length of the string literal value, in bytes, not
1643    /// [`char`]s or graphemes.
1644    pub fn len(&self) -> usize {
1645        self.iter().fold(0, |acc, part| acc + part.value.len())
1646    }
1647
1648    /// Returns an iterator over the [`char`]s of each string literal part.
1649    pub fn chars(&self) -> impl Iterator<Item = char> + Clone + '_ {
1650        self.iter().flat_map(|part| part.value.chars())
1651    }
1652
1653    /// Returns the concatenated string value as a [`str`].
1654    ///
1655    /// Note that this will perform an allocation on the first invocation if the
1656    /// string value is implicitly concatenated.
1657    pub fn to_str(&self) -> &str {
1658        match &self.inner {
1659            StringLiteralValueInner::Single(value) => value.as_str(),
1660            StringLiteralValueInner::Concatenated(value) => value.to_str(),
1661        }
1662    }
1663}
1664
1665impl<'a> IntoIterator for &'a StringLiteralValue {
1666    type Item = &'a StringLiteral;
1667    type IntoIter = Iter<'a, StringLiteral>;
1668
1669    fn into_iter(self) -> Self::IntoIter {
1670        self.iter()
1671    }
1672}
1673
1674impl<'a> IntoIterator for &'a mut StringLiteralValue {
1675    type Item = &'a mut StringLiteral;
1676    type IntoIter = IterMut<'a, StringLiteral>;
1677    fn into_iter(self) -> Self::IntoIter {
1678        self.iter_mut()
1679    }
1680}
1681
1682impl PartialEq<str> for StringLiteralValue {
1683    fn eq(&self, other: &str) -> bool {
1684        if self.len() != other.len() {
1685            return false;
1686        }
1687        // The `zip` here is safe because we have checked the length of both parts.
1688        self.chars().zip(other.chars()).all(|(c1, c2)| c1 == c2)
1689    }
1690}
1691
1692impl fmt::Display for StringLiteralValue {
1693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1694        f.write_str(self.to_str())
1695    }
1696}
1697
1698/// An internal representation of [`StringLiteralValue`].
1699#[derive(Clone, Debug, PartialEq)]
1700#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1701enum StringLiteralValueInner {
1702    /// A single string literal i.e., `"foo"`.
1703    Single(StringLiteral),
1704
1705    /// An implicitly concatenated string literals i.e., `"foo" "bar"`.
1706    Concatenated(Box<ConcatenatedStringLiteral>),
1707}
1708
1709bitflags! {
1710    #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
1711    struct StringLiteralFlagsInner: u8 {
1712        /// The string uses double quotes (e.g. `"foo"`).
1713        /// If this flag is not set, the string uses single quotes (`'foo'`).
1714        const DOUBLE = 1 << 0;
1715
1716        /// The string is triple-quoted (`"""foo"""`):
1717        /// it begins and ends with three consecutive quote characters.
1718        const TRIPLE_QUOTED = 1 << 1;
1719
1720        /// The string has a `u` or `U` prefix, e.g. `u"foo"`.
1721        /// While this prefix is a no-op at runtime,
1722        /// strings with this prefix can have no other prefixes set;
1723        /// it is therefore invalid for this flag to be set
1724        /// if `R_PREFIX` is also set.
1725        const U_PREFIX = 1 << 2;
1726
1727        /// The string has an `r` prefix, meaning it is a raw string
1728        /// with a lowercase 'r' (e.g. `r"foo\."`).
1729        /// It is invalid to set this flag if `U_PREFIX` is also set.
1730        const R_PREFIX_LOWER = 1 << 3;
1731
1732        /// The string has an `R` prefix, meaning it is a raw string
1733        /// with an uppercase 'R' (e.g. `R'foo\d'`).
1734        /// See https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#r-strings-and-r-strings
1735        /// for why we track the casing of the `r` prefix,
1736        /// but not for any other prefix
1737        const R_PREFIX_UPPER = 1 << 4;
1738
1739        /// The string was deemed invalid by the parser.
1740        const INVALID = 1 << 5;
1741
1742        /// The string literal misses the matching closing quote(s).
1743        const UNCLOSED = 1 << 6;
1744    }
1745}
1746
1747#[cfg(feature = "get-size")]
1748impl get_size2::GetSize for StringLiteralFlagsInner {}
1749
1750/// Flags that can be queried to obtain information
1751/// regarding the prefixes and quotes used for a string literal.
1752///
1753/// ## Notes on usage
1754///
1755/// If you're using a `Generator` from the `ruff_python_codegen` crate to generate a lint-rule fix
1756/// from an existing string literal, consider passing along the [`StringLiteral::flags`] field or
1757/// the result of the [`StringLiteralValue::first_literal_flags`] method. If you don't have an
1758/// existing string but have a `Checker` from the `ruff_linter` crate available, consider using
1759/// `Checker::default_string_flags` to create instances of this struct; this method will properly
1760/// handle surrounding f-strings. For usage that doesn't fit into one of these categories, the
1761/// public constructor [`StringLiteralFlags::empty`] can be used.
1762#[derive(Copy, Clone, Eq, PartialEq, Hash)]
1763#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1764pub struct StringLiteralFlags(StringLiteralFlagsInner);
1765
1766impl StringLiteralFlags {
1767    /// Construct a new [`StringLiteralFlags`] with **no flags set**.
1768    ///
1769    /// See [`StringLiteralFlags::with_quote_style`], [`StringLiteralFlags::with_triple_quotes`],
1770    /// and [`StringLiteralFlags::with_prefix`] for ways of setting the quote style (single or
1771    /// double), enabling triple quotes, and adding prefixes (such as `r` or `u`), respectively.
1772    ///
1773    /// See the documentation for [`StringLiteralFlags`] for additional caveats on this constructor,
1774    /// and situations in which alternative ways to construct this struct should be used, especially
1775    /// when writing lint rules.
1776    pub fn empty() -> Self {
1777        Self(StringLiteralFlagsInner::empty())
1778    }
1779
1780    #[must_use]
1781    pub fn with_quote_style(mut self, quote_style: Quote) -> Self {
1782        self.0
1783            .set(StringLiteralFlagsInner::DOUBLE, quote_style.is_double());
1784        self
1785    }
1786
1787    #[must_use]
1788    pub fn with_triple_quotes(mut self, triple_quotes: TripleQuotes) -> Self {
1789        self.0.set(
1790            StringLiteralFlagsInner::TRIPLE_QUOTED,
1791            triple_quotes.is_yes(),
1792        );
1793        self
1794    }
1795
1796    #[must_use]
1797    pub fn with_unclosed(mut self, unclosed: bool) -> Self {
1798        self.0.set(StringLiteralFlagsInner::UNCLOSED, unclosed);
1799        self
1800    }
1801
1802    #[must_use]
1803    pub fn with_prefix(self, prefix: StringLiteralPrefix) -> Self {
1804        let StringLiteralFlags(flags) = self;
1805        match prefix {
1806            StringLiteralPrefix::Empty => Self(
1807                flags
1808                    - StringLiteralFlagsInner::R_PREFIX_LOWER
1809                    - StringLiteralFlagsInner::R_PREFIX_UPPER
1810                    - StringLiteralFlagsInner::U_PREFIX,
1811            ),
1812            StringLiteralPrefix::Raw { uppercase: false } => Self(
1813                (flags | StringLiteralFlagsInner::R_PREFIX_LOWER)
1814                    - StringLiteralFlagsInner::R_PREFIX_UPPER
1815                    - StringLiteralFlagsInner::U_PREFIX,
1816            ),
1817            StringLiteralPrefix::Raw { uppercase: true } => Self(
1818                (flags | StringLiteralFlagsInner::R_PREFIX_UPPER)
1819                    - StringLiteralFlagsInner::R_PREFIX_LOWER
1820                    - StringLiteralFlagsInner::U_PREFIX,
1821            ),
1822            StringLiteralPrefix::Unicode => Self(
1823                (flags | StringLiteralFlagsInner::U_PREFIX)
1824                    - StringLiteralFlagsInner::R_PREFIX_LOWER
1825                    - StringLiteralFlagsInner::R_PREFIX_UPPER,
1826            ),
1827        }
1828    }
1829
1830    #[must_use]
1831    pub fn with_invalid(mut self) -> Self {
1832        self.0 |= StringLiteralFlagsInner::INVALID;
1833        self
1834    }
1835
1836    /// Returns `true` if the parser deemed the string literal invalid.
1837    pub const fn is_invalid(self) -> bool {
1838        self.0.contains(StringLiteralFlagsInner::INVALID)
1839    }
1840
1841    pub const fn prefix(self) -> StringLiteralPrefix {
1842        if self.0.contains(StringLiteralFlagsInner::U_PREFIX) {
1843            debug_assert!(
1844                !self.0.intersects(
1845                    StringLiteralFlagsInner::R_PREFIX_LOWER
1846                        .union(StringLiteralFlagsInner::R_PREFIX_UPPER)
1847                )
1848            );
1849            StringLiteralPrefix::Unicode
1850        } else if self.0.contains(StringLiteralFlagsInner::R_PREFIX_LOWER) {
1851            debug_assert!(!self.0.contains(StringLiteralFlagsInner::R_PREFIX_UPPER));
1852            StringLiteralPrefix::Raw { uppercase: false }
1853        } else if self.0.contains(StringLiteralFlagsInner::R_PREFIX_UPPER) {
1854            StringLiteralPrefix::Raw { uppercase: true }
1855        } else {
1856            StringLiteralPrefix::Empty
1857        }
1858    }
1859}
1860
1861impl StringFlags for StringLiteralFlags {
1862    /// Return the quoting style (single or double quotes)
1863    /// used by the string's opener and closer:
1864    /// - `"a"` -> `QuoteStyle::Double`
1865    /// - `'a'` -> `QuoteStyle::Single`
1866    fn quote_style(self) -> Quote {
1867        if self.0.contains(StringLiteralFlagsInner::DOUBLE) {
1868            Quote::Double
1869        } else {
1870            Quote::Single
1871        }
1872    }
1873
1874    /// Return `true` if the string is triple-quoted, i.e.,
1875    /// it begins and ends with three consecutive quote characters.
1876    /// For example: `"""bar"""`
1877    fn triple_quotes(self) -> TripleQuotes {
1878        if self.0.contains(StringLiteralFlagsInner::TRIPLE_QUOTED) {
1879            TripleQuotes::Yes
1880        } else {
1881            TripleQuotes::No
1882        }
1883    }
1884
1885    fn prefix(self) -> AnyStringPrefix {
1886        AnyStringPrefix::Regular(self.prefix())
1887    }
1888
1889    fn is_unclosed(self) -> bool {
1890        self.0.intersects(StringLiteralFlagsInner::UNCLOSED)
1891    }
1892}
1893
1894impl fmt::Debug for StringLiteralFlags {
1895    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1896        f.debug_struct("StringLiteralFlags")
1897            .field("quote_style", &self.quote_style())
1898            .field("prefix", &self.prefix())
1899            .field("triple_quoted", &self.is_triple_quoted())
1900            .field("unclosed", &self.is_unclosed())
1901            .finish()
1902    }
1903}
1904
1905/// An AST node that represents a single string literal which is part of an
1906/// [`ExprStringLiteral`].
1907#[derive(Clone, Debug, PartialEq)]
1908#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1909pub struct StringLiteral {
1910    pub range: TextRange,
1911    pub node_index: AtomicNodeIndex,
1912    pub value: Box<str>,
1913    pub flags: StringLiteralFlags,
1914}
1915
1916impl Deref for StringLiteral {
1917    type Target = str;
1918
1919    fn deref(&self) -> &Self::Target {
1920        &self.value
1921    }
1922}
1923
1924impl StringLiteral {
1925    /// Extracts a string slice containing the entire `String`.
1926    pub fn as_str(&self) -> &str {
1927        self
1928    }
1929
1930    /// Creates an invalid string literal with the given range.
1931    pub fn invalid(range: TextRange) -> Self {
1932        Self {
1933            range,
1934            value: "".into(),
1935            node_index: AtomicNodeIndex::NONE,
1936            flags: StringLiteralFlags::empty().with_invalid(),
1937        }
1938    }
1939
1940    /// The range of the string literal's contents.
1941    ///
1942    /// This excludes any prefixes, opening quotes or closing quotes.
1943    pub fn content_range(&self) -> TextRange {
1944        TextRange::new(
1945            self.start() + self.flags.opener_len(),
1946            self.end() - self.flags.closer_len(),
1947        )
1948    }
1949}
1950
1951impl From<StringLiteral> for Expr {
1952    fn from(payload: StringLiteral) -> Self {
1953        ExprStringLiteral {
1954            range: payload.range,
1955            node_index: AtomicNodeIndex::NONE,
1956            value: StringLiteralValue::single(payload),
1957        }
1958        .into()
1959    }
1960}
1961
1962/// An internal representation of [`StringLiteral`] that represents an
1963/// implicitly concatenated string.
1964#[derive(Clone)]
1965#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1966struct ConcatenatedStringLiteral {
1967    /// The individual [`StringLiteral`] parts that make up the concatenated string.
1968    strings: Vec<StringLiteral>,
1969    /// The concatenated string value.
1970    value: OnceLock<Box<str>>,
1971}
1972
1973impl ConcatenatedStringLiteral {
1974    /// Extracts a string slice containing the entire concatenated string.
1975    fn to_str(&self) -> &str {
1976        self.value.get_or_init(|| {
1977            let concatenated: String = self.strings.iter().map(StringLiteral::as_str).collect();
1978            concatenated.into_boxed_str()
1979        })
1980    }
1981}
1982
1983impl PartialEq for ConcatenatedStringLiteral {
1984    fn eq(&self, other: &Self) -> bool {
1985        if self.strings.len() != other.strings.len() {
1986            return false;
1987        }
1988        // The `zip` here is safe because we have checked the length of both parts.
1989        self.strings
1990            .iter()
1991            .zip(&other.strings)
1992            .all(|(s1, s2)| s1 == s2)
1993    }
1994}
1995
1996impl Debug for ConcatenatedStringLiteral {
1997    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1998        f.debug_struct("ConcatenatedStringLiteral")
1999            .field("strings", &self.strings)
2000            .field("value", &self.to_str())
2001            .finish()
2002    }
2003}
2004
2005impl ExprBytesLiteral {
2006    /// Return `Some(literal)` if the bytestring only consists of a single `BytesLiteral` part
2007    /// (indicating that it is not implicitly concatenated). Otherwise, return `None`.
2008    pub const fn as_single_part_bytestring(&self) -> Option<&BytesLiteral> {
2009        match &self.value.inner {
2010            BytesLiteralValueInner::Single(value) => Some(value),
2011            BytesLiteralValueInner::Concatenated(_) => None,
2012        }
2013    }
2014}
2015
2016/// The value representing a [`ExprBytesLiteral`].
2017#[derive(Clone, Debug, PartialEq)]
2018#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2019pub struct BytesLiteralValue {
2020    inner: BytesLiteralValueInner,
2021}
2022
2023impl BytesLiteralValue {
2024    /// Create a new bytestring literal with a single [`BytesLiteral`] part.
2025    pub fn single(value: BytesLiteral) -> Self {
2026        Self {
2027            inner: BytesLiteralValueInner::Single(value),
2028        }
2029    }
2030
2031    /// Creates a new bytestring literal with the given values that represents an
2032    /// implicitly concatenated bytestring.
2033    ///
2034    /// # Panics
2035    ///
2036    /// Panics if `values` has less than 2 elements.
2037    /// Use [`BytesLiteralValue::single`] instead.
2038    pub fn concatenated(values: Vec<BytesLiteral>) -> Self {
2039        assert!(
2040            values.len() > 1,
2041            "Use `BytesLiteralValue::single` to create single-part bytestrings"
2042        );
2043        Self {
2044            inner: BytesLiteralValueInner::Concatenated(values),
2045        }
2046    }
2047
2048    /// Returns `true` if the bytestring is implicitly concatenated.
2049    pub const fn is_implicit_concatenated(&self) -> bool {
2050        matches!(self.inner, BytesLiteralValueInner::Concatenated(_))
2051    }
2052
2053    /// Returns a slice of all the [`BytesLiteral`] parts contained in this value.
2054    pub fn as_slice(&self) -> &[BytesLiteral] {
2055        match &self.inner {
2056            BytesLiteralValueInner::Single(value) => std::slice::from_ref(value),
2057            BytesLiteralValueInner::Concatenated(value) => value.as_slice(),
2058        }
2059    }
2060
2061    /// Returns a mutable slice of all the [`BytesLiteral`] parts contained in this value.
2062    fn as_mut_slice(&mut self) -> &mut [BytesLiteral] {
2063        match &mut self.inner {
2064            BytesLiteralValueInner::Single(value) => std::slice::from_mut(value),
2065            BytesLiteralValueInner::Concatenated(value) => value.as_mut_slice(),
2066        }
2067    }
2068
2069    /// Returns an iterator over all the [`BytesLiteral`] parts contained in this value.
2070    pub fn iter(&self) -> Iter<'_, BytesLiteral> {
2071        self.as_slice().iter()
2072    }
2073
2074    /// Returns an iterator over all the [`BytesLiteral`] parts contained in this value
2075    /// that allows modification.
2076    pub fn iter_mut(&mut self) -> IterMut<'_, BytesLiteral> {
2077        self.as_mut_slice().iter_mut()
2078    }
2079
2080    /// Return `true` if the node represents an empty bytestring.
2081    ///
2082    /// Note that a [`BytesLiteralValue`] node will always have >=1 [`BytesLiteral`] parts
2083    /// inside it. This method checks whether the value of the concatenated parts is equal
2084    /// to the empty bytestring, not whether the bytestring has 0 parts inside it.
2085    pub fn is_empty(&self) -> bool {
2086        self.iter().all(|part| part.is_empty())
2087    }
2088
2089    /// Returns the length of the concatenated bytestring.
2090    pub fn len(&self) -> usize {
2091        self.iter().map(|part| part.len()).sum()
2092    }
2093
2094    /// Returns an iterator over the bytes of the concatenated bytestring.
2095    pub fn bytes(&self) -> impl Iterator<Item = u8> + '_ {
2096        self.iter().flat_map(|part| part.as_slice().iter().copied())
2097    }
2098}
2099
2100impl<'a> IntoIterator for &'a BytesLiteralValue {
2101    type Item = &'a BytesLiteral;
2102    type IntoIter = Iter<'a, BytesLiteral>;
2103
2104    fn into_iter(self) -> Self::IntoIter {
2105        self.iter()
2106    }
2107}
2108
2109impl<'a> IntoIterator for &'a mut BytesLiteralValue {
2110    type Item = &'a mut BytesLiteral;
2111    type IntoIter = IterMut<'a, BytesLiteral>;
2112    fn into_iter(self) -> Self::IntoIter {
2113        self.iter_mut()
2114    }
2115}
2116
2117impl PartialEq<[u8]> for BytesLiteralValue {
2118    fn eq(&self, other: &[u8]) -> bool {
2119        if self.len() != other.len() {
2120            return false;
2121        }
2122        // The `zip` here is safe because we have checked the length of both parts.
2123        self.bytes()
2124            .zip(other.iter().copied())
2125            .all(|(b1, b2)| b1 == b2)
2126    }
2127}
2128
2129impl<'a> From<&'a BytesLiteralValue> for Cow<'a, [u8]> {
2130    fn from(value: &'a BytesLiteralValue) -> Self {
2131        match value.as_slice() {
2132            [part] => Cow::Borrowed(part.as_slice()),
2133            parts => {
2134                let mut joined = Vec::with_capacity(value.len());
2135                for part in parts {
2136                    joined.extend_from_slice(part.as_slice());
2137                }
2138                Cow::Owned(joined)
2139            }
2140        }
2141    }
2142}
2143
2144/// An internal representation of [`BytesLiteralValue`].
2145#[derive(Clone, Debug, PartialEq)]
2146#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2147enum BytesLiteralValueInner {
2148    /// A single-part bytestring literal i.e., `b"foo"`.
2149    Single(BytesLiteral),
2150
2151    /// An implicitly concatenated bytestring literal i.e., `b"foo" b"bar"`.
2152    Concatenated(Vec<BytesLiteral>),
2153}
2154
2155bitflags! {
2156    #[derive(Default, Copy, Clone, PartialEq, Eq, Hash)]
2157    struct BytesLiteralFlagsInner: u8 {
2158        /// The bytestring uses double quotes (e.g. `b"foo"`).
2159        /// If this flag is not set, the bytestring uses single quotes (e.g. `b'foo'`).
2160        const DOUBLE = 1 << 0;
2161
2162        /// The bytestring is triple-quoted (e.g. `b"""foo"""`):
2163        /// it begins and ends with three consecutive quote characters.
2164        const TRIPLE_QUOTED = 1 << 1;
2165
2166        /// The bytestring has an `r` prefix (e.g. `rb"foo"`),
2167        /// meaning it is a raw bytestring with a lowercase 'r'.
2168        const R_PREFIX_LOWER = 1 << 2;
2169
2170        /// The bytestring has an `R` prefix (e.g. `Rb"foo"`),
2171        /// meaning it is a raw bytestring with an uppercase 'R'.
2172        /// See https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#r-strings-and-r-strings
2173        /// for why we track the casing of the `r` prefix, but not for any other prefix
2174        const R_PREFIX_UPPER = 1 << 3;
2175
2176        /// The bytestring was deemed invalid by the parser.
2177        const INVALID = 1 << 4;
2178
2179        /// The byte string misses the matching closing quote(s).
2180        const UNCLOSED = 1 << 5;
2181    }
2182}
2183
2184#[cfg(feature = "get-size")]
2185impl get_size2::GetSize for BytesLiteralFlagsInner {}
2186
2187/// Flags that can be queried to obtain information
2188/// regarding the prefixes and quotes used for a bytes literal.
2189///
2190/// ## Notes on usage
2191///
2192/// If you're using a `Generator` from the `ruff_python_codegen` crate to generate a lint-rule fix
2193/// from an existing bytes literal, consider passing along the [`BytesLiteral::flags`] field. If
2194/// you don't have an existing literal but have a `Checker` from the `ruff_linter` crate available,
2195/// consider using `Checker::default_bytes_flags` to create instances of this struct; this method
2196/// will properly handle surrounding f-strings. For usage that doesn't fit into one of these
2197/// categories, the public constructor [`BytesLiteralFlags::empty`] can be used.
2198#[derive(Copy, Clone, Eq, PartialEq, Hash)]
2199#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2200pub struct BytesLiteralFlags(BytesLiteralFlagsInner);
2201
2202impl BytesLiteralFlags {
2203    /// Construct a new [`BytesLiteralFlags`] with **no flags set**.
2204    ///
2205    /// See [`BytesLiteralFlags::with_quote_style`], [`BytesLiteralFlags::with_triple_quotes`], and
2206    /// [`BytesLiteralFlags::with_prefix`] for ways of setting the quote style (single or double),
2207    /// enabling triple quotes, and adding prefixes (such as `r`), respectively.
2208    ///
2209    /// See the documentation for [`BytesLiteralFlags`] for additional caveats on this constructor,
2210    /// and situations in which alternative ways to construct this struct should be used, especially
2211    /// when writing lint rules.
2212    pub fn empty() -> Self {
2213        Self(BytesLiteralFlagsInner::empty())
2214    }
2215
2216    #[must_use]
2217    pub fn with_quote_style(mut self, quote_style: Quote) -> Self {
2218        self.0
2219            .set(BytesLiteralFlagsInner::DOUBLE, quote_style.is_double());
2220        self
2221    }
2222
2223    #[must_use]
2224    pub fn with_triple_quotes(mut self, triple_quotes: TripleQuotes) -> Self {
2225        self.0.set(
2226            BytesLiteralFlagsInner::TRIPLE_QUOTED,
2227            triple_quotes.is_yes(),
2228        );
2229        self
2230    }
2231
2232    #[must_use]
2233    pub fn with_unclosed(mut self, unclosed: bool) -> Self {
2234        self.0.set(BytesLiteralFlagsInner::UNCLOSED, unclosed);
2235        self
2236    }
2237
2238    #[must_use]
2239    pub fn with_prefix(mut self, prefix: ByteStringPrefix) -> Self {
2240        match prefix {
2241            ByteStringPrefix::Regular => {
2242                self.0 -= BytesLiteralFlagsInner::R_PREFIX_LOWER;
2243                self.0 -= BytesLiteralFlagsInner::R_PREFIX_UPPER;
2244            }
2245            ByteStringPrefix::Raw { uppercase_r } => {
2246                self.0
2247                    .set(BytesLiteralFlagsInner::R_PREFIX_UPPER, uppercase_r);
2248                self.0
2249                    .set(BytesLiteralFlagsInner::R_PREFIX_LOWER, !uppercase_r);
2250            }
2251        }
2252        self
2253    }
2254
2255    #[must_use]
2256    pub fn with_invalid(mut self) -> Self {
2257        self.0 |= BytesLiteralFlagsInner::INVALID;
2258        self
2259    }
2260
2261    /// Returns `true` if the parser deemed the bytes literal invalid.
2262    pub const fn is_invalid(self) -> bool {
2263        self.0.contains(BytesLiteralFlagsInner::INVALID)
2264    }
2265
2266    pub const fn prefix(self) -> ByteStringPrefix {
2267        if self.0.contains(BytesLiteralFlagsInner::R_PREFIX_LOWER) {
2268            debug_assert!(!self.0.contains(BytesLiteralFlagsInner::R_PREFIX_UPPER));
2269            ByteStringPrefix::Raw { uppercase_r: false }
2270        } else if self.0.contains(BytesLiteralFlagsInner::R_PREFIX_UPPER) {
2271            ByteStringPrefix::Raw { uppercase_r: true }
2272        } else {
2273            ByteStringPrefix::Regular
2274        }
2275    }
2276}
2277
2278impl StringFlags for BytesLiteralFlags {
2279    /// Return `true` if the bytestring is triple-quoted, i.e.,
2280    /// it begins and ends with three consecutive quote characters.
2281    /// For example: `b"""{bar}"""`
2282    fn triple_quotes(self) -> TripleQuotes {
2283        if self.0.contains(BytesLiteralFlagsInner::TRIPLE_QUOTED) {
2284            TripleQuotes::Yes
2285        } else {
2286            TripleQuotes::No
2287        }
2288    }
2289
2290    /// Return the quoting style (single or double quotes)
2291    /// used by the bytestring's opener and closer:
2292    /// - `b"a"` -> `QuoteStyle::Double`
2293    /// - `b'a'` -> `QuoteStyle::Single`
2294    fn quote_style(self) -> Quote {
2295        if self.0.contains(BytesLiteralFlagsInner::DOUBLE) {
2296            Quote::Double
2297        } else {
2298            Quote::Single
2299        }
2300    }
2301
2302    fn prefix(self) -> AnyStringPrefix {
2303        AnyStringPrefix::Bytes(self.prefix())
2304    }
2305
2306    fn is_unclosed(self) -> bool {
2307        self.0.intersects(BytesLiteralFlagsInner::UNCLOSED)
2308    }
2309}
2310
2311impl fmt::Debug for BytesLiteralFlags {
2312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2313        f.debug_struct("BytesLiteralFlags")
2314            .field("quote_style", &self.quote_style())
2315            .field("prefix", &self.prefix())
2316            .field("triple_quoted", &self.is_triple_quoted())
2317            .field("unclosed", &self.is_unclosed())
2318            .finish()
2319    }
2320}
2321
2322/// An AST node that represents a single bytes literal which is part of an
2323/// [`ExprBytesLiteral`].
2324#[derive(Clone, Debug, PartialEq)]
2325#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2326pub struct BytesLiteral {
2327    pub range: TextRange,
2328    pub node_index: AtomicNodeIndex,
2329    pub value: Box<[u8]>,
2330    pub flags: BytesLiteralFlags,
2331}
2332
2333impl Deref for BytesLiteral {
2334    type Target = [u8];
2335
2336    fn deref(&self) -> &Self::Target {
2337        &self.value
2338    }
2339}
2340
2341impl BytesLiteral {
2342    /// Extracts a byte slice containing the entire [`BytesLiteral`].
2343    pub fn as_slice(&self) -> &[u8] {
2344        self
2345    }
2346
2347    /// Creates a new invalid bytes literal with the given range.
2348    pub fn invalid(range: TextRange) -> Self {
2349        Self {
2350            range,
2351            value: Box::new([]),
2352            node_index: AtomicNodeIndex::NONE,
2353            flags: BytesLiteralFlags::empty().with_invalid(),
2354        }
2355    }
2356
2357    /// The range of the byte literal's contents.
2358    ///
2359    /// This excludes any prefixes, opening quotes or closing quotes.
2360    pub fn content_range(&self) -> TextRange {
2361        TextRange::new(
2362            self.start() + self.flags.opener_len(),
2363            self.end() - self.flags.closer_len(),
2364        )
2365    }
2366}
2367
2368impl From<BytesLiteral> for Expr {
2369    fn from(payload: BytesLiteral) -> Self {
2370        ExprBytesLiteral {
2371            range: payload.range,
2372            node_index: AtomicNodeIndex::NONE,
2373            value: BytesLiteralValue::single(payload),
2374        }
2375        .into()
2376    }
2377}
2378
2379bitflags! {
2380    /// Flags that can be queried to obtain information
2381    /// regarding the prefixes and quotes used for a string literal.
2382    ///
2383    /// Note that not all of these flags can be validly combined -- e.g.,
2384    /// it is invalid to combine the `U_PREFIX` flag with any other
2385    /// of the `*_PREFIX` flags. As such, the recommended way to set the
2386    /// prefix flags is by calling the `as_flags()` method on the
2387    /// `StringPrefix` enum.
2388    #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
2389    struct AnyStringFlagsInner: u16 {
2390        /// The string uses double quotes (`"`).
2391        /// If this flag is not set, the string uses single quotes (`'`).
2392        const DOUBLE = 1 << 0;
2393
2394        /// The string is triple-quoted:
2395        /// it begins and ends with three consecutive quote characters.
2396        const TRIPLE_QUOTED = 1 << 1;
2397
2398        /// The string has a `u` or `U` prefix.
2399        /// While this prefix is a no-op at runtime,
2400        /// strings with this prefix can have no other prefixes set.
2401        const U_PREFIX = 1 << 2;
2402
2403        /// The string has a `b` or `B` prefix.
2404        /// This means that the string is a sequence of `int`s at runtime,
2405        /// rather than a sequence of `str`s.
2406        /// Strings with this flag can also be raw strings,
2407        /// but can have no other prefixes.
2408        const B_PREFIX = 1 << 3;
2409
2410        /// The string has a `f` or `F` prefix, meaning it is an f-string.
2411        /// F-strings can also be raw strings,
2412        /// but can have no other prefixes.
2413        const F_PREFIX = 1 << 4;
2414
2415        /// The string has a `t` or `T` prefix, meaning it is a t-string.
2416        /// T-strings can also be raw strings,
2417        /// but can have no other prefixes.
2418        const T_PREFIX = 1 << 5;
2419
2420        /// The string has an `r` prefix, meaning it is a raw string.
2421        /// F-strings and byte-strings can be raw,
2422        /// as can strings with no other prefixes.
2423        /// U-strings cannot be raw.
2424        const R_PREFIX_LOWER = 1 << 6;
2425
2426        /// The string has an `R` prefix, meaning it is a raw string.
2427        /// The casing of the `r`/`R` has no semantic significance at runtime;
2428        /// see https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#r-strings-and-r-strings
2429        /// for why we track the casing of the `r` prefix,
2430        /// but not for any other prefix
2431        const R_PREFIX_UPPER = 1 << 7;
2432
2433        /// String without matching closing quote(s).
2434        const UNCLOSED = 1 << 8;
2435    }
2436}
2437
2438#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2439pub struct AnyStringFlags(AnyStringFlagsInner);
2440
2441impl AnyStringFlags {
2442    #[must_use]
2443    pub fn with_prefix(mut self, prefix: AnyStringPrefix) -> Self {
2444        self.0 |= match prefix {
2445            // regular strings
2446            AnyStringPrefix::Regular(StringLiteralPrefix::Empty) => AnyStringFlagsInner::empty(),
2447            AnyStringPrefix::Regular(StringLiteralPrefix::Unicode) => AnyStringFlagsInner::U_PREFIX,
2448            AnyStringPrefix::Regular(StringLiteralPrefix::Raw { uppercase: false }) => {
2449                AnyStringFlagsInner::R_PREFIX_LOWER
2450            }
2451            AnyStringPrefix::Regular(StringLiteralPrefix::Raw { uppercase: true }) => {
2452                AnyStringFlagsInner::R_PREFIX_UPPER
2453            }
2454
2455            // bytestrings
2456            AnyStringPrefix::Bytes(ByteStringPrefix::Regular) => AnyStringFlagsInner::B_PREFIX,
2457            AnyStringPrefix::Bytes(ByteStringPrefix::Raw { uppercase_r: false }) => {
2458                AnyStringFlagsInner::B_PREFIX.union(AnyStringFlagsInner::R_PREFIX_LOWER)
2459            }
2460            AnyStringPrefix::Bytes(ByteStringPrefix::Raw { uppercase_r: true }) => {
2461                AnyStringFlagsInner::B_PREFIX.union(AnyStringFlagsInner::R_PREFIX_UPPER)
2462            }
2463
2464            // f-strings
2465            AnyStringPrefix::Format(FStringPrefix::Regular) => AnyStringFlagsInner::F_PREFIX,
2466            AnyStringPrefix::Format(FStringPrefix::Raw { uppercase_r: false }) => {
2467                AnyStringFlagsInner::F_PREFIX.union(AnyStringFlagsInner::R_PREFIX_LOWER)
2468            }
2469            AnyStringPrefix::Format(FStringPrefix::Raw { uppercase_r: true }) => {
2470                AnyStringFlagsInner::F_PREFIX.union(AnyStringFlagsInner::R_PREFIX_UPPER)
2471            }
2472
2473            // t-strings
2474            AnyStringPrefix::Template(TStringPrefix::Regular) => AnyStringFlagsInner::T_PREFIX,
2475            AnyStringPrefix::Template(TStringPrefix::Raw { uppercase_r: false }) => {
2476                AnyStringFlagsInner::T_PREFIX.union(AnyStringFlagsInner::R_PREFIX_LOWER)
2477            }
2478            AnyStringPrefix::Template(TStringPrefix::Raw { uppercase_r: true }) => {
2479                AnyStringFlagsInner::T_PREFIX.union(AnyStringFlagsInner::R_PREFIX_UPPER)
2480            }
2481        };
2482        self
2483    }
2484
2485    pub fn new(prefix: AnyStringPrefix, quotes: Quote, triple_quotes: TripleQuotes) -> Self {
2486        Self(AnyStringFlagsInner::empty())
2487            .with_prefix(prefix)
2488            .with_quote_style(quotes)
2489            .with_triple_quotes(triple_quotes)
2490    }
2491
2492    /// Does the string have a `u` or `U` prefix?
2493    pub const fn is_u_string(self) -> bool {
2494        self.0.contains(AnyStringFlagsInner::U_PREFIX)
2495    }
2496
2497    /// Does the string have an `r` or `R` prefix?
2498    pub const fn is_raw_string(self) -> bool {
2499        self.0.intersects(
2500            AnyStringFlagsInner::R_PREFIX_LOWER.union(AnyStringFlagsInner::R_PREFIX_UPPER),
2501        )
2502    }
2503
2504    /// Does the string have an `f`,`F`,`t`, or `T` prefix?
2505    pub const fn is_interpolated_string(self) -> bool {
2506        self.0
2507            .intersects(AnyStringFlagsInner::F_PREFIX.union(AnyStringFlagsInner::T_PREFIX))
2508    }
2509
2510    /// Does the string have a `b` or `B` prefix?
2511    pub const fn is_byte_string(self) -> bool {
2512        self.0.contains(AnyStringFlagsInner::B_PREFIX)
2513    }
2514
2515    #[must_use]
2516    pub fn with_quote_style(mut self, quotes: Quote) -> Self {
2517        match quotes {
2518            Quote::Double => self.0 |= AnyStringFlagsInner::DOUBLE,
2519            Quote::Single => self.0 -= AnyStringFlagsInner::DOUBLE,
2520        }
2521        self
2522    }
2523
2524    #[must_use]
2525    pub fn with_triple_quotes(mut self, triple_quotes: TripleQuotes) -> Self {
2526        self.0
2527            .set(AnyStringFlagsInner::TRIPLE_QUOTED, triple_quotes.is_yes());
2528        self
2529    }
2530
2531    #[must_use]
2532    pub fn with_unclosed(mut self, unclosed: bool) -> Self {
2533        self.0.set(AnyStringFlagsInner::UNCLOSED, unclosed);
2534        self
2535    }
2536}
2537
2538impl StringFlags for AnyStringFlags {
2539    /// Does the string use single or double quotes in its opener and closer?
2540    fn quote_style(self) -> Quote {
2541        if self.0.contains(AnyStringFlagsInner::DOUBLE) {
2542            Quote::Double
2543        } else {
2544            Quote::Single
2545        }
2546    }
2547
2548    fn triple_quotes(self) -> TripleQuotes {
2549        if self.0.contains(AnyStringFlagsInner::TRIPLE_QUOTED) {
2550            TripleQuotes::Yes
2551        } else {
2552            TripleQuotes::No
2553        }
2554    }
2555
2556    fn prefix(self) -> AnyStringPrefix {
2557        let AnyStringFlags(flags) = self;
2558
2559        // f-strings
2560        if flags.contains(AnyStringFlagsInner::F_PREFIX) {
2561            if flags.contains(AnyStringFlagsInner::R_PREFIX_LOWER) {
2562                return AnyStringPrefix::Format(FStringPrefix::Raw { uppercase_r: false });
2563            }
2564            if flags.contains(AnyStringFlagsInner::R_PREFIX_UPPER) {
2565                return AnyStringPrefix::Format(FStringPrefix::Raw { uppercase_r: true });
2566            }
2567            return AnyStringPrefix::Format(FStringPrefix::Regular);
2568        }
2569
2570        // t-strings
2571        if flags.contains(AnyStringFlagsInner::T_PREFIX) {
2572            if flags.contains(AnyStringFlagsInner::R_PREFIX_LOWER) {
2573                return AnyStringPrefix::Template(TStringPrefix::Raw { uppercase_r: false });
2574            }
2575            if flags.contains(AnyStringFlagsInner::R_PREFIX_UPPER) {
2576                return AnyStringPrefix::Template(TStringPrefix::Raw { uppercase_r: true });
2577            }
2578            return AnyStringPrefix::Template(TStringPrefix::Regular);
2579        }
2580
2581        // bytestrings
2582        if flags.contains(AnyStringFlagsInner::B_PREFIX) {
2583            if flags.contains(AnyStringFlagsInner::R_PREFIX_LOWER) {
2584                return AnyStringPrefix::Bytes(ByteStringPrefix::Raw { uppercase_r: false });
2585            }
2586            if flags.contains(AnyStringFlagsInner::R_PREFIX_UPPER) {
2587                return AnyStringPrefix::Bytes(ByteStringPrefix::Raw { uppercase_r: true });
2588            }
2589            return AnyStringPrefix::Bytes(ByteStringPrefix::Regular);
2590        }
2591
2592        // all other strings
2593        if flags.contains(AnyStringFlagsInner::R_PREFIX_LOWER) {
2594            return AnyStringPrefix::Regular(StringLiteralPrefix::Raw { uppercase: false });
2595        }
2596        if flags.contains(AnyStringFlagsInner::R_PREFIX_UPPER) {
2597            return AnyStringPrefix::Regular(StringLiteralPrefix::Raw { uppercase: true });
2598        }
2599        if flags.contains(AnyStringFlagsInner::U_PREFIX) {
2600            return AnyStringPrefix::Regular(StringLiteralPrefix::Unicode);
2601        }
2602        AnyStringPrefix::Regular(StringLiteralPrefix::Empty)
2603    }
2604
2605    fn is_unclosed(self) -> bool {
2606        self.0.intersects(AnyStringFlagsInner::UNCLOSED)
2607    }
2608}
2609
2610impl fmt::Debug for AnyStringFlags {
2611    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2612        f.debug_struct("AnyStringFlags")
2613            .field("prefix", &self.prefix())
2614            .field("triple_quoted", &self.is_triple_quoted())
2615            .field("quote_style", &self.quote_style())
2616            .field("unclosed", &self.is_unclosed())
2617            .finish()
2618    }
2619}
2620
2621impl From<AnyStringFlags> for StringLiteralFlags {
2622    fn from(value: AnyStringFlags) -> StringLiteralFlags {
2623        let AnyStringPrefix::Regular(prefix) = value.prefix() else {
2624            unreachable!(
2625                "Should never attempt to convert {} into a regular string",
2626                value.prefix()
2627            )
2628        };
2629        StringLiteralFlags::empty()
2630            .with_quote_style(value.quote_style())
2631            .with_prefix(prefix)
2632            .with_triple_quotes(value.triple_quotes())
2633            .with_unclosed(value.is_unclosed())
2634    }
2635}
2636
2637impl From<StringLiteralFlags> for AnyStringFlags {
2638    fn from(value: StringLiteralFlags) -> Self {
2639        value.as_any_string_flags()
2640    }
2641}
2642
2643impl From<AnyStringFlags> for BytesLiteralFlags {
2644    fn from(value: AnyStringFlags) -> BytesLiteralFlags {
2645        let AnyStringPrefix::Bytes(bytestring_prefix) = value.prefix() else {
2646            unreachable!(
2647                "Should never attempt to convert {} into a bytestring",
2648                value.prefix()
2649            )
2650        };
2651        BytesLiteralFlags::empty()
2652            .with_quote_style(value.quote_style())
2653            .with_prefix(bytestring_prefix)
2654            .with_triple_quotes(value.triple_quotes())
2655            .with_unclosed(value.is_unclosed())
2656    }
2657}
2658
2659impl From<BytesLiteralFlags> for AnyStringFlags {
2660    fn from(value: BytesLiteralFlags) -> Self {
2661        value.as_any_string_flags()
2662    }
2663}
2664
2665impl From<AnyStringFlags> for FStringFlags {
2666    fn from(value: AnyStringFlags) -> FStringFlags {
2667        let AnyStringPrefix::Format(prefix) = value.prefix() else {
2668            unreachable!(
2669                "Should never attempt to convert {} into an f-string",
2670                value.prefix()
2671            )
2672        };
2673        FStringFlags::empty()
2674            .with_quote_style(value.quote_style())
2675            .with_prefix(prefix)
2676            .with_triple_quotes(value.triple_quotes())
2677            .with_unclosed(value.is_unclosed())
2678    }
2679}
2680
2681impl From<FStringFlags> for AnyStringFlags {
2682    fn from(value: FStringFlags) -> Self {
2683        value.as_any_string_flags()
2684    }
2685}
2686
2687impl From<AnyStringFlags> for TStringFlags {
2688    fn from(value: AnyStringFlags) -> TStringFlags {
2689        let AnyStringPrefix::Template(prefix) = value.prefix() else {
2690            unreachable!(
2691                "Should never attempt to convert {} into a t-string",
2692                value.prefix()
2693            )
2694        };
2695        TStringFlags::empty()
2696            .with_quote_style(value.quote_style())
2697            .with_prefix(prefix)
2698            .with_triple_quotes(value.triple_quotes())
2699            .with_unclosed(value.is_unclosed())
2700    }
2701}
2702
2703impl From<TStringFlags> for AnyStringFlags {
2704    fn from(value: TStringFlags) -> Self {
2705        value.as_any_string_flags()
2706    }
2707}
2708
2709#[derive(Clone, Debug, PartialEq, is_macro::Is)]
2710#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2711pub enum Number {
2712    Int(int::Int),
2713    Float(f64),
2714    Complex { real: f64, imag: f64 },
2715}
2716
2717impl ExprName {
2718    pub fn id(&self) -> &Name {
2719        &self.id
2720    }
2721
2722    /// Returns `true` if this node represents an invalid name i.e., the `ctx` is [`Invalid`].
2723    ///
2724    /// [`Invalid`]: ExprContext::Invalid
2725    pub const fn is_invalid(&self) -> bool {
2726        matches!(self.ctx, ExprContext::Invalid)
2727    }
2728}
2729
2730impl ExprList {
2731    pub fn iter(&self) -> std::slice::Iter<'_, Expr> {
2732        self.elts.iter()
2733    }
2734
2735    pub fn len(&self) -> usize {
2736        self.elts.len()
2737    }
2738
2739    pub fn is_empty(&self) -> bool {
2740        self.elts.is_empty()
2741    }
2742}
2743
2744impl<'a> IntoIterator for &'a ExprList {
2745    type IntoIter = std::slice::Iter<'a, Expr>;
2746    type Item = &'a Expr;
2747
2748    fn into_iter(self) -> Self::IntoIter {
2749        self.iter()
2750    }
2751}
2752
2753impl ExprTuple {
2754    pub fn iter(&self) -> std::slice::Iter<'_, Expr> {
2755        self.elts.iter()
2756    }
2757
2758    pub fn len(&self) -> usize {
2759        self.elts.len()
2760    }
2761
2762    pub fn is_empty(&self) -> bool {
2763        self.elts.is_empty()
2764    }
2765}
2766
2767impl<'a> IntoIterator for &'a ExprTuple {
2768    type IntoIter = std::slice::Iter<'a, Expr>;
2769    type Item = &'a Expr;
2770
2771    fn into_iter(self) -> Self::IntoIter {
2772        self.iter()
2773    }
2774}
2775
2776/// See also [expr_context](https://docs.python.org/3/library/ast.html#ast.expr_context)
2777#[derive(Clone, Debug, PartialEq, is_macro::Is, Copy, Hash, Eq)]
2778#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2779pub enum ExprContext {
2780    Load,
2781    Store,
2782    Del,
2783    Invalid,
2784}
2785
2786/// See also [boolop](https://docs.python.org/3/library/ast.html#ast.BoolOp)
2787#[derive(Clone, Debug, PartialEq, is_macro::Is, Copy, Hash, Eq)]
2788#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2789pub enum BoolOp {
2790    And,
2791    Or,
2792}
2793
2794impl BoolOp {
2795    pub const fn as_str(&self) -> &'static str {
2796        match self {
2797            BoolOp::And => "and",
2798            BoolOp::Or => "or",
2799        }
2800    }
2801}
2802
2803impl fmt::Display for BoolOp {
2804    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2805        f.write_str(self.as_str())
2806    }
2807}
2808
2809/// See also [operator](https://docs.python.org/3/library/ast.html#ast.operator)
2810#[derive(Clone, Debug, PartialEq, is_macro::Is, Copy, Hash, Eq)]
2811#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2812pub enum Operator {
2813    Add,
2814    Sub,
2815    Mult,
2816    MatMult,
2817    Div,
2818    Mod,
2819    Pow,
2820    LShift,
2821    RShift,
2822    BitOr,
2823    BitXor,
2824    BitAnd,
2825    FloorDiv,
2826}
2827
2828impl Operator {
2829    pub const fn as_str(&self) -> &'static str {
2830        match self {
2831            Operator::Add => "+",
2832            Operator::Sub => "-",
2833            Operator::Mult => "*",
2834            Operator::MatMult => "@",
2835            Operator::Div => "/",
2836            Operator::Mod => "%",
2837            Operator::Pow => "**",
2838            Operator::LShift => "<<",
2839            Operator::RShift => ">>",
2840            Operator::BitOr => "|",
2841            Operator::BitXor => "^",
2842            Operator::BitAnd => "&",
2843            Operator::FloorDiv => "//",
2844        }
2845    }
2846
2847    /// Returns the dunder method name for the operator.
2848    pub const fn dunder(self) -> &'static str {
2849        match self {
2850            Operator::Add => "__add__",
2851            Operator::Sub => "__sub__",
2852            Operator::Mult => "__mul__",
2853            Operator::MatMult => "__matmul__",
2854            Operator::Div => "__truediv__",
2855            Operator::Mod => "__mod__",
2856            Operator::Pow => "__pow__",
2857            Operator::LShift => "__lshift__",
2858            Operator::RShift => "__rshift__",
2859            Operator::BitOr => "__or__",
2860            Operator::BitXor => "__xor__",
2861            Operator::BitAnd => "__and__",
2862            Operator::FloorDiv => "__floordiv__",
2863        }
2864    }
2865
2866    /// Returns the in-place dunder method name for the operator.
2867    pub const fn in_place_dunder(self) -> &'static str {
2868        match self {
2869            Operator::Add => "__iadd__",
2870            Operator::Sub => "__isub__",
2871            Operator::Mult => "__imul__",
2872            Operator::MatMult => "__imatmul__",
2873            Operator::Div => "__itruediv__",
2874            Operator::Mod => "__imod__",
2875            Operator::Pow => "__ipow__",
2876            Operator::LShift => "__ilshift__",
2877            Operator::RShift => "__irshift__",
2878            Operator::BitOr => "__ior__",
2879            Operator::BitXor => "__ixor__",
2880            Operator::BitAnd => "__iand__",
2881            Operator::FloorDiv => "__ifloordiv__",
2882        }
2883    }
2884
2885    /// Returns the reflected dunder method name for the operator.
2886    pub const fn reflected_dunder(self) -> &'static str {
2887        match self {
2888            Operator::Add => "__radd__",
2889            Operator::Sub => "__rsub__",
2890            Operator::Mult => "__rmul__",
2891            Operator::MatMult => "__rmatmul__",
2892            Operator::Div => "__rtruediv__",
2893            Operator::Mod => "__rmod__",
2894            Operator::Pow => "__rpow__",
2895            Operator::LShift => "__rlshift__",
2896            Operator::RShift => "__rrshift__",
2897            Operator::BitOr => "__ror__",
2898            Operator::BitXor => "__rxor__",
2899            Operator::BitAnd => "__rand__",
2900            Operator::FloorDiv => "__rfloordiv__",
2901        }
2902    }
2903}
2904
2905impl fmt::Display for Operator {
2906    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2907        f.write_str(self.as_str())
2908    }
2909}
2910
2911/// See also [unaryop](https://docs.python.org/3/library/ast.html#ast.unaryop)
2912#[derive(Clone, Debug, PartialEq, is_macro::Is, Copy, Hash, Eq)]
2913#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2914pub enum UnaryOp {
2915    Invert,
2916    Not,
2917    UAdd,
2918    USub,
2919}
2920
2921impl UnaryOp {
2922    pub const fn as_str(&self) -> &'static str {
2923        match self {
2924            UnaryOp::Invert => "~",
2925            UnaryOp::Not => "not",
2926            UnaryOp::UAdd => "+",
2927            UnaryOp::USub => "-",
2928        }
2929    }
2930}
2931
2932impl fmt::Display for UnaryOp {
2933    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2934        f.write_str(self.as_str())
2935    }
2936}
2937
2938/// See also [cmpop](https://docs.python.org/3/library/ast.html#ast.cmpop)
2939#[derive(Clone, Debug, PartialEq, is_macro::Is, Copy, Hash, Eq)]
2940#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2941pub enum CmpOp {
2942    Eq,
2943    NotEq,
2944    Lt,
2945    LtE,
2946    Gt,
2947    GtE,
2948    Is,
2949    IsNot,
2950    In,
2951    NotIn,
2952}
2953
2954impl CmpOp {
2955    pub const fn as_str(&self) -> &'static str {
2956        match self {
2957            CmpOp::Eq => "==",
2958            CmpOp::NotEq => "!=",
2959            CmpOp::Lt => "<",
2960            CmpOp::LtE => "<=",
2961            CmpOp::Gt => ">",
2962            CmpOp::GtE => ">=",
2963            CmpOp::Is => "is",
2964            CmpOp::IsNot => "is not",
2965            CmpOp::In => "in",
2966            CmpOp::NotIn => "not in",
2967        }
2968    }
2969
2970    #[must_use]
2971    pub const fn negate(&self) -> Self {
2972        match self {
2973            CmpOp::Eq => CmpOp::NotEq,
2974            CmpOp::NotEq => CmpOp::Eq,
2975            CmpOp::Lt => CmpOp::GtE,
2976            CmpOp::LtE => CmpOp::Gt,
2977            CmpOp::Gt => CmpOp::LtE,
2978            CmpOp::GtE => CmpOp::Lt,
2979            CmpOp::Is => CmpOp::IsNot,
2980            CmpOp::IsNot => CmpOp::Is,
2981            CmpOp::In => CmpOp::NotIn,
2982            CmpOp::NotIn => CmpOp::In,
2983        }
2984    }
2985}
2986
2987impl fmt::Display for CmpOp {
2988    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2989        f.write_str(self.as_str())
2990    }
2991}
2992
2993/// See also [comprehension](https://docs.python.org/3/library/ast.html#ast.comprehension)
2994#[derive(Clone, Debug, PartialEq)]
2995#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2996pub struct Comprehension {
2997    pub range: TextRange,
2998    pub node_index: AtomicNodeIndex,
2999    pub target: Expr,
3000    pub iter: Expr,
3001    pub ifs: Vec<Expr>,
3002    pub is_async: bool,
3003}
3004
3005/// See also [ExceptHandler](https://docs.python.org/3/library/ast.html#ast.ExceptHandler)
3006#[derive(Clone, Debug, PartialEq)]
3007#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3008pub struct ExceptHandlerExceptHandler {
3009    pub range: TextRange,
3010    pub node_index: AtomicNodeIndex,
3011    pub type_: Option<Box<Expr>>,
3012    pub name: Option<Identifier>,
3013    pub body: Suite,
3014}
3015
3016/// See also [arg](https://docs.python.org/3/library/ast.html#ast.arg)
3017#[derive(Clone, Debug, PartialEq)]
3018#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3019pub struct Parameter {
3020    pub range: TextRange,
3021    pub node_index: AtomicNodeIndex,
3022    pub name: Identifier,
3023    pub annotation: Option<Box<Expr>>,
3024}
3025
3026impl Parameter {
3027    pub const fn name(&self) -> &Identifier {
3028        &self.name
3029    }
3030
3031    pub fn annotation(&self) -> Option<&Expr> {
3032        self.annotation.as_deref()
3033    }
3034}
3035
3036/// See also [keyword](https://docs.python.org/3/library/ast.html#ast.keyword)
3037#[derive(Clone, Debug, PartialEq)]
3038#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3039pub struct Keyword {
3040    pub range: TextRange,
3041    pub node_index: AtomicNodeIndex,
3042    pub arg: Option<Identifier>,
3043    pub value: Expr,
3044}
3045
3046/// See also [alias](https://docs.python.org/3/library/ast.html#ast.alias)
3047#[derive(Clone, Debug, PartialEq)]
3048#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3049pub struct Alias {
3050    pub range: TextRange,
3051    pub node_index: AtomicNodeIndex,
3052    pub name: Identifier,
3053    pub asname: Option<Identifier>,
3054}
3055
3056/// See also [withitem](https://docs.python.org/3/library/ast.html#ast.withitem)
3057#[derive(Clone, Debug, PartialEq)]
3058#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3059pub struct WithItem {
3060    pub range: TextRange,
3061    pub node_index: AtomicNodeIndex,
3062    pub context_expr: Expr,
3063    pub optional_vars: Option<Box<Expr>>,
3064}
3065
3066/// See also [match_case](https://docs.python.org/3/library/ast.html#ast.match_case)
3067#[derive(Clone, Debug, PartialEq)]
3068#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3069pub struct MatchCase {
3070    pub range: TextRange,
3071    pub node_index: AtomicNodeIndex,
3072    pub pattern: Pattern,
3073    pub guard: Option<Box<Expr>>,
3074    pub body: Suite,
3075}
3076
3077impl Pattern {
3078    /// Checks if the [`Pattern`] is an [irrefutable pattern].
3079    ///
3080    /// [irrefutable pattern]: https://peps.python.org/pep-0634/#irrefutable-case-blocks
3081    pub fn is_irrefutable(&self) -> bool {
3082        self.irrefutable_pattern().is_some()
3083    }
3084
3085    /// Return `Some(IrrefutablePattern)` if `self` is irrefutable or `None` otherwise.
3086    pub fn irrefutable_pattern(&self) -> Option<IrrefutablePattern> {
3087        match self {
3088            Pattern::MatchAs(PatternMatchAs {
3089                pattern,
3090                name,
3091                range,
3092                node_index,
3093            }) => match pattern {
3094                Some(pattern) => pattern.irrefutable_pattern(),
3095                None => match name {
3096                    Some(name) => Some(IrrefutablePattern {
3097                        kind: IrrefutablePatternKind::Name(name.id.clone()),
3098                        range: *range,
3099                        node_index: node_index.clone(),
3100                    }),
3101                    None => Some(IrrefutablePattern {
3102                        kind: IrrefutablePatternKind::Wildcard,
3103                        range: *range,
3104                        node_index: node_index.clone(),
3105                    }),
3106                },
3107            },
3108            Pattern::MatchOr(PatternMatchOr { patterns, .. }) => {
3109                patterns.iter().find_map(Pattern::irrefutable_pattern)
3110            }
3111            _ => None,
3112        }
3113    }
3114
3115    /// Checks if the [`Pattern`] is a [wildcard pattern].
3116    ///
3117    /// The following are wildcard patterns:
3118    /// ```python
3119    /// match subject:
3120    ///     case _ as x: ...
3121    ///     case _ | _: ...
3122    ///     case _: ...
3123    /// ```
3124    ///
3125    /// [wildcard pattern]: https://docs.python.org/3/reference/compound_stmts.html#wildcard-patterns
3126    pub fn is_wildcard(&self) -> bool {
3127        match self {
3128            Pattern::MatchAs(PatternMatchAs { pattern, .. }) => {
3129                pattern.as_deref().is_none_or(Pattern::is_wildcard)
3130            }
3131            Pattern::MatchOr(PatternMatchOr { patterns, .. }) => {
3132                patterns.iter().all(Pattern::is_wildcard)
3133            }
3134            _ => false,
3135        }
3136    }
3137}
3138
3139pub struct IrrefutablePattern {
3140    pub kind: IrrefutablePatternKind,
3141    pub range: TextRange,
3142    pub node_index: AtomicNodeIndex,
3143}
3144
3145#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3146#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3147pub enum IrrefutablePatternKind {
3148    Name(Name),
3149    Wildcard,
3150}
3151
3152/// An AST node to represent the arguments to a [`crate::PatternMatchClass`], i.e., the
3153/// parenthesized contents in `case Point(1, x=0, y=0)`.
3154///
3155/// Like [`Arguments`], but for [`crate::PatternMatchClass`].
3156#[derive(Clone, Debug, PartialEq)]
3157#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3158pub struct PatternArguments {
3159    pub range: TextRange,
3160    pub node_index: AtomicNodeIndex,
3161    pub patterns: ThinVec<Pattern>,
3162    pub keywords: Vec<PatternKeyword>,
3163}
3164
3165/// An AST node to represent the keyword arguments to a [`crate::PatternMatchClass`], i.e., the
3166/// `x=0` and `y=0` in `case Point(x=0, y=0)`.
3167///
3168/// Like [`Keyword`], but for [`crate::PatternMatchClass`].
3169#[derive(Clone, Debug, PartialEq)]
3170#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3171pub struct PatternKeyword {
3172    pub range: TextRange,
3173    pub node_index: AtomicNodeIndex,
3174    pub attr: Identifier,
3175    pub pattern: Pattern,
3176}
3177
3178impl PatternArguments {
3179    /// Returns an iterator over the patterns and keywords in source order.
3180    pub fn iter_source_order(&self) -> PatternArgumentsSourceOrder<'_> {
3181        PatternArgumentsSourceOrder {
3182            patterns: &self.patterns,
3183            keywords: &self.keywords,
3184            next_pattern: 0,
3185            next_keyword: 0,
3186        }
3187    }
3188}
3189
3190/// The iterator returned by [`PatternArguments::iter_source_order`].
3191#[derive(Clone)]
3192pub struct PatternArgumentsSourceOrder<'a> {
3193    patterns: &'a [Pattern],
3194    keywords: &'a [PatternKeyword],
3195    next_pattern: usize,
3196    next_keyword: usize,
3197}
3198
3199/// An entry in the argument list of a class pattern.
3200#[derive(Copy, Clone, Debug, PartialEq)]
3201pub enum PatternOrKeyword<'a> {
3202    Pattern(&'a Pattern),
3203    Keyword(&'a PatternKeyword),
3204}
3205
3206impl<'a> Iterator for PatternArgumentsSourceOrder<'a> {
3207    type Item = PatternOrKeyword<'a>;
3208
3209    fn next(&mut self) -> Option<Self::Item> {
3210        let pattern = self.patterns.get(self.next_pattern);
3211        let keyword = self.keywords.get(self.next_keyword);
3212
3213        if let Some(pattern) = pattern
3214            && keyword.is_none_or(|keyword| pattern.start() <= keyword.start())
3215        {
3216            self.next_pattern += 1;
3217            Some(PatternOrKeyword::Pattern(pattern))
3218        } else if let Some(keyword) = keyword {
3219            self.next_keyword += 1;
3220            Some(PatternOrKeyword::Keyword(keyword))
3221        } else {
3222            None
3223        }
3224    }
3225}
3226
3227impl FusedIterator for PatternArgumentsSourceOrder<'_> {}
3228
3229impl TypeParam {
3230    pub const fn name(&self) -> &Identifier {
3231        match self {
3232            Self::TypeVar(x) => &x.name,
3233            Self::ParamSpec(x) => &x.name,
3234            Self::TypeVarTuple(x) => &x.name,
3235        }
3236    }
3237
3238    pub fn default(&self) -> Option<&Expr> {
3239        match self {
3240            Self::TypeVar(x) => x.default.as_deref(),
3241            Self::ParamSpec(x) => x.default.as_deref(),
3242            Self::TypeVarTuple(x) => x.default.as_deref(),
3243        }
3244    }
3245}
3246
3247/// See also [decorator](https://docs.python.org/3/library/ast.html#ast.decorator)
3248#[derive(Clone, Debug, PartialEq)]
3249#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3250pub struct Decorator {
3251    pub range: TextRange,
3252    pub node_index: AtomicNodeIndex,
3253    pub expression: Expr,
3254}
3255
3256/// Enumeration of the two kinds of parameter
3257#[derive(Debug, PartialEq, Clone, Copy)]
3258pub enum AnyParameterRef<'a> {
3259    /// Variadic parameters cannot have default values,
3260    /// e.g. both `*args` and `**kwargs` in the following function:
3261    ///
3262    /// ```python
3263    /// def foo(*args, **kwargs): pass
3264    /// ```
3265    Variadic(&'a Parameter),
3266
3267    /// Non-variadic parameters can have default values,
3268    /// though they won't necessarily always have them:
3269    ///
3270    /// ```python
3271    /// def bar(a=1, /, b=2, *, c=3): pass
3272    /// ```
3273    NonVariadic(&'a ParameterWithDefault),
3274}
3275
3276impl<'a> AnyParameterRef<'a> {
3277    pub const fn as_parameter(self) -> &'a Parameter {
3278        match self {
3279            Self::NonVariadic(param) => &param.parameter,
3280            Self::Variadic(param) => param,
3281        }
3282    }
3283
3284    pub const fn name(self) -> &'a Identifier {
3285        &self.as_parameter().name
3286    }
3287
3288    pub const fn is_variadic(self) -> bool {
3289        matches!(self, Self::Variadic(_))
3290    }
3291
3292    pub fn annotation(self) -> Option<&'a Expr> {
3293        self.as_parameter().annotation.as_deref()
3294    }
3295
3296    pub fn default(self) -> Option<&'a Expr> {
3297        match self {
3298            Self::NonVariadic(param) => param.default.as_deref(),
3299            Self::Variadic(_) => None,
3300        }
3301    }
3302}
3303
3304impl Ranged for AnyParameterRef<'_> {
3305    fn range(&self) -> TextRange {
3306        match self {
3307            Self::NonVariadic(param) => param.range,
3308            Self::Variadic(param) => param.range,
3309        }
3310    }
3311}
3312
3313/// An alternative type of AST `arguments`. This is ruff_python_parser-friendly and human-friendly definition of function arguments.
3314/// This form also has advantage to implement pre-order traverse.
3315///
3316/// `defaults` and `kw_defaults` fields are removed and the default values are placed under each [`ParameterWithDefault`] typed argument.
3317/// `vararg` and `kwarg` are still typed as `arg` because they never can have a default value.
3318///
3319/// The original Python-style AST type orders `kwonlyargs` fields by default existence; [Parameters] has location-ordered `kwonlyargs` fields.
3320///
3321/// NOTE: This type differs from the original Python AST. See: [arguments](https://docs.python.org/3/library/ast.html#ast.arguments).
3322
3323#[derive(Clone, Debug, PartialEq, Default)]
3324#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3325pub struct Parameters {
3326    pub range: TextRange,
3327    pub node_index: AtomicNodeIndex,
3328    pub posonlyargs: ThinVec<ParameterWithDefault>,
3329    pub args: ThinVec<ParameterWithDefault>,
3330    pub vararg: Option<Box<Parameter>>,
3331    pub kwonlyargs: ThinVec<ParameterWithDefault>,
3332    pub kwarg: Option<Box<Parameter>>,
3333}
3334
3335impl Parameters {
3336    /// Returns an iterator over all non-variadic parameters included in this [`Parameters`] node.
3337    ///
3338    /// The variadic parameters (`.vararg` and `.kwarg`) can never have default values;
3339    /// non-variadic parameters sometimes will.
3340    pub fn iter_non_variadic_params(&self) -> impl Iterator<Item = &ParameterWithDefault> {
3341        self.posonlyargs
3342            .iter()
3343            .chain(&self.args)
3344            .chain(&self.kwonlyargs)
3345    }
3346
3347    /// Returns the [`ParameterWithDefault`] with the given name, or `None` if no such [`ParameterWithDefault`] exists.
3348    pub fn find(&self, name: &str) -> Option<&ParameterWithDefault> {
3349        self.iter_non_variadic_params()
3350            .find(|arg| arg.parameter.name.as_str() == name)
3351    }
3352
3353    /// Returns the index of the parameter with the given name
3354    pub fn index(&self, name: &str) -> Option<usize> {
3355        self.iter_non_variadic_params()
3356            .position(|arg| arg.parameter.name.as_str() == name)
3357    }
3358
3359    /// Returns an iterator over all parameters included in this [`Parameters`] node.
3360    pub fn iter(&self) -> ParametersIterator<'_> {
3361        ParametersIterator::new(self)
3362    }
3363
3364    /// Returns the total number of parameters included in this [`Parameters`] node.
3365    pub fn len(&self) -> usize {
3366        let Parameters {
3367            range: _,
3368            node_index: _,
3369            posonlyargs,
3370            args,
3371            vararg,
3372            kwonlyargs,
3373            kwarg,
3374        } = self;
3375        // Safety: a Python function can have an arbitrary number of parameters,
3376        // so theoretically this could be a number that wouldn't fit into a usize,
3377        // which would lead to a panic. A Python function with that many parameters
3378        // is extremely unlikely outside of generated code, however, and it's even
3379        // more unlikely that we'd find a function with that many parameters in a
3380        // source-code file <=4GB large (Ruff's maximum).
3381        posonlyargs
3382            .len()
3383            .checked_add(args.len())
3384            .and_then(|length| length.checked_add(usize::from(vararg.is_some())))
3385            .and_then(|length| length.checked_add(kwonlyargs.len()))
3386            .and_then(|length| length.checked_add(usize::from(kwarg.is_some())))
3387            .expect("Failed to fit the number of parameters into a usize")
3388    }
3389
3390    /// Returns `true` if a parameter with the given name is included in this [`Parameters`].
3391    pub fn includes(&self, name: &str) -> bool {
3392        self.iter().any(|param| param.name() == name)
3393    }
3394
3395    /// Returns `true` if the [`Parameters`] is empty.
3396    pub fn is_empty(&self) -> bool {
3397        self.posonlyargs.is_empty()
3398            && self.args.is_empty()
3399            && self.kwonlyargs.is_empty()
3400            && self.vararg.is_none()
3401            && self.kwarg.is_none()
3402    }
3403
3404    /// Returns an iterator over all parameters in source order.
3405    ///
3406    /// This differs from [`Parameters::iter`] which returns parameters
3407    /// in type-based order (positional-only, regular, variadic, keyword-only,
3408    /// keyword). For well-formed Python the two orderings are identical, but
3409    /// error recovery can produce ASTs where variadic parameters appear before
3410    /// non-variadic ones (e.g. `def foo(**kwargs, a):`).
3411    pub fn iter_source_order(&self) -> ParametersSourceOrderIterator<'_> {
3412        let mut variadics = [self.vararg.as_deref(), self.kwarg.as_deref()];
3413        variadics.sort_by_key(|param| param.map_or(TextSize::new(u32::MAX), Ranged::start));
3414
3415        ParametersSourceOrderIterator {
3416            next_non_variadic_peeked: None,
3417            posonlyargs: self.posonlyargs.iter(),
3418            args: self.args.iter(),
3419            kwonlyargs: self.kwonlyargs.iter(),
3420            variadics,
3421            next_variadic: 0,
3422        }
3423    }
3424}
3425
3426pub struct ParametersIterator<'a> {
3427    posonlyargs: Iter<'a, ParameterWithDefault>,
3428    args: Iter<'a, ParameterWithDefault>,
3429    vararg: Option<&'a Parameter>,
3430    kwonlyargs: Iter<'a, ParameterWithDefault>,
3431    kwarg: Option<&'a Parameter>,
3432}
3433
3434impl<'a> ParametersIterator<'a> {
3435    fn new(parameters: &'a Parameters) -> Self {
3436        let Parameters {
3437            range: _,
3438            node_index: _,
3439            posonlyargs,
3440            args,
3441            vararg,
3442            kwonlyargs,
3443            kwarg,
3444        } = parameters;
3445        Self {
3446            posonlyargs: posonlyargs.iter(),
3447            args: args.iter(),
3448            vararg: vararg.as_deref(),
3449            kwonlyargs: kwonlyargs.iter(),
3450            kwarg: kwarg.as_deref(),
3451        }
3452    }
3453}
3454
3455impl<'a> Iterator for ParametersIterator<'a> {
3456    type Item = AnyParameterRef<'a>;
3457
3458    fn next(&mut self) -> Option<Self::Item> {
3459        let ParametersIterator {
3460            posonlyargs,
3461            args,
3462            vararg,
3463            kwonlyargs,
3464            kwarg,
3465        } = self;
3466
3467        if let Some(param) = posonlyargs.next() {
3468            return Some(AnyParameterRef::NonVariadic(param));
3469        }
3470        if let Some(param) = args.next() {
3471            return Some(AnyParameterRef::NonVariadic(param));
3472        }
3473        if let Some(param) = vararg.take() {
3474            return Some(AnyParameterRef::Variadic(param));
3475        }
3476        if let Some(param) = kwonlyargs.next() {
3477            return Some(AnyParameterRef::NonVariadic(param));
3478        }
3479        kwarg.take().map(AnyParameterRef::Variadic)
3480    }
3481
3482    fn size_hint(&self) -> (usize, Option<usize>) {
3483        let ParametersIterator {
3484            posonlyargs,
3485            args,
3486            vararg,
3487            kwonlyargs,
3488            kwarg,
3489        } = self;
3490
3491        let posonlyargs_len = posonlyargs.len();
3492        let args_len = args.len();
3493        let vararg_len = usize::from(vararg.is_some());
3494        let kwonlyargs_len = kwonlyargs.len();
3495        let kwarg_len = usize::from(kwarg.is_some());
3496
3497        let lower = posonlyargs_len
3498            .saturating_add(args_len)
3499            .saturating_add(vararg_len)
3500            .saturating_add(kwonlyargs_len)
3501            .saturating_add(kwarg_len);
3502
3503        let upper = posonlyargs_len
3504            .checked_add(args_len)
3505            .and_then(|length| length.checked_add(vararg_len))
3506            .and_then(|length| length.checked_add(kwonlyargs_len))
3507            .and_then(|length| length.checked_add(kwarg_len));
3508
3509        (lower, upper)
3510    }
3511
3512    fn last(mut self) -> Option<Self::Item> {
3513        self.next_back()
3514    }
3515}
3516
3517impl DoubleEndedIterator for ParametersIterator<'_> {
3518    fn next_back(&mut self) -> Option<Self::Item> {
3519        let ParametersIterator {
3520            posonlyargs,
3521            args,
3522            vararg,
3523            kwonlyargs,
3524            kwarg,
3525        } = self;
3526
3527        if let Some(param) = kwarg.take() {
3528            return Some(AnyParameterRef::Variadic(param));
3529        }
3530        if let Some(param) = kwonlyargs.next_back() {
3531            return Some(AnyParameterRef::NonVariadic(param));
3532        }
3533        if let Some(param) = vararg.take() {
3534            return Some(AnyParameterRef::Variadic(param));
3535        }
3536        if let Some(param) = args.next_back() {
3537            return Some(AnyParameterRef::NonVariadic(param));
3538        }
3539        posonlyargs.next_back().map(AnyParameterRef::NonVariadic)
3540    }
3541}
3542
3543impl FusedIterator for ParametersIterator<'_> {}
3544
3545/// We rely on the same invariants outlined in the comment above `Parameters::len()`
3546/// in order to implement `ExactSizeIterator` here
3547impl ExactSizeIterator for ParametersIterator<'_> {}
3548
3549impl<'a> IntoIterator for &'a Parameters {
3550    type IntoIter = ParametersIterator<'a>;
3551    type Item = AnyParameterRef<'a>;
3552    fn into_iter(self) -> Self::IntoIter {
3553        self.iter()
3554    }
3555}
3556
3557impl<'a> IntoIterator for &'a Box<Parameters> {
3558    type IntoIter = ParametersIterator<'a>;
3559    type Item = AnyParameterRef<'a>;
3560    fn into_iter(self) -> Self::IntoIter {
3561        (&**self).into_iter()
3562    }
3563}
3564
3565/// The iterator returned by [`Parameters::iter_source_order`].
3566pub struct ParametersSourceOrderIterator<'a> {
3567    next_non_variadic_peeked: Option<&'a ParameterWithDefault>,
3568    posonlyargs: Iter<'a, ParameterWithDefault>,
3569    args: Iter<'a, ParameterWithDefault>,
3570    kwonlyargs: Iter<'a, ParameterWithDefault>,
3571    variadics: [Option<&'a Parameter>; 2],
3572    next_variadic: usize,
3573}
3574
3575impl<'a> ParametersSourceOrderIterator<'a> {
3576    /// Returns the next variadic parameter that appears before `before`, if any.
3577    fn next_variadic_before(&mut self, before: TextSize) -> Option<&'a Parameter> {
3578        let param = self.variadics.get(self.next_variadic).copied().flatten()?;
3579        if param.start() < before {
3580            self.next_variadic += 1;
3581            Some(param)
3582        } else {
3583            None
3584        }
3585    }
3586
3587    fn next_non_variadic(&mut self) -> Option<&'a ParameterWithDefault> {
3588        self.next_non_variadic_peeked
3589            .take()
3590            .or_else(|| self.posonlyargs.next())
3591            .or_else(|| self.args.next())
3592            .or_else(|| self.kwonlyargs.next())
3593    }
3594
3595    fn peek_next_non_variadic(&mut self) -> Option<&'a ParameterWithDefault> {
3596        let next = self.next_non_variadic()?;
3597        self.next_non_variadic_peeked = Some(next);
3598        Some(next)
3599    }
3600}
3601
3602impl<'a> Iterator for ParametersSourceOrderIterator<'a> {
3603    type Item = AnyParameterRef<'a>;
3604
3605    fn next(&mut self) -> Option<Self::Item> {
3606        // If there's a variadic parameter that comes before the next
3607        // non-variadic parameter, emit it first.
3608        let next_non_variadic_start = self
3609            .peek_next_non_variadic()
3610            .map_or(TextSize::new(u32::MAX), Ranged::start);
3611
3612        if let Some(variadic) = self.next_variadic_before(next_non_variadic_start) {
3613            return Some(AnyParameterRef::Variadic(variadic));
3614        }
3615
3616        if let Some(non_variadic) = self.next_non_variadic() {
3617            return Some(AnyParameterRef::NonVariadic(non_variadic));
3618        }
3619
3620        // Drain remaining variadics.
3621        self.next_variadic_before(TextSize::new(u32::MAX))
3622            .map(AnyParameterRef::Variadic)
3623    }
3624}
3625
3626impl FusedIterator for ParametersSourceOrderIterator<'_> {}
3627
3628/// An alternative type of AST `arg`. This is used for each function argument that might have a default value.
3629/// Used by `Arguments` original type.
3630///
3631/// NOTE: This type is different from original Python AST.
3632#[derive(Clone, Debug, PartialEq)]
3633#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3634pub struct ParameterWithDefault {
3635    pub range: TextRange,
3636    pub node_index: AtomicNodeIndex,
3637    pub parameter: Parameter,
3638    pub default: Option<Box<Expr>>,
3639}
3640
3641impl ParameterWithDefault {
3642    pub fn default(&self) -> Option<&Expr> {
3643        self.default.as_deref()
3644    }
3645
3646    pub const fn name(&self) -> &Identifier {
3647        self.parameter.name()
3648    }
3649
3650    pub fn annotation(&self) -> Option<&Expr> {
3651        self.parameter.annotation()
3652    }
3653
3654    /// Return `true` if the parameter name uses the pre-PEP-570 convention
3655    /// (specified in PEP 484) to indicate to a type checker that it should be treated
3656    /// as positional-only.
3657    pub fn uses_pep_484_positional_only_convention(&self) -> bool {
3658        let name = self.name();
3659        name.starts_with("__") && !name.ends_with("__")
3660    }
3661}
3662
3663/// An AST node used to represent the arguments passed to a function call or class definition.
3664///
3665/// For example, given:
3666/// ```python
3667/// foo(1, 2, 3, bar=4, baz=5)
3668/// ```
3669/// The `Arguments` node would span from the left to right parentheses (inclusive), and contain
3670/// the arguments and keyword arguments in the order they appear in the source code.
3671///
3672/// Similarly, given:
3673/// ```python
3674/// class Foo(Bar, baz=1, qux=2):
3675///     pass
3676/// ```
3677/// The `Arguments` node would again span from the left to right parentheses (inclusive), and
3678/// contain the `Bar` argument and the `baz` and `qux` keyword arguments in the order they
3679/// appear in the source code.
3680///
3681/// In the context of a class definition, the Python-style AST refers to the arguments as `bases`,
3682/// as they represent the "explicitly specified base classes", while the keyword arguments are
3683/// typically used for `metaclass`, with any additional arguments being passed to the `metaclass`.
3684
3685#[derive(Clone, Debug, PartialEq)]
3686#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3687pub struct Arguments {
3688    pub range: TextRange,
3689    pub node_index: AtomicNodeIndex,
3690    pub args: ThinVec<Expr>,
3691    pub keywords: ThinVec<Keyword>,
3692}
3693
3694/// An entry in the argument list of a function call.
3695#[derive(Copy, Clone, Debug, PartialEq)]
3696pub enum ArgOrKeyword<'a> {
3697    Arg(&'a Expr),
3698    Keyword(&'a Keyword),
3699}
3700
3701impl<'a> ArgOrKeyword<'a> {
3702    pub const fn value(self) -> &'a Expr {
3703        match self {
3704            ArgOrKeyword::Arg(argument) => argument,
3705            ArgOrKeyword::Keyword(keyword) => &keyword.value,
3706        }
3707    }
3708
3709    pub const fn is_variadic(self) -> bool {
3710        match self {
3711            ArgOrKeyword::Arg(expr) => expr.is_starred_expr(),
3712            ArgOrKeyword::Keyword(keyword) => keyword.arg.is_none(),
3713        }
3714    }
3715
3716    pub const fn as_variadic(self) -> Option<&'a Keyword> {
3717        match self {
3718            ArgOrKeyword::Keyword(keyword) if keyword.arg.is_none() => Some(keyword),
3719            _ => None,
3720        }
3721    }
3722
3723    pub const fn as_keyword(self) -> Option<&'a Keyword> {
3724        match self {
3725            ArgOrKeyword::Keyword(keyword) => Some(keyword),
3726            ArgOrKeyword::Arg(_) => None,
3727        }
3728    }
3729}
3730
3731impl<'a> From<&'a Expr> for ArgOrKeyword<'a> {
3732    fn from(arg: &'a Expr) -> Self {
3733        Self::Arg(arg)
3734    }
3735}
3736
3737impl<'a> From<&'a Keyword> for ArgOrKeyword<'a> {
3738    fn from(keyword: &'a Keyword) -> Self {
3739        Self::Keyword(keyword)
3740    }
3741}
3742
3743impl Ranged for ArgOrKeyword<'_> {
3744    fn range(&self) -> TextRange {
3745        match self {
3746            Self::Arg(arg) => arg.range(),
3747            Self::Keyword(keyword) => keyword.range(),
3748        }
3749    }
3750}
3751
3752impl Arguments {
3753    /// Return the number of positional and keyword arguments.
3754    pub fn len(&self) -> usize {
3755        self.args.len() + self.keywords.len()
3756    }
3757
3758    /// Return `true` if there are no positional or keyword arguments.
3759    pub fn is_empty(&self) -> bool {
3760        self.len() == 0
3761    }
3762
3763    /// Return the [`Keyword`] with the given name, or `None` if no such [`Keyword`] exists.
3764    pub fn find_keyword(&self, keyword_name: &str) -> Option<&Keyword> {
3765        self.keywords.iter().find(|keyword| {
3766            let Keyword { arg, .. } = keyword;
3767            arg.as_ref().is_some_and(|arg| arg == keyword_name)
3768        })
3769    }
3770
3771    /// Return the positional argument at the given index, or `None` if no such argument exists.
3772    pub fn find_positional(&self, position: usize) -> Option<&Expr> {
3773        self.args
3774            .iter()
3775            .take_while(|expr| !expr.is_starred_expr())
3776            .nth(position)
3777    }
3778
3779    /// Return the value for the argument with the given name or at the given position, or `None` if no such
3780    /// argument exists. Used to retrieve argument values that can be provided _either_ as keyword or
3781    /// positional arguments.
3782    pub fn find_argument_value(&self, name: &str, position: usize) -> Option<&Expr> {
3783        self.find_argument(name, position).map(ArgOrKeyword::value)
3784    }
3785
3786    /// Return the argument with the given name or at the given position, or `None` if no such
3787    /// argument exists. Used to retrieve arguments that can be provided _either_ as keyword or
3788    /// positional arguments.
3789    pub fn find_argument(&self, name: &str, position: usize) -> Option<ArgOrKeyword<'_>> {
3790        self.find_keyword(name)
3791            .map(ArgOrKeyword::from)
3792            .or_else(|| self.find_positional(position).map(ArgOrKeyword::from))
3793    }
3794
3795    /// Iterates over the positional and keyword arguments in the order of declaration.
3796    ///
3797    /// Positional arguments are generally before keyword arguments, but star arguments are an
3798    /// exception:
3799    /// ```python
3800    /// class A(*args, a=2, *args2, **kwargs):
3801    ///     pass
3802    ///
3803    /// f(*args, a=2, *args2, **kwargs)
3804    /// ```
3805    /// where `*args` and `args2` are `args` while `a=1` and `kwargs` are `keywords`.
3806    ///
3807    /// If you would just chain `args` and `keywords` the call would get reordered which we don't
3808    /// want. This function instead "merge sorts" them into the correct order.
3809    ///
3810    /// Note that the order of evaluation is always first `args`, then `keywords`:
3811    /// ```python
3812    /// def f(*args, **kwargs):
3813    ///     pass
3814    ///
3815    /// def g(x):
3816    ///     print(x)
3817    ///     return x
3818    ///
3819    ///
3820    /// f(*g([1]), a=g(2), *g([3]), **g({"4": 5}))
3821    /// ```
3822    /// Output:
3823    /// ```text
3824    /// [1]
3825    /// [3]
3826    /// 2
3827    /// {'4': 5}
3828    /// ```
3829    pub fn iter_source_order(&self) -> ArgumentsSourceOrder<'_> {
3830        ArgumentsSourceOrder {
3831            args: &self.args,
3832            keywords: &self.keywords,
3833            next_arg: 0,
3834            next_keyword: 0,
3835        }
3836    }
3837
3838    pub fn inner_range(&self) -> TextRange {
3839        TextRange::new(self.l_paren_range().end(), self.r_paren_range().start())
3840    }
3841
3842    pub fn l_paren_range(&self) -> TextRange {
3843        TextRange::at(self.start(), '('.text_len())
3844    }
3845
3846    pub fn r_paren_range(&self) -> TextRange {
3847        TextRange::new(self.end() - ')'.text_len(), self.end())
3848    }
3849}
3850
3851/// The iterator returned by [`Arguments::iter_source_order`].
3852#[derive(Clone)]
3853pub struct ArgumentsSourceOrder<'a> {
3854    args: &'a [Expr],
3855    keywords: &'a [Keyword],
3856    next_arg: usize,
3857    next_keyword: usize,
3858}
3859
3860impl<'a> Iterator for ArgumentsSourceOrder<'a> {
3861    type Item = ArgOrKeyword<'a>;
3862
3863    fn next(&mut self) -> Option<Self::Item> {
3864        let arg = self.args.get(self.next_arg);
3865        let keyword = self.keywords.get(self.next_keyword);
3866
3867        if let Some(arg) = arg
3868            && keyword.is_none_or(|keyword| arg.start() <= keyword.start())
3869        {
3870            self.next_arg += 1;
3871            Some(ArgOrKeyword::Arg(arg))
3872        } else if let Some(keyword) = keyword {
3873            self.next_keyword += 1;
3874            Some(ArgOrKeyword::Keyword(keyword))
3875        } else {
3876            None
3877        }
3878    }
3879}
3880
3881impl FusedIterator for ArgumentsSourceOrder<'_> {}
3882
3883/// An AST node used to represent a sequence of type parameters.
3884///
3885/// For example, given:
3886/// ```python
3887/// class C[T, U, V]: ...
3888/// ```
3889/// The `TypeParams` node would span from the left to right brackets (inclusive), and contain
3890/// the `T`, `U`, and `V` type parameters in the order they appear in the source code.
3891
3892#[derive(Clone, Debug, PartialEq)]
3893#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3894pub struct TypeParams {
3895    pub range: TextRange,
3896    pub node_index: AtomicNodeIndex,
3897    pub type_params: Vec<TypeParam>,
3898}
3899
3900impl Deref for TypeParams {
3901    type Target = [TypeParam];
3902
3903    fn deref(&self) -> &Self::Target {
3904        &self.type_params
3905    }
3906}
3907
3908impl<'a> IntoIterator for &'a TypeParams {
3909    type Item = &'a TypeParam;
3910    type IntoIter = std::slice::Iter<'a, TypeParam>;
3911
3912    fn into_iter(self) -> Self::IntoIter {
3913        self.type_params.iter()
3914    }
3915}
3916
3917/// A suite represents a sequence of [`Stmt`].
3918///
3919/// See: <https://docs.python.org/3/reference/compound_stmts.html#grammar-token-python-grammar-suite>
3920pub type Suite = ThinVec<Stmt>;
3921
3922pub type DecoratorList = ThinVec<Decorator>;
3923
3924pub type Patterns = ThinVec<Pattern>;
3925
3926pub type PatternKeys = ThinVec<Expr>;
3927
3928pub type ParameterWithDefaults = ThinVec<ParameterWithDefault>;
3929
3930/// The kind of escape command as defined in [IPython Syntax] in the IPython codebase.
3931///
3932/// [IPython Syntax]: https://github.com/ipython/ipython/blob/635815e8f1ded5b764d66cacc80bbe25e9e2587f/IPython/core/inputtransformer2.py#L335-L343
3933#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
3934#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3935pub enum IpyEscapeKind {
3936    /// Send line to underlying system shell (`!`).
3937    Shell,
3938    /// Send line to system shell and capture output (`!!`).
3939    ShCap,
3940    /// Show help on object (`?`).
3941    Help,
3942    /// Show help on object, with extra verbosity (`??`).
3943    Help2,
3944    /// Call magic function (`%`).
3945    Magic,
3946    /// Call cell magic function (`%%`).
3947    Magic2,
3948    /// Call first argument with rest of line as arguments after splitting on whitespace
3949    /// and quote each as string (`,`).
3950    Quote,
3951    /// Call first argument with rest of line as an argument quoted as a single string (`;`).
3952    Quote2,
3953    /// Call first argument with rest of line as arguments (`/`).
3954    Paren,
3955}
3956
3957impl TryFrom<char> for IpyEscapeKind {
3958    type Error = String;
3959
3960    fn try_from(ch: char) -> Result<Self, Self::Error> {
3961        match ch {
3962            '!' => Ok(IpyEscapeKind::Shell),
3963            '?' => Ok(IpyEscapeKind::Help),
3964            '%' => Ok(IpyEscapeKind::Magic),
3965            ',' => Ok(IpyEscapeKind::Quote),
3966            ';' => Ok(IpyEscapeKind::Quote2),
3967            '/' => Ok(IpyEscapeKind::Paren),
3968            _ => Err(format!("Unexpected magic escape: {ch}")),
3969        }
3970    }
3971}
3972
3973impl TryFrom<[char; 2]> for IpyEscapeKind {
3974    type Error = String;
3975
3976    fn try_from(ch: [char; 2]) -> Result<Self, Self::Error> {
3977        match ch {
3978            ['!', '!'] => Ok(IpyEscapeKind::ShCap),
3979            ['?', '?'] => Ok(IpyEscapeKind::Help2),
3980            ['%', '%'] => Ok(IpyEscapeKind::Magic2),
3981            [c1, c2] => Err(format!("Unexpected magic escape: {c1}{c2}")),
3982        }
3983    }
3984}
3985
3986impl fmt::Display for IpyEscapeKind {
3987    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3988        f.write_str(self.as_str())
3989    }
3990}
3991
3992impl IpyEscapeKind {
3993    /// Returns `true` if the escape kind is help i.e., `?` or `??`.
3994    pub const fn is_help(self) -> bool {
3995        matches!(self, IpyEscapeKind::Help | IpyEscapeKind::Help2)
3996    }
3997
3998    /// Returns `true` if the escape kind is magic i.e., `%` or `%%`.
3999    pub const fn is_magic(self) -> bool {
4000        matches!(self, IpyEscapeKind::Magic | IpyEscapeKind::Magic2)
4001    }
4002
4003    pub fn as_str(self) -> &'static str {
4004        match self {
4005            IpyEscapeKind::Shell => "!",
4006            IpyEscapeKind::ShCap => "!!",
4007            IpyEscapeKind::Help => "?",
4008            IpyEscapeKind::Help2 => "??",
4009            IpyEscapeKind::Magic => "%",
4010            IpyEscapeKind::Magic2 => "%%",
4011            IpyEscapeKind::Quote => ",",
4012            IpyEscapeKind::Quote2 => ";",
4013            IpyEscapeKind::Paren => "/",
4014        }
4015    }
4016}
4017
4018/// An `Identifier` with an empty `id` is invalid.
4019///
4020/// For example, in the following code `id` will be empty.
4021/// ```python
4022/// def 1():
4023///     ...
4024/// ```
4025#[derive(Clone, Debug, PartialEq, Eq, Hash)]
4026#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
4027pub struct Identifier {
4028    pub id: Name,
4029    pub range: TextRange,
4030    pub node_index: AtomicNodeIndex,
4031}
4032
4033impl Identifier {
4034    #[inline]
4035    pub fn new(id: impl Into<Name>, range: TextRange) -> Self {
4036        Self {
4037            id: id.into(),
4038            node_index: AtomicNodeIndex::NONE,
4039            range,
4040        }
4041    }
4042
4043    pub fn id(&self) -> &Name {
4044        &self.id
4045    }
4046
4047    pub fn is_valid(&self) -> bool {
4048        !self.id.is_empty()
4049    }
4050}
4051
4052impl Identifier {
4053    #[inline]
4054    pub fn as_str(&self) -> &str {
4055        self.id.as_str()
4056    }
4057}
4058
4059impl PartialEq<str> for Identifier {
4060    #[inline]
4061    fn eq(&self, other: &str) -> bool {
4062        self.id == other
4063    }
4064}
4065
4066impl PartialEq<String> for Identifier {
4067    #[inline]
4068    fn eq(&self, other: &String) -> bool {
4069        self.id == other
4070    }
4071}
4072
4073impl std::ops::Deref for Identifier {
4074    type Target = str;
4075    #[inline]
4076    fn deref(&self) -> &Self::Target {
4077        self.id.as_str()
4078    }
4079}
4080
4081impl AsRef<str> for Identifier {
4082    #[inline]
4083    fn as_ref(&self) -> &str {
4084        self.id.as_str()
4085    }
4086}
4087
4088impl std::fmt::Display for Identifier {
4089    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4090        std::fmt::Display::fmt(&self.id, f)
4091    }
4092}
4093
4094impl From<Identifier> for Name {
4095    #[inline]
4096    fn from(identifier: Identifier) -> Name {
4097        identifier.id
4098    }
4099}
4100
4101#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
4102#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
4103pub enum Singleton {
4104    None,
4105    True,
4106    False,
4107}
4108
4109impl From<bool> for Singleton {
4110    fn from(value: bool) -> Self {
4111        if value {
4112            Singleton::True
4113        } else {
4114            Singleton::False
4115        }
4116    }
4117}
4118
4119#[cfg(test)]
4120mod tests {
4121    use ruff_text_size::{Ranged, TextRange, TextSize};
4122
4123    use crate::generated::*;
4124    use crate::{
4125        Arguments, AtomicNodeIndex, FString, FStringFlags, FStringPart, FStringPartMut,
4126        FStringValue, Mod, Parameters, StringLiteral, StringLiteralFlags,
4127    };
4128
4129    #[test]
4130    fn f_string_parts() {
4131        let fstring = |start| FString {
4132            range: TextRange::at(TextSize::new(start), TextSize::new(3)),
4133            node_index: AtomicNodeIndex::NONE,
4134            elements: Vec::new().into(),
4135            flags: FStringFlags::empty(),
4136        };
4137        let single = FStringValue::single(fstring(0));
4138        let concatenated = FStringValue::concatenated(vec![
4139            FStringPart::FString(fstring(0)),
4140            FStringPart::Literal(StringLiteral {
4141                range: TextRange::at(TextSize::new(3), TextSize::new(3)),
4142                node_index: AtomicNodeIndex::NONE,
4143                value: "x".into(),
4144                flags: StringLiteralFlags::empty(),
4145            }),
4146            FStringPart::FString(fstring(6)),
4147        ]);
4148
4149        for (mut value, starts) in [(single, vec![0]), (concatenated, vec![0, 3, 6])] {
4150            let mut parts = value.iter();
4151            let mut expected = starts.iter();
4152            while expected.len() > 0 {
4153                assert_eq!(parts.len(), expected.len());
4154                assert_eq!(
4155                    parts.next().map(|part| part.start().to_u32()),
4156                    expected.next().copied()
4157                );
4158                assert_eq!(
4159                    parts.next_back().map(|part| part.start().to_u32()),
4160                    expected.next_back().copied()
4161                );
4162            }
4163            assert_eq!(parts.len(), 0);
4164            assert_eq!(parts.next(), None);
4165            assert_eq!(parts.next_back(), None);
4166
4167            let mut parts = value.iter_mut();
4168            for (part, start) in parts.by_ref().rev().zip(starts.iter().rev()) {
4169                let range = match part {
4170                    FStringPartMut::Literal(literal) => &mut literal.range,
4171                    FStringPartMut::FString(fstring) => &mut fstring.range,
4172                };
4173                assert_eq!(range.start().to_u32(), *start);
4174                *range = TextRange::at(TextSize::new(start + 10), TextSize::new(3));
4175            }
4176            assert_eq!(parts.len(), 0);
4177            assert!(parts.next().is_none());
4178            assert!(parts.next_back().is_none());
4179            assert_eq!(
4180                value
4181                    .iter()
4182                    .map(|part| part.start().to_u32())
4183                    .collect::<Vec<_>>(),
4184                starts.iter().map(|start| start + 10).collect::<Vec<_>>(),
4185            );
4186        }
4187    }
4188
4189    #[test]
4190    #[cfg(target_pointer_width = "64")]
4191    fn size() {
4192        assert_eq!(std::mem::size_of::<Stmt>(), 88);
4193        assert_eq!(std::mem::size_of::<StmtFunctionDef>(), 88);
4194        assert_eq!(std::mem::size_of::<StmtClassDef>(), 80);
4195        assert_eq!(std::mem::size_of::<StmtTry>(), 64);
4196        assert_eq!(std::mem::size_of::<Mod>(), 32);
4197        assert_eq!(std::mem::size_of::<Pattern>(), 72);
4198        assert_eq!(std::mem::size_of::<Parameters>(), 56);
4199        assert_eq!(std::mem::size_of::<Arguments>(), 32);
4200        assert_eq!(std::mem::size_of::<Expr>(), 56);
4201        assert_eq!(std::mem::size_of::<ExprAttribute>(), 56);
4202        assert_eq!(std::mem::size_of::<ExprAwait>(), 24);
4203        assert_eq!(std::mem::size_of::<ExprBinOp>(), 32);
4204        assert_eq!(std::mem::size_of::<ExprBoolOp>(), 40);
4205        assert_eq!(std::mem::size_of::<ExprBooleanLiteral>(), 16);
4206        assert_eq!(std::mem::size_of::<ExprBytesLiteral>(), 48);
4207        assert_eq!(std::mem::size_of::<ExprCall>(), 48);
4208        assert_eq!(std::mem::size_of::<ExprCompare>(), 48);
4209        assert_eq!(std::mem::size_of::<ExprDict>(), 40);
4210        assert_eq!(std::mem::size_of::<ExprDictComp>(), 48);
4211        assert_eq!(std::mem::size_of::<ExprEllipsisLiteral>(), 12);
4212        assert_eq!(std::mem::size_of::<ExprFString>(), 48);
4213        assert_eq!(std::mem::size_of::<ExprGenerator>(), 48);
4214        assert_eq!(std::mem::size_of::<ExprIf>(), 40);
4215        assert_eq!(std::mem::size_of::<ExprIpyEscapeCommand>(), 32);
4216        assert_eq!(std::mem::size_of::<ExprLambda>(), 32);
4217        assert_eq!(std::mem::size_of::<ExprList>(), 40);
4218        assert_eq!(std::mem::size_of::<ExprListComp>(), 48);
4219        assert_eq!(std::mem::size_of::<ExprName>(), 32);
4220        assert_eq!(std::mem::size_of::<ExprNamed>(), 32);
4221        assert_eq!(std::mem::size_of::<ExprNoneLiteral>(), 12);
4222        assert_eq!(std::mem::size_of::<ExprNumberLiteral>(), 40);
4223        assert_eq!(std::mem::size_of::<ExprSet>(), 40);
4224        assert_eq!(std::mem::size_of::<ExprSetComp>(), 48);
4225        assert_eq!(std::mem::size_of::<ExprSlice>(), 40);
4226        assert_eq!(std::mem::size_of::<ExprStarred>(), 24);
4227        assert_eq!(std::mem::size_of::<ExprStringLiteral>(), 48);
4228        assert_eq!(std::mem::size_of::<ExprSubscript>(), 32);
4229        assert_eq!(std::mem::size_of::<ExprTString>(), 48);
4230        assert_eq!(std::mem::size_of::<ExprTuple>(), 40);
4231        assert_eq!(std::mem::size_of::<ExprUnaryOp>(), 24);
4232        assert_eq!(std::mem::size_of::<ExprYield>(), 24);
4233        assert_eq!(std::mem::size_of::<ExprYieldFrom>(), 24);
4234    }
4235}