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 pub fn bases(&self) -> &[Expr] {
35 match &self.arguments {
36 Some(arguments) => &arguments.args,
37 None => &[],
38 }
39 }
40
41 pub fn keywords(&self) -> &[Keyword] {
43 match &self.arguments {
44 Some(arguments) => &arguments.keywords,
45 None => &[],
46 }
47 }
48}
49
50impl StmtImportFrom {
51 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 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 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 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 pub fn precedence(&self) -> OperatorPrecedence {
114 OperatorPrecedence::from(self)
115 }
116}
117
118impl ExprCompare {
119 pub fn first_operand(&self) -> &Expr {
126 self.operands
127 .first()
128 .expect("A comparison has a left operand")
129 }
130
131 pub fn second_operand(&self) -> &Expr {
137 self.operands
138 .get(1)
139 .expect("A comparison has a right operand")
140 }
141
142 pub fn first_operator(&self) -> CmpOp {
148 *self.ops.first().expect("A comparison has an operator")
149 }
150
151 pub fn comparators(&self) -> &[Expr] {
157 &self.operands[1..]
158 }
159
160 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 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 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#[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 pub fn iter_keys(&self) -> DictKeyIterator<'_> {
254 DictKeyIterator::new(&self.items)
255 }
256
257 pub fn iter_values(&self) -> DictValueIterator<'_> {
260 DictValueIterator::new(&self.items)
261 }
262
263 pub fn key(&self, n: usize) -> Option<&Expr> {
268 self.items[n].key()
269 }
270
271 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#[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#[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#[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 None = -1, Str = b's' as i8,
461 Ascii = b'a' as i8,
463 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#[derive(Clone, PartialEq, Eq, Hash)]
488#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
489pub struct DebugText {
490 text: compact_str::CompactString,
492 expression_start: u32,
494 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 pub fn as_str(&self) -> &str {
527 &self.text
528 }
529
530 pub fn leading(&self) -> &str {
532 &self.text[..self.expression_start as usize]
533 }
534
535 pub fn expression(&self) -> &str {
537 &self.text[self.expression_start as usize..self.expression_end as usize]
538 }
539
540 pub fn trailing(&self) -> &str {
542 &self.text[self.expression_end as usize..]
543 }
544}
545
546impl ExprFString {
547 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#[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 pub fn single(value: FString) -> Self {
567 Self {
568 inner: FStringValueInner::Single(value),
569 }
570 }
571
572 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 pub fn is_implicit_concatenated(&self) -> bool {
591 matches!(self.inner, FStringValueInner::Concatenated(_))
592 }
593
594 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 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 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 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 pub fn elements(&self) -> impl Iterator<Item = &InterpolatedStringElement> {
656 self.f_strings().flat_map(|fstring| fstring.elements.iter())
657 }
658
659 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#[derive(Clone, Debug, PartialEq)]
693#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
694enum FStringValueInner {
695 Single(FString),
697
698 Concatenated(Vec<FStringPart>),
700}
701
702#[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#[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
763pub 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#[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
815pub 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 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#[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 pub fn single(value: TString) -> Self {
872 Self {
873 inner: TStringValueInner::Single(value),
874 }
875 }
876
877 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 pub fn is_implicit_concatenated(&self) -> bool {
896 matches!(self.inner, TStringValueInner::Concatenated(_))
897 }
898
899 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 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 pub fn iter(&self) -> Iter<'_, TString> {
917 self.as_slice().iter()
918 }
919
920 pub fn iter_mut(&mut self) -> IterMut<'_, TString> {
923 self.as_mut_slice().iter_mut()
924 }
925
926 pub fn elements(&self) -> impl Iterator<Item = &InterpolatedStringElement> {
938 self.iter().flat_map(|tstring| tstring.elements.iter())
939 }
940
941 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#[derive(Clone, Debug, PartialEq)]
977#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
978enum TStringValueInner {
979 Single(TString),
981
982 Concatenated(Vec<TString>),
984}
985
986pub trait StringFlags: Copy {
987 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 fn is_triple_quoted(self) -> bool {
999 self.triple_quotes().is_yes()
1000 }
1001
1002 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 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 fn opener_len(self) -> TextSize {
1028 self.prefix().text_len() + self.quote_len()
1029 }
1030
1031 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 const DOUBLE = 1 << 0;
1079
1080 const TRIPLE_QUOTED = 1 << 1;
1084
1085 const R_PREFIX_LOWER = 1 << 2;
1088
1089 const R_PREFIX_UPPER = 1 << 3;
1095
1096 const UNCLOSED = 1 << 4;
1099 }
1100}
1101
1102#[cfg(feature = "get-size")]
1103impl get_size2::GetSize for InterpolatedStringFlagsInner {}
1104
1105#[derive(Copy, Clone, Eq, PartialEq, Hash)]
1122#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1123pub struct FStringFlags(InterpolatedStringFlagsInner);
1124
1125impl FStringFlags {
1126 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#[derive(Copy, Clone, Eq, PartialEq, Hash)]
1225#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1226pub struct TStringFlags(InterpolatedStringFlagsInner);
1227
1228impl TStringFlags {
1229 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 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 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 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 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#[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#[derive(Clone, Default, PartialEq)]
1417#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1418pub struct InterpolatedStringElements(Box<[InterpolatedStringElement]>);
1419
1420impl InterpolatedStringElements {
1421 pub fn literals(&self) -> impl Iterator<Item = &InterpolatedStringLiteralElement> {
1423 self.iter().filter_map(|element| element.as_literal())
1424 }
1425
1426 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#[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 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#[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 pub fn single(string: StringLiteral) -> Self {
1550 Self {
1551 inner: StringLiteralValueInner::Single(string),
1552 }
1553 }
1554
1555 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 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 pub const fn is_implicit_concatenated(&self) -> bool {
1589 matches!(self.inner, StringLiteralValueInner::Concatenated(_))
1590 }
1591
1592 pub fn is_unicode(&self) -> bool {
1601 self.iter()
1602 .next()
1603 .is_some_and(|part| part.flags.prefix().is_unicode())
1604 }
1605
1606 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 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 pub fn iter(&self) -> Iter<'_, StringLiteral> {
1624 self.as_slice().iter()
1625 }
1626
1627 pub fn iter_mut(&mut self) -> IterMut<'_, StringLiteral> {
1630 self.as_mut_slice().iter_mut()
1631 }
1632
1633 pub fn is_empty(&self) -> bool {
1639 self.len() == 0
1640 }
1641
1642 pub fn len(&self) -> usize {
1645 self.iter().fold(0, |acc, part| acc + part.value.len())
1646 }
1647
1648 pub fn chars(&self) -> impl Iterator<Item = char> + Clone + '_ {
1650 self.iter().flat_map(|part| part.value.chars())
1651 }
1652
1653 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 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#[derive(Clone, Debug, PartialEq)]
1700#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1701enum StringLiteralValueInner {
1702 Single(StringLiteral),
1704
1705 Concatenated(Box<ConcatenatedStringLiteral>),
1707}
1708
1709bitflags! {
1710 #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
1711 struct StringLiteralFlagsInner: u8 {
1712 const DOUBLE = 1 << 0;
1715
1716 const TRIPLE_QUOTED = 1 << 1;
1719
1720 const U_PREFIX = 1 << 2;
1726
1727 const R_PREFIX_LOWER = 1 << 3;
1731
1732 const R_PREFIX_UPPER = 1 << 4;
1738
1739 const INVALID = 1 << 5;
1741
1742 const UNCLOSED = 1 << 6;
1744 }
1745}
1746
1747#[cfg(feature = "get-size")]
1748impl get_size2::GetSize for StringLiteralFlagsInner {}
1749
1750#[derive(Copy, Clone, Eq, PartialEq, Hash)]
1763#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1764pub struct StringLiteralFlags(StringLiteralFlagsInner);
1765
1766impl StringLiteralFlags {
1767 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 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 fn quote_style(self) -> Quote {
1867 if self.0.contains(StringLiteralFlagsInner::DOUBLE) {
1868 Quote::Double
1869 } else {
1870 Quote::Single
1871 }
1872 }
1873
1874 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#[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 pub fn as_str(&self) -> &str {
1927 self
1928 }
1929
1930 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 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#[derive(Clone)]
1965#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
1966struct ConcatenatedStringLiteral {
1967 strings: Vec<StringLiteral>,
1969 value: OnceLock<Box<str>>,
1971}
1972
1973impl ConcatenatedStringLiteral {
1974 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 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 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#[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 pub fn single(value: BytesLiteral) -> Self {
2026 Self {
2027 inner: BytesLiteralValueInner::Single(value),
2028 }
2029 }
2030
2031 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 pub const fn is_implicit_concatenated(&self) -> bool {
2050 matches!(self.inner, BytesLiteralValueInner::Concatenated(_))
2051 }
2052
2053 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 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 pub fn iter(&self) -> Iter<'_, BytesLiteral> {
2071 self.as_slice().iter()
2072 }
2073
2074 pub fn iter_mut(&mut self) -> IterMut<'_, BytesLiteral> {
2077 self.as_mut_slice().iter_mut()
2078 }
2079
2080 pub fn is_empty(&self) -> bool {
2086 self.iter().all(|part| part.is_empty())
2087 }
2088
2089 pub fn len(&self) -> usize {
2091 self.iter().map(|part| part.len()).sum()
2092 }
2093
2094 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 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#[derive(Clone, Debug, PartialEq)]
2146#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2147enum BytesLiteralValueInner {
2148 Single(BytesLiteral),
2150
2151 Concatenated(Vec<BytesLiteral>),
2153}
2154
2155bitflags! {
2156 #[derive(Default, Copy, Clone, PartialEq, Eq, Hash)]
2157 struct BytesLiteralFlagsInner: u8 {
2158 const DOUBLE = 1 << 0;
2161
2162 const TRIPLE_QUOTED = 1 << 1;
2165
2166 const R_PREFIX_LOWER = 1 << 2;
2169
2170 const R_PREFIX_UPPER = 1 << 3;
2175
2176 const INVALID = 1 << 4;
2178
2179 const UNCLOSED = 1 << 5;
2181 }
2182}
2183
2184#[cfg(feature = "get-size")]
2185impl get_size2::GetSize for BytesLiteralFlagsInner {}
2186
2187#[derive(Copy, Clone, Eq, PartialEq, Hash)]
2199#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
2200pub struct BytesLiteralFlags(BytesLiteralFlagsInner);
2201
2202impl BytesLiteralFlags {
2203 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 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 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 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#[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 pub fn as_slice(&self) -> &[u8] {
2344 self
2345 }
2346
2347 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 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 #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
2389 struct AnyStringFlagsInner: u16 {
2390 const DOUBLE = 1 << 0;
2393
2394 const TRIPLE_QUOTED = 1 << 1;
2397
2398 const U_PREFIX = 1 << 2;
2402
2403 const B_PREFIX = 1 << 3;
2409
2410 const F_PREFIX = 1 << 4;
2414
2415 const T_PREFIX = 1 << 5;
2419
2420 const R_PREFIX_LOWER = 1 << 6;
2425
2426 const R_PREFIX_UPPER = 1 << 7;
2432
2433 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 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 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 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 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 pub const fn is_u_string(self) -> bool {
2494 self.0.contains(AnyStringFlagsInner::U_PREFIX)
2495 }
2496
2497 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 pub const fn is_interpolated_string(self) -> bool {
2506 self.0
2507 .intersects(AnyStringFlagsInner::F_PREFIX.union(AnyStringFlagsInner::T_PREFIX))
2508 }
2509
2510 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 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 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 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 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 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 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#[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#[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#[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 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 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 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#[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#[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#[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#[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#[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#[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#[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#[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#[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 pub fn is_irrefutable(&self) -> bool {
3082 self.irrefutable_pattern().is_some()
3083 }
3084
3085 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 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#[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#[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 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#[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#[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#[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#[derive(Debug, PartialEq, Clone, Copy)]
3258pub enum AnyParameterRef<'a> {
3259 Variadic(&'a Parameter),
3266
3267 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) => ¶m.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#[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 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 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 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 pub fn iter(&self) -> ParametersIterator<'_> {
3361 ParametersIterator::new(self)
3362 }
3363
3364 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 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 pub fn includes(&self, name: &str) -> bool {
3392 self.iter().any(|param| param.name() == name)
3393 }
3394
3395 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 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
3545impl 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
3565pub 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 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 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 self.next_variadic_before(TextSize::new(u32::MAX))
3622 .map(AnyParameterRef::Variadic)
3623 }
3624}
3625
3626impl FusedIterator for ParametersSourceOrderIterator<'_> {}
3627
3628#[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 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#[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#[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 pub fn len(&self) -> usize {
3755 self.args.len() + self.keywords.len()
3756 }
3757
3758 pub fn is_empty(&self) -> bool {
3760 self.len() == 0
3761 }
3762
3763 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 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 pub fn find_argument_value(&self, name: &str, position: usize) -> Option<&Expr> {
3783 self.find_argument(name, position).map(ArgOrKeyword::value)
3784 }
3785
3786 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 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#[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#[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
3917pub 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#[derive(PartialEq, Eq, Debug, Clone, Hash, Copy)]
3934#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
3935pub enum IpyEscapeKind {
3936 Shell,
3938 ShCap,
3940 Help,
3942 Help2,
3944 Magic,
3946 Magic2,
3948 Quote,
3951 Quote2,
3953 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 pub const fn is_help(self) -> bool {
3995 matches!(self, IpyEscapeKind::Help | IpyEscapeKind::Help2)
3996 }
3997
3998 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#[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}