Repository navigation
Expand file tree
/
Copy pathnodes.rs
More file actions
4260 lines (3760 loc) · 137 KB
/
Copy pathnodes.rs
File metadata and controls
4260 lines (3760 loc) · 137 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::derive_partial_eq_without_eq)]
use crate::AtomicNodeIndex;
use crate::generated::{
ExprBytesLiteral, ExprCall, ExprCompare, ExprDict, ExprFString, ExprList, ExprName, ExprSet,
ExprStringLiteral, ExprTString, ExprTuple, PatternMatchAs, PatternMatchOr, StmtClassDef,
};
use std::borrow::Cow;
use std::fmt;
use std::fmt::Debug;
use std::iter::{FusedIterator, Once};
use std::ops::{Deref, DerefMut};
use std::slice::{Iter, IterMut};
use std::sync::OnceLock;
use bitflags::bitflags;
use thin_vec::ThinVec;
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use crate::str_prefix::{
AnyStringPrefix, ByteStringPrefix, FStringPrefix, StringLiteralPrefix, TStringPrefix,
};
use crate::{
Expr, ExprRef, InterpolatedStringElement, LiteralExpressionRef, OperatorPrecedence, Pattern,
Stmt, TypeParam, int,
name::Name,
str::{Quote, TripleQuotes},
};
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub enum ConstantValue {
None,
Boolean(bool),
Str(Box<str>),
Bytes(Box<[u8]>),
Integer(Box<str>),
Tuple(Vec<Self>),
Frozenset(Vec<Self>),
Float(f64),
Complex { real: f64, imag: f64 },
Ellipsis,
}
impl StmtClassDef {
/// Return an iterator over the bases of the class.
pub fn bases(&self) -> &[Expr] {
match &self.arguments {
Some(arguments) => &arguments.args,
None => &[],
}
}
/// Return an iterator over the metaclass keywords of the class.
pub fn keywords(&self) -> &[Keyword] {
match &self.arguments {
Some(arguments) => &arguments.keywords,
None => &[],
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub struct ElifElseClause {
pub range: TextRange,
pub node_index: AtomicNodeIndex,
pub test: Option<Expr>,
pub body: Suite,
pub runtime_body: Option<Vec<Option<Stmt>>>,
pub runtime_orelse: Option<Vec<Option<Stmt>>>,
}
impl Expr {
/// Returns `true` if the expression is a literal expression.
///
/// A literal expression is either a string literal, bytes literal,
/// integer, float, complex number, boolean, `None`, or ellipsis (`...`).
pub fn is_literal_expr(&self) -> bool {
matches!(
self,
Expr::StringLiteral(_)
| Expr::BytesLiteral(_)
| Expr::NumberLiteral(_)
| Expr::Constant(_)
| Expr::BooleanLiteral(_)
| Expr::NoneLiteral(_)
| Expr::EllipsisLiteral(_)
)
}
/// Returns [`LiteralExpressionRef`] if the expression is a literal expression.
pub fn as_literal_expr(&self) -> Option<LiteralExpressionRef<'_>> {
match self {
Expr::StringLiteral(expr) => Some(LiteralExpressionRef::StringLiteral(expr)),
Expr::BytesLiteral(expr) => Some(LiteralExpressionRef::BytesLiteral(expr)),
Expr::NumberLiteral(expr) => Some(LiteralExpressionRef::NumberLiteral(expr)),
Expr::BooleanLiteral(expr) => Some(LiteralExpressionRef::BooleanLiteral(expr)),
Expr::NoneLiteral(expr) => Some(LiteralExpressionRef::NoneLiteral(expr)),
Expr::EllipsisLiteral(expr) => Some(LiteralExpressionRef::EllipsisLiteral(expr)),
_ => None,
}
}
/// Return the value expression after peeling off any nested named expressions.
///
/// For example, this returns the `x` expression for both `x` and `(y := x)`.
pub fn expression_value(&self) -> &Self {
let mut expr = self;
while let Expr::Named(named) = expr {
expr = &named.value;
}
expr
}
/// Return the [`OperatorPrecedence`] of this expression
pub fn precedence(&self) -> OperatorPrecedence {
OperatorPrecedence::from(self)
}
}
impl ExprCompare {
/// Returns the initial operand (`a` in `a < b <= c`).
///
/// # Panics
///
/// Panics if there are no operands. The parser always produces at least two operands,
/// synthesizing an invalid name expression for a missing operand during error recovery.
pub fn first_operand(&self) -> &Expr {
self.operands
.first()
.expect("A comparison has a left operand")
}
/// Returns the right operand of the first comparison (`b` in `a < b <= c`).
///
/// # Panics
///
/// Panics if there are fewer than two operands. See [`Self::first_operand`].
pub fn second_operand(&self) -> &Expr {
self.operands
.get(1)
.expect("A comparison has a right operand")
}
/// Returns the first comparison operator (`<` in `a < b <= c`).
///
/// # Panics
///
/// Panics if there are no operators. The parser always produces at least one operator.
pub fn first_operator(&self) -> CmpOp {
*self.ops.first().expect("A comparison has an operator")
}
/// Returns all operands after the initial operand (`[b, c]` in `a < b <= c`).
///
/// # Panics
///
/// Panics if there are no operands. See [`Self::first_operand`].
pub fn comparators(&self) -> &[Expr] {
&self.operands[1..]
}
/// Returns `(left, operator, right)` if there is exactly one operator and two operands.
pub fn as_single(&self) -> Option<(&Expr, &CmpOp, &Expr)> {
match (&*self.operands, &*self.ops) {
([left, right], [op]) => Some((left, op, right)),
_ => None,
}
}
/// Iterates over each comparison as `(left, operator, right)`.
///
/// For `a < b <= c`, yields `(a, <, b)` followed by `(b, <=, c)`.
pub fn iter(
&self,
) -> impl DoubleEndedIterator<Item = (&Expr, &CmpOp, &Expr)> + ExactSizeIterator {
self.operands
.iter()
.zip(self.ops.iter())
.zip(self.operands.iter().skip(1))
.map(|((left, op), right)| (left, op, right))
}
}
impl ExprRef<'_> {
/// See [`Expr::is_literal_expr`].
pub fn is_literal_expr(&self) -> bool {
matches!(
self,
ExprRef::StringLiteral(_)
| ExprRef::BytesLiteral(_)
| ExprRef::NumberLiteral(_)
| ExprRef::BooleanLiteral(_)
| ExprRef::NoneLiteral(_)
| ExprRef::EllipsisLiteral(_)
)
}
pub fn precedence(&self) -> OperatorPrecedence {
OperatorPrecedence::from(*self)
}
}
/// Represents an item in a [dictionary literal display][1].
///
/// Consider the following Python dictionary literal:
/// ```python
/// {key1: value1, **other_dictionary}
/// ```
///
/// In our AST, this would be represented using an `ExprDict` node containing
/// two `DictItem` nodes inside it:
/// ```ignore
/// [
/// DictItem {
/// key: Some(Expr::Name(ExprName { id: "key1" })),
/// value: Expr::Name(ExprName { id: "value1" }),
/// },
/// DictItem {
/// key: None,
/// value: Expr::Name(ExprName { id: "other_dictionary" }),
/// }
/// ]
/// ```
///
/// [1]: https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub struct DictItem {
pub key: Option<Expr>,
pub value: Expr,
}
impl DictItem {
fn key(&self) -> Option<&Expr> {
self.key.as_ref()
}
fn value(&self) -> &Expr {
&self.value
}
}
impl Ranged for DictItem {
fn range(&self) -> TextRange {
TextRange::new(
self.key.as_ref().map_or(self.value.start(), Ranged::start),
self.value.end(),
)
}
}
impl ExprDict {
/// Returns an `Iterator` over the AST nodes representing the
/// dictionary's keys.
pub fn iter_keys(&self) -> DictKeyIterator<'_> {
DictKeyIterator::new(&self.items)
}
/// Returns an `Iterator` over the AST nodes representing the
/// dictionary's values.
pub fn iter_values(&self) -> DictValueIterator<'_> {
DictValueIterator::new(&self.items)
}
/// Returns the AST node representing the *n*th key of this
/// dictionary.
///
/// Panics: If the index `n` is out of bounds.
pub fn key(&self, n: usize) -> Option<&Expr> {
self.items[n].key()
}
/// Returns the AST node representing the *n*th value of this
/// dictionary.
///
/// Panics: If the index `n` is out of bounds.
pub fn value(&self, n: usize) -> &Expr {
self.items[n].value()
}
pub fn iter(&self) -> std::slice::Iter<'_, DictItem> {
self.items.iter()
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
impl<'a> IntoIterator for &'a ExprDict {
type IntoIter = std::slice::Iter<'a, DictItem>;
type Item = &'a DictItem;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Debug, Clone)]
pub struct DictKeyIterator<'a> {
items: Iter<'a, DictItem>,
}
impl<'a> DictKeyIterator<'a> {
fn new(items: &'a [DictItem]) -> Self {
Self {
items: items.iter(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<'a> Iterator for DictKeyIterator<'a> {
type Item = Option<&'a Expr>;
fn next(&mut self) -> Option<Self::Item> {
self.items.next().map(DictItem::key)
}
fn last(mut self) -> Option<Self::Item> {
self.next_back()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.items.size_hint()
}
}
impl DoubleEndedIterator for DictKeyIterator<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.items.next_back().map(DictItem::key)
}
}
impl FusedIterator for DictKeyIterator<'_> {}
impl ExactSizeIterator for DictKeyIterator<'_> {}
#[derive(Debug, Clone)]
pub struct DictValueIterator<'a> {
items: Iter<'a, DictItem>,
}
impl<'a> DictValueIterator<'a> {
fn new(items: &'a [DictItem]) -> Self {
Self {
items: items.iter(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<'a> Iterator for DictValueIterator<'a> {
type Item = &'a Expr;
fn next(&mut self) -> Option<Self::Item> {
self.items.next().map(DictItem::value)
}
fn last(mut self) -> Option<Self::Item> {
self.next_back()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.items.size_hint()
}
}
impl DoubleEndedIterator for DictValueIterator<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.items.next_back().map(DictItem::value)
}
}
impl FusedIterator for DictValueIterator<'_> {}
impl ExactSizeIterator for DictValueIterator<'_> {}
impl ExprSet {
pub fn iter(&self) -> std::slice::Iter<'_, Expr> {
self.elts.iter()
}
pub fn len(&self) -> usize {
self.elts.len()
}
pub fn is_empty(&self) -> bool {
self.elts.is_empty()
}
}
impl<'a> IntoIterator for &'a ExprSet {
type IntoIter = std::slice::Iter<'a, Expr>;
type Item = &'a Expr;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub struct InterpolatedStringFormatSpec {
pub range: TextRange,
pub node_index: AtomicNodeIndex,
pub elements: InterpolatedStringElements,
}
/// See also [FormattedValue](https://docs.python.org/3/library/ast.html#ast.FormattedValue)
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub struct InterpolatedElement {
pub range: TextRange,
pub node_index: AtomicNodeIndex,
pub expression: Box<Expr>,
pub debug_text: Option<DebugText>,
pub conversion: ConversionFlag,
pub format_spec: Option<Box<InterpolatedStringFormatSpec>>,
pub runtime_str: Option<crate::ConstantValue>,
pub runtime_interpolation_format_spec: Option<Box<Expr>>,
pub runtime_formatted_value_format_spec: Option<Box<Expr>>,
}
/// An `FStringLiteralElement` with an empty `value` is an invalid f-string element.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub struct InterpolatedStringLiteralElement {
pub range: TextRange,
pub node_index: AtomicNodeIndex,
pub value: Box<str>,
}
impl InterpolatedStringLiteralElement {
pub fn is_valid(&self) -> bool {
!self.value.is_empty()
}
}
impl Deref for InterpolatedStringLiteralElement {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.value
}
}
/// Transforms a value prior to formatting it.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, is_macro::Is)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
#[repr(i8)]
#[expect(clippy::cast_possible_wrap)]
pub enum ConversionFlag {
/// No conversion
None = -1, // CPython uses -1
/// Converts by calling `str(<value>)`.
Str = b's' as i8,
/// Converts by calling `ascii(<value>)`.
Ascii = b'a' as i8,
/// Converts by calling `repr(<value>)`.
Repr = b'r' as i8,
}
impl ConversionFlag {
pub fn to_byte(&self) -> Option<u8> {
match self {
Self::None => None,
flag => Some(*flag as u8),
}
}
pub fn to_char(&self) -> Option<char> {
Some(self.to_byte()? as char)
}
}
/// The debug text of a self-documenting f-string expression (e.g., `f"{x=}"`).
///
/// Stores the concatenation of leading text, expression source, and trailing text as a single
/// [`CompactString`], with byte offsets to split them. The offsets are needed because the leading
/// and trailing portions can contain non-whitespace characters (grouping parentheses, comments in
/// triple-quoted f-strings) that cannot be distinguished from expression content by scanning.
///
/// [`CompactString`]: compact_str::CompactString
#[derive(Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub struct DebugText {
/// The full text between the `{` and the conversion / `format_spec` / `}`.
text: compact_str::CompactString,
/// Byte offset where the expression source begins.
expression_start: u32,
/// Byte offset where the expression source ends.
expression_end: u32,
}
impl std::fmt::Debug for DebugText {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DebugText")
.field("leading", &self.leading())
.field("expression", &self.expression())
.field("trailing", &self.trailing())
.finish()
}
}
impl DebugText {
pub fn new(leading: &str, expression: &str, trailing: &str) -> Self {
let expression_start = leading.text_len().to_u32();
let expression_end = expression_start + expression.text_len().to_u32();
let mut buf = compact_str::CompactString::with_capacity(
leading.len() + expression.len() + trailing.len(),
);
buf.push_str(leading);
buf.push_str(expression);
buf.push_str(trailing);
Self {
text: buf,
expression_start,
expression_end,
}
}
/// The full debug text between the `{` and the conversion / `format_spec` / `}`.
pub fn as_str(&self) -> &str {
&self.text
}
/// The text between the `{` and the expression node.
pub fn leading(&self) -> &str {
&self.text[..self.expression_start as usize]
}
/// The source text of the expression (e.g., `0x0` in `f"{0x0=}"`).
pub fn expression(&self) -> &str {
&self.text[self.expression_start as usize..self.expression_end as usize]
}
/// The text between the expression and the conversion, the `format_spec`, or the `}`.
pub fn trailing(&self) -> &str {
&self.text[self.expression_end as usize..]
}
}
impl ExprFString {
/// Returns the single [`FString`] if the f-string isn't implicitly concatenated, [`None`]
/// otherwise.
pub const fn as_single_part_fstring(&self) -> Option<&FString> {
match &self.value.inner {
FStringValueInner::Single(fstring) => Some(fstring),
FStringValueInner::Concatenated(_) => None,
}
}
}
/// The value representing an [`ExprFString`].
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub struct FStringValue {
inner: FStringValueInner,
}
impl FStringValue {
/// Creates a new f-string literal with a single [`FString`] part.
pub fn single(value: FString) -> Self {
Self {
inner: FStringValueInner::Single(value),
}
}
/// Creates a new f-string with the given values that represents an implicitly
/// concatenated f-string.
///
/// # Panics
///
/// Panics if `values` has less than 2 elements.
/// Use [`FStringValue::single`] instead.
pub fn concatenated(values: Vec<FStringPart>) -> Self {
assert!(
values.len() > 1,
"Use `FStringValue::single` to create single-part f-strings"
);
Self {
inner: FStringValueInner::Concatenated(values),
}
}
/// Returns `true` if the f-string is implicitly concatenated, `false` otherwise.
pub fn is_implicit_concatenated(&self) -> bool {
matches!(self.inner, FStringValueInner::Concatenated(_))
}
/// Returns an iterator over the parts of this f-string, in source order.
pub fn iter(&self) -> FStringParts<'_> {
match &self.inner {
FStringValueInner::Single(fstring) => FStringParts::Single(std::iter::once(fstring)),
FStringValueInner::Concatenated(parts) => FStringParts::Concatenated(parts.iter()),
}
}
/// Returns a mutable iterator over the parts of this f-string, in source order.
pub fn iter_mut(&mut self) -> FStringPartsMut<'_> {
match &mut self.inner {
FStringValueInner::Single(fstring) => FStringPartsMut::Single(std::iter::once(fstring)),
FStringValueInner::Concatenated(parts) => {
FStringPartsMut::Concatenated(parts.iter_mut())
}
}
}
/// Returns an iterator over the [`StringLiteral`] parts contained in this value.
///
/// Note that this doesn't recurse into the f-string parts. For example,
///
/// ```python
/// "foo" f"bar {x}" "baz" f"qux"
/// ```
///
/// Here, the string literal parts returned would be `"foo"` and `"baz"`.
pub fn literals(&self) -> impl Iterator<Item = &StringLiteral> {
self.iter().filter_map(|part| match part {
FStringPartRef::Literal(literal) => Some(literal),
FStringPartRef::FString(_) => None,
})
}
/// Returns an iterator over the [`FString`] parts contained in this value.
///
/// Note that this doesn't recurse into the f-string parts. For example,
///
/// ```python
/// "foo" f"bar {x}" "baz" f"qux"
/// ```
///
/// Here, the f-string parts returned would be `f"bar {x}"` and `f"qux"`.
pub fn f_strings(&self) -> impl Iterator<Item = &FString> {
self.iter().filter_map(|part| match part {
FStringPartRef::FString(fstring) => Some(fstring),
FStringPartRef::Literal(_) => None,
})
}
/// Returns an iterator over all the [`InterpolatedStringElement`] contained in this value.
///
/// An f-string element is what makes up an [`FString`] i.e., it is either a
/// string literal or an expression. In the following example,
///
/// ```python
/// "foo" f"bar {x}" "baz" f"qux"
/// ```
///
/// The f-string elements returned would be string literal (`"bar "`),
/// expression (`x`) and string literal (`"qux"`).
pub fn elements(&self) -> impl Iterator<Item = &InterpolatedStringElement> {
self.f_strings().flat_map(|fstring| fstring.elements.iter())
}
/// Returns `true` if the node represents an empty f-string literal.
///
/// Note that a [`FStringValue`] node will always have >= 1 [`FStringPart`]s inside it.
/// This method checks whether the value of the concatenated parts is equal to the empty
/// f-string, not whether the f-string has 0 parts inside it.
pub fn is_empty_literal(&self) -> bool {
match &self.inner {
FStringValueInner::Single(fstring) => fstring.elements.is_empty(),
FStringValueInner::Concatenated(fstring_parts) => {
fstring_parts.iter().all(FStringPart::is_empty_literal)
}
}
}
}
impl<'a> IntoIterator for &'a FStringValue {
type Item = FStringPartRef<'a>;
type IntoIter = FStringParts<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a> IntoIterator for &'a mut FStringValue {
type Item = FStringPartMut<'a>;
type IntoIter = FStringPartsMut<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
/// An internal representation of [`FStringValue`].
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
enum FStringValueInner {
/// A single f-string i.e., `f"foo"`.
Single(FString),
/// An implicitly concatenated f-string i.e., `"foo" f"bar {x}"`.
Concatenated(Vec<FStringPart>),
}
/// An f-string part which is either a string literal or an f-string.
#[derive(Clone, Debug, PartialEq, is_macro::Is)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub enum FStringPart {
Literal(StringLiteral),
FString(FString),
}
impl FStringPart {
pub fn quote_style(&self) -> Quote {
FStringPartRef::from(self).quote_style()
}
pub fn is_empty_literal(&self) -> bool {
match &self {
FStringPart::Literal(string_literal) => string_literal.value.is_empty(),
FStringPart::FString(f_string) => f_string.elements.is_empty(),
}
}
}
impl Ranged for FStringPart {
fn range(&self) -> TextRange {
FStringPartRef::from(self).range()
}
}
/// A borrowed string literal or f-string part of an [`FStringValue`].
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum FStringPartRef<'a> {
Literal(&'a StringLiteral),
FString(&'a FString),
}
impl FStringPartRef<'_> {
pub fn quote_style(self) -> Quote {
match self {
Self::Literal(literal) => literal.flags.quote_style(),
Self::FString(fstring) => fstring.flags.quote_style(),
}
}
}
impl<'a> From<&'a FStringPart> for FStringPartRef<'a> {
fn from(part: &'a FStringPart) -> Self {
match part {
FStringPart::Literal(literal) => Self::Literal(literal),
FStringPart::FString(fstring) => Self::FString(fstring),
}
}
}
impl Ranged for FStringPartRef<'_> {
fn range(&self) -> TextRange {
match self {
Self::Literal(literal) => literal.range(),
Self::FString(fstring) => fstring.range(),
}
}
}
/// A mutably borrowed string literal or f-string part of an [`FStringValue`].
pub enum FStringPartMut<'a> {
Literal(&'a mut StringLiteral),
FString(&'a mut FString),
}
impl<'a> From<&'a mut FStringPart> for FStringPartMut<'a> {
fn from(part: &'a mut FStringPart) -> Self {
match part {
FStringPart::Literal(literal) => Self::Literal(literal),
FStringPart::FString(fstring) => Self::FString(fstring),
}
}
}
/// The iterator returned by [`FStringValue::iter`].
#[derive(Clone)]
pub enum FStringParts<'a> {
Single(Once<&'a FString>),
Concatenated(Iter<'a, FStringPart>),
}
impl<'a> Iterator for FStringParts<'a> {
type Item = FStringPartRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
match self {
Self::Single(single) => single.next().map(FStringPartRef::FString),
Self::Concatenated(parts) => parts.next().map(FStringPartRef::from),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
Self::Single(single) => single.size_hint(),
Self::Concatenated(parts) => parts.size_hint(),
}
}
}
impl DoubleEndedIterator for FStringParts<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
match self {
Self::Single(single) => single.next_back().map(FStringPartRef::FString),
Self::Concatenated(parts) => parts.next_back().map(FStringPartRef::from),
}
}
}
impl ExactSizeIterator for FStringParts<'_> {}
impl FusedIterator for FStringParts<'_> {}
/// The iterator returned by [`FStringValue::iter_mut`].
pub enum FStringPartsMut<'a> {
Single(Once<&'a mut FString>),
Concatenated(IterMut<'a, FStringPart>),
}
impl<'a> Iterator for FStringPartsMut<'a> {
type Item = FStringPartMut<'a>;
fn next(&mut self) -> Option<Self::Item> {
match self {
Self::Single(single) => single.next().map(FStringPartMut::FString),
Self::Concatenated(parts) => parts.next().map(FStringPartMut::from),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
Self::Single(single) => single.size_hint(),
Self::Concatenated(parts) => parts.size_hint(),
}
}
}
impl DoubleEndedIterator for FStringPartsMut<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
match self {
Self::Single(single) => single.next_back().map(FStringPartMut::FString),
Self::Concatenated(parts) => parts.next_back().map(FStringPartMut::from),
}
}
}
impl ExactSizeIterator for FStringPartsMut<'_> {}
impl FusedIterator for FStringPartsMut<'_> {}
impl ExprTString {
/// Returns the single [`TString`] if the t-string isn't implicitly concatenated, [`None`]
/// otherwise.
pub const fn as_single_part_tstring(&self) -> Option<&TString> {
match &self.value.inner {
TStringValueInner::Single(tstring) => Some(tstring),
TStringValueInner::Concatenated(_) => None,
}
}
}
/// The value representing an [`ExprTString`].
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
pub struct TStringValue {
inner: TStringValueInner,
}
impl TStringValue {
/// Creates a new t-string literal with a single [`TString`] part.
pub fn single(value: TString) -> Self {
Self {
inner: TStringValueInner::Single(value),
}
}
/// Creates a new t-string with the given values that represents an implicitly
/// concatenated t-string.
///
/// # Panics
///
/// Panics if `values` has less than 2 elements.
/// Use [`TStringValue::single`] instead.
pub fn concatenated(values: Vec<TString>) -> Self {
assert!(
values.len() > 1,
"Use `TStringValue::single` to create single-part t-strings"
);
Self {
inner: TStringValueInner::Concatenated(values),
}
}
/// Returns `true` if the t-string is implicitly concatenated, `false` otherwise.
pub fn is_implicit_concatenated(&self) -> bool {
matches!(self.inner, TStringValueInner::Concatenated(_))
}
/// Returns a slice of all the [`TString`]s contained in this value.
pub fn as_slice(&self) -> &[TString] {
match &self.inner {
TStringValueInner::Single(part) => std::slice::from_ref(part),
TStringValueInner::Concatenated(parts) => parts,
}
}
/// Returns a mutable slice of all the [`TString`]s contained in this value.
fn as_mut_slice(&mut self) -> &mut [TString] {
match &mut self.inner {
TStringValueInner::Single(part) => std::slice::from_mut(part),
TStringValueInner::Concatenated(parts) => parts,
}
}
/// Returns an iterator over all the [`TString`]s contained in this value.
pub fn iter(&self) -> Iter<'_, TString> {
self.as_slice().iter()
}
/// Returns an iterator over all the [`TString`]s contained in this value
/// that allows modification.
pub fn iter_mut(&mut self) -> IterMut<'_, TString> {
self.as_mut_slice().iter_mut()
}
/// Returns an iterator over all the [`InterpolatedStringElement`] contained in this value.
///
/// An interpolated string element is what makes up an [`TString`] i.e., it is either a
/// string literal or an interpolation. In the following example,
///
/// ```python
/// t"foo" t"bar {x}" t"baz" t"qux"
/// ```
///
/// The interpolated string elements returned would be string literal (`"bar "`),
/// interpolation (`x`) and string literal (`"qux"`).
pub fn elements(&self) -> impl Iterator<Item = &InterpolatedStringElement> {
self.iter().flat_map(|tstring| tstring.elements.iter())
}
/// Returns `true` if the node represents an empty t-string in the
/// sense that `__iter__` returns an empty iterable.
///
/// Beware that empty t-strings are still truthy, i.e. `bool(t"") == True`.
///
/// Note that a [`TStringValue`] node will always contain at least one
/// [`TString`] node. This method checks whether each of the constituent
/// t-strings (in an implicitly concatenated t-string) are empty
/// in the above sense.
pub fn is_empty_iterable(&self) -> bool {
match &self.inner {
TStringValueInner::Single(tstring) => tstring.is_empty(),
TStringValueInner::Concatenated(tstrings) => tstrings.iter().all(TString::is_empty),
}
}
}
impl<'a> IntoIterator for &'a TStringValue {
type Item = &'a TString;
type IntoIter = Iter<'a, TString>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a> IntoIterator for &'a mut TStringValue {
type Item = &'a mut TString;
type IntoIter = IterMut<'a, TString>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
/// An internal representation of [`TStringValue`].
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "get-size", derive(get_size2::GetSize))]
enum TStringValueInner {
/// A single t-string i.e., `t"foo"`.
Single(TString),
/// An implicitly concatenated t-string i.e., `t"foo" t"bar {x}"`.
Concatenated(Vec<TString>),
}
pub trait StringFlags: Copy {
/// Does the string use single or double quotes in its opener and closer?
fn quote_style(self) -> Quote;
fn triple_quotes(self) -> TripleQuotes;
fn prefix(self) -> AnyStringPrefix;