Repository navigation
Expand file tree
/
Copy pathcomparable.rs
More file actions
2415 lines (2188 loc) · 67.9 KB
/
Copy pathcomparable.rs
File metadata and controls
2415 lines (2188 loc) · 67.9 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
//! Structural equality and hashing for borrowed Python AST nodes.
//!
//! Two [`ComparableExpr`]s are considered equal if the underlying AST nodes have the
//! same shape, ignoring trivia (e.g., parentheses, comments, and whitespace), the
//! location in the source code, and other contextual information (e.g., whether they
//! represent reads or writes, which is typically encoded in the Python AST).
//!
//! For example, in `[(a, b) for a, b in c]`, the `(a, b)` and `a, b` expressions are
//! considered equal, despite the former being parenthesized, and despite the former
//! being a write ([`ast::ExprContext::Store`]) and the latter being a read
//! ([`ast::ExprContext::Load`]).
//!
//! Similarly, `"a" "b"` and `"ab"` would be considered equal, despite the former being
//! an implicit concatenation of string literals, as these expressions are considered to
//! have the same shape in that they evaluate to the same value.
use crate as ast;
use crate::{ConstantValue, Expr, Number};
use std::borrow::Cow;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
/// Use `compare_enum!(Wrapper(AstEnum) { ... })` to compare borrowed AST nodes
/// by their structural fields. Listing the fields once keeps the wrapper's
/// `PartialEq`, `Hash`, and `Debug` implementations in sync. Equality checks
/// the variants before reading either node's fields.
///
/// List every variant of `AstEnum`. For example, `ComparableStmt` uses both
/// forms of entry.
///
/// - `Return => stmt_return_fields` delegates to a function taking
/// `&ast::StmtReturn` and returning `Option<ComparableExpr<'_>>`. Only the
/// return value participates in comparison.
/// - `Pass(ast::StmtPass { range: _, node_index: _ })` compares just the
/// variant. Any two `pass` statements are structurally equal.
///
/// Destructure the node exhaustively in the helper or the inline pattern so
/// that adding an AST field forces a decision about whether to compare it.
macro_rules! compare_enum {
($key:ident($ast:ident) {
$($variant:ident $(($ignored:pat))? $(=> $fields:ident)?,)*
}) => {
impl PartialEq for $key<'_> {
fn eq(&self, other: &Self) -> bool {
match self.0 {
$(
$(ast::$ast::$variant(left) => match other.0 {
ast::$ast::$variant(right) => $fields(left) == $fields(right),
_ => false,
},)?
$(ast::$ast::$variant($ignored) => matches!(other.0, ast::$ast::$variant(_)),)?
)*
}
}
}
impl Eq for $key<'_> {}
impl Hash for $key<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant::<ast::$ast>(&self.0).hash(state);
match self.0 {
$(
$(ast::$ast::$variant(node) => $fields(node).hash(state),)?
$(ast::$ast::$variant($ignored) => {},)?
)*
}
}
}
impl fmt::Debug for $key<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
$(
$(ast::$ast::$variant(node) => f
.debug_tuple(stringify!($variant))
.field(&$fields(node))
.finish(),)?
$(ast::$ast::$variant($ignored) => f.write_str(stringify!($variant)),)?
)*
}
}
}
};
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableAlias<'a> {
name: &'a str,
asname: Option<&'a str>,
}
impl<'a> From<&'a ast::Alias> for ComparableAlias<'a> {
fn from(alias: &'a ast::Alias) -> Self {
let ast::Alias {
name,
asname,
range: _,
node_index: _,
} = alias;
Self {
name: name.as_str(),
asname: asname.as_deref(),
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableWithItem<'a> {
context_expr: ComparableExpr<'a>,
optional_vars: Option<ComparableExpr<'a>>,
}
impl<'a> From<&'a ast::WithItem> for ComparableWithItem<'a> {
fn from(with_item: &'a ast::WithItem) -> Self {
let ast::WithItem {
context_expr,
optional_vars,
range: _,
node_index: _,
} = with_item;
Self {
context_expr: context_expr.into(),
optional_vars: optional_vars.as_ref().map(Into::into),
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparablePatternKeyword<'a> {
attr: &'a str,
pattern: ComparablePattern<'a>,
}
impl<'a> From<&'a ast::PatternKeyword> for ComparablePatternKeyword<'a> {
fn from(keyword: &'a ast::PatternKeyword) -> Self {
let ast::PatternKeyword {
attr,
pattern,
range: _,
node_index: _,
} = keyword;
Self {
attr: attr.as_str(),
pattern: pattern.into(),
}
}
}
/// A borrowed structural comparison key for a match pattern.
#[derive(Clone, Copy)]
pub struct ComparablePattern<'a>(&'a ast::Pattern);
impl<'a> From<&'a ast::Pattern> for ComparablePattern<'a> {
fn from(node: &'a ast::Pattern) -> Self {
Self(node)
}
}
compare_enum!(ComparablePattern(Pattern) {
MatchValue => match_value_fields,
MatchSingleton => match_singleton_fields,
MatchSequence => match_sequence_fields,
MatchMapping => match_mapping_fields,
MatchClass => match_class_fields,
MatchStar => match_star_fields,
MatchAs => match_as_fields,
MatchOr => match_or_fields,
});
fn match_value_fields(node: &ast::PatternMatchValue) -> ComparableExpr<'_> {
let ast::PatternMatchValue {
value,
range: _,
node_index: _,
} = node;
value.into()
}
fn match_singleton_fields(node: &ast::PatternMatchSingleton) -> ast::Singleton {
let ast::PatternMatchSingleton {
value,
range: _,
node_index: _,
} = node;
*value
}
fn match_sequence_fields(node: &ast::PatternMatchSequence) -> ComparablePatternSlice<'_> {
let ast::PatternMatchSequence {
runtime_patterns: _,
patterns,
range: _,
node_index: _,
} = node;
ComparableSlice::new(patterns)
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct MatchMappingFields<'a> {
keys: ComparableExprSlice<'a>,
patterns: ComparablePatternSlice<'a>,
rest: Option<&'a str>,
}
fn match_mapping_fields(node: &ast::PatternMatchMapping) -> MatchMappingFields<'_> {
let ast::PatternMatchMapping {
runtime_keys: _,
runtime_patterns: _,
keys,
patterns,
rest,
range: _,
node_index: _,
} = node;
MatchMappingFields {
keys: ComparableSlice::new(keys),
patterns: ComparableSlice::new(patterns),
rest: rest.as_deref(),
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct MatchClassFields<'a> {
cls: ComparableExpr<'a>,
patterns: ComparablePatternSlice<'a>,
keywords: ComparableSlice<'a, ast::PatternKeyword, ComparablePatternKeyword<'a>>,
}
fn match_class_fields(node: &ast::PatternMatchClass) -> MatchClassFields<'_> {
let ast::PatternMatchClass {
runtime_patterns: _,
runtime_kwd_attrs: _,
runtime_kwd_patterns: _,
cls,
arguments:
ast::PatternArguments {
patterns,
keywords,
range: _,
node_index: _,
},
range: _,
node_index: _,
} = node;
MatchClassFields {
cls: cls.into(),
patterns: ComparableSlice::new(patterns),
keywords: ComparableSlice::new(keywords),
}
}
fn match_star_fields(node: &ast::PatternMatchStar) -> Option<&str> {
let ast::PatternMatchStar {
name,
range: _,
node_index: _,
} = node;
name.as_deref()
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct MatchAsFields<'a> {
pattern: Option<ComparablePattern<'a>>,
name: Option<&'a str>,
}
fn match_as_fields(node: &ast::PatternMatchAs) -> MatchAsFields<'_> {
let ast::PatternMatchAs {
pattern,
name,
range: _,
node_index: _,
} = node;
MatchAsFields {
pattern: pattern.as_deref().map(Into::into),
name: name.as_deref(),
}
}
fn match_or_fields(node: &ast::PatternMatchOr) -> ComparablePatternSlice<'_> {
let ast::PatternMatchOr {
runtime_patterns: _,
patterns,
range: _,
node_index: _,
} = node;
ComparableSlice::new(patterns)
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableMatchCase<'a> {
pattern: ComparablePattern<'a>,
guard: Option<ComparableExpr<'a>>,
body: ComparableStmtSlice<'a>,
}
impl<'a> From<&'a ast::MatchCase> for ComparableMatchCase<'a> {
fn from(match_case: &'a ast::MatchCase) -> Self {
let ast::MatchCase {
runtime_body: _,
pattern,
guard,
body,
range: _,
node_index: _,
} = match_case;
Self {
pattern: pattern.into(),
guard: guard.as_ref().map(Into::into),
body: ComparableSlice::new(body),
}
}
}
impl<'a> From<&'a ast::Decorator> for ComparableExpr<'a> {
fn from(decorator: &'a ast::Decorator) -> Self {
let ast::Decorator {
expression,
range: _,
node_index: _,
} = decorator;
expression.into()
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableText<'a>(&'a str);
impl<'a> From<&'a ast::Identifier> for ComparableText<'a> {
fn from(identifier: &'a ast::Identifier) -> Self {
let ast::Identifier {
id,
range: _,
node_index: _,
} = identifier;
Self(id.as_str())
}
}
struct ComparableNumber<'a>(&'a ast::Number);
impl fmt::Debug for ComparableNumber<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl PartialEq for ComparableNumber<'_> {
fn eq(&self, other: &Self) -> bool {
match self.0 {
ast::Number::Int(left) => matches!(other.0, ast::Number::Int(right) if left == right),
ast::Number::Float(left) => {
matches!(other.0, ast::Number::Float(right) if left.to_bits() == right.to_bits())
}
ast::Number::Complex { real, imag } => match other.0 {
ast::Number::Complex {
real: other_real,
imag: other_imag,
} => {
real.to_bits() == other_real.to_bits() && imag.to_bits() == other_imag.to_bits()
}
_ => false,
},
}
}
}
impl Eq for ComparableNumber<'_> {}
impl Hash for ComparableNumber<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant(self.0).hash(state);
match self.0 {
ast::Number::Int(value) => value.hash(state),
ast::Number::Float(value) => value.to_bits().hash(state),
ast::Number::Complex { real, imag } => (real.to_bits(), imag.to_bits()).hash(state),
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum ComparableConstantValue<'a> {
None,
Boolean(bool),
Str(&'a str),
Bytes(Cow<'a, [u8]>),
Integer(&'a str),
Tuple(Vec<Self>),
Frozenset(Vec<Self>),
Float(u64),
Complex { real: u64, imag: u64 },
Ellipsis,
}
impl<'a> From<&'a ConstantValue> for ComparableConstantValue<'a> {
fn from(value: &'a ConstantValue) -> Self {
match value {
ConstantValue::None => Self::None,
ConstantValue::Boolean(value) => Self::Boolean(*value),
ConstantValue::Str(value) => Self::Str(value),
ConstantValue::Bytes(value) => Self::Bytes(Cow::from(value.as_ref())),
ConstantValue::Integer(value) => Self::Integer(value),
ConstantValue::Tuple(elements) => {
Self::Tuple(elements.iter().map(Into::into).collect())
}
ConstantValue::Frozenset(elements) => {
Self::Frozenset(elements.iter().map(Into::into).collect())
}
ConstantValue::Float(value) => Self::Float(value.to_bits()),
ConstantValue::Complex { real, imag } => Self::Complex {
real: real.to_bits(),
imag: imag.to_bits(),
},
ConstantValue::Ellipsis => Self::Ellipsis,
}
}
}
/// Borrows a sequence and converts each element as it is visited.
struct ComparableSlice<'a, T, C> {
items: &'a [T],
comparable: PhantomData<fn() -> C>,
}
impl<'a, T, C> ComparableSlice<'a, T, C> {
fn new(items: &'a [T]) -> Self {
Self {
items,
comparable: PhantomData,
}
}
fn iter(&self) -> impl Iterator<Item = C>
where
C: From<&'a T>,
{
self.items.iter().map(C::from)
}
}
impl<'a, T, C: From<&'a T> + fmt::Debug> fmt::Debug for ComparableSlice<'a, T, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<T, C> Default for ComparableSlice<'_, T, C> {
fn default() -> Self {
Self::new(&[])
}
}
impl<'a, T, C: From<&'a T> + PartialEq> PartialEq for ComparableSlice<'a, T, C> {
fn eq(&self, other: &Self) -> bool {
self.items.len() == other.items.len() && self.iter().eq(other.iter())
}
}
impl<'a, T, C: From<&'a T> + Eq> Eq for ComparableSlice<'a, T, C> {}
impl<'a, T, C: From<&'a T> + Hash> Hash for ComparableSlice<'a, T, C> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.items.len().hash(state);
for item in self.iter() {
item.hash(state);
}
}
}
type ComparableStmtSlice<'a> = ComparableSlice<'a, ast::Stmt, ComparableStmt<'a>>;
type ComparablePatternSlice<'a> = ComparableSlice<'a, ast::Pattern, ComparablePattern<'a>>;
type ComparableComprehensionSlice<'a> =
ComparableSlice<'a, ast::Comprehension, ComparableComprehension<'a>>;
type ComparableExprSlice<'a> = ComparableSlice<'a, Expr, ComparableExpr<'a>>;
#[derive(Debug, Default, PartialEq, Eq, Hash)]
struct ComparableArguments<'a> {
args: ComparableExprSlice<'a>,
keywords: ComparableSlice<'a, ast::Keyword, ComparableKeyword<'a>>,
}
impl<'a> From<&'a ast::Arguments> for ComparableArguments<'a> {
fn from(arguments: &'a ast::Arguments) -> Self {
let ast::Arguments {
runtime_args: _,
runtime_bases: _,
args,
keywords,
range: _,
node_index: _,
} = arguments;
Self {
args: ComparableSlice::new(args),
keywords: ComparableSlice::new(keywords),
}
}
}
#[derive(Clone, Copy)]
struct ComparableParameters<'a>(&'a ast::Parameters);
impl fmt::Debug for ComparableParameters<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
ComparableParametersFields::from(self.0).fmt(f)
}
}
impl PartialEq for ComparableParameters<'_> {
fn eq(&self, other: &Self) -> bool {
ComparableParametersFields::from(self.0) == ComparableParametersFields::from(other.0)
}
}
impl Eq for ComparableParameters<'_> {}
impl Hash for ComparableParameters<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
ComparableParametersFields::from(self.0).hash(state);
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableParametersFields<'a> {
posonlyargs: ComparableSlice<'a, ast::ParameterWithDefault, ComparableParameterWithDefault<'a>>,
args: ComparableSlice<'a, ast::ParameterWithDefault, ComparableParameterWithDefault<'a>>,
vararg: Option<ComparableParameter<'a>>,
kwonlyargs: ComparableSlice<'a, ast::ParameterWithDefault, ComparableParameterWithDefault<'a>>,
kwarg: Option<ComparableParameter<'a>>,
}
impl<'a> From<&'a ast::Parameters> for ComparableParametersFields<'a> {
fn from(parameters: &'a ast::Parameters) -> Self {
let ast::Parameters {
runtime_defaults: _,
posonlyargs,
args,
vararg,
kwonlyargs,
kwarg,
range: _,
node_index: _,
} = parameters;
Self {
posonlyargs: ComparableSlice::new(posonlyargs),
args: ComparableSlice::new(args),
vararg: vararg.as_deref().map(Into::into),
kwonlyargs: ComparableSlice::new(kwonlyargs),
kwarg: kwarg.as_deref().map(Into::into),
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableParameter<'a> {
arg: &'a str,
annotation: Option<ComparableExpr<'a>>,
}
impl<'a> From<&'a ast::Parameter> for ComparableParameter<'a> {
fn from(arg: &'a ast::Parameter) -> Self {
let ast::Parameter {
runtime_type_comment: _,
runtime_type_comment_bytes: _,
name,
annotation,
range: _,
node_index: _,
} = arg;
Self {
arg: name.as_str(),
annotation: annotation.as_ref().map(Into::into),
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableParameterWithDefault<'a> {
def: ComparableParameter<'a>,
default: Option<ComparableExpr<'a>>,
}
impl<'a> From<&'a ast::ParameterWithDefault> for ComparableParameterWithDefault<'a> {
fn from(arg: &'a ast::ParameterWithDefault) -> Self {
let ast::ParameterWithDefault {
parameter,
default,
range: _,
node_index: _,
} = arg;
Self {
def: parameter.into(),
default: default.as_ref().map(Into::into),
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ComparableKeyword<'a> {
arg: Option<&'a str>,
value: ComparableExpr<'a>,
}
impl<'a> From<&'a ast::Keyword> for ComparableKeyword<'a> {
fn from(keyword: &'a ast::Keyword) -> Self {
let ast::Keyword {
arg,
value,
range: _,
node_index: _,
} = keyword;
Self {
arg: arg.as_ref().map(ast::Identifier::as_str),
value: value.into(),
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableComprehension<'a> {
target: ComparableExpr<'a>,
iter: ComparableExpr<'a>,
ifs: ComparableExprSlice<'a>,
is_async: bool,
}
impl<'a> From<&'a ast::Comprehension> for ComparableComprehension<'a> {
fn from(comprehension: &'a ast::Comprehension) -> Self {
let ast::Comprehension {
runtime_ifs: _,
runtime_is_async: _,
target,
iter,
ifs,
is_async,
range: _,
node_index: _,
} = comprehension;
Self {
target: target.into(),
iter: iter.into(),
ifs: ComparableSlice::new(ifs),
is_async: *is_async,
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableExceptHandler<'a> {
type_: Option<ComparableExpr<'a>>,
name: Option<&'a str>,
body: ComparableStmtSlice<'a>,
}
impl<'a> From<&'a ast::ExceptHandler> for ComparableExceptHandler<'a> {
fn from(except_handler: &'a ast::ExceptHandler) -> Self {
let ast::ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler {
runtime_body: _,
type_,
name,
body,
range: _,
node_index: _,
}) = except_handler;
Self {
type_: type_.as_ref().map(Into::into),
name: name.as_deref(),
body: ComparableSlice::new(body),
}
}
}
/// Compares normalized elements. The enclosing expression distinguishes f-strings from t-strings.
#[derive(Clone, Copy)]
enum ComparableInterpolatedString<'a> {
FString(&'a ast::FStringValue),
TString(&'a ast::TStringValue),
}
impl<'a> ComparableInterpolatedString<'a> {
/// Coalesce adjacent literals so that part boundaries do not affect comparison.
/// For example, `f"{foo!r} one" " and two " f" and three {bar!s}"` decomposes into
///
/// - An f-string part with the interpolation `{foo!r}` and the literal `" one"`.
/// - A plain string literal part containing `" and two "`.
/// - An f-string part with the literal `" and three "` and the interpolation `{bar!s}`.
///
/// All three pieces of literal text form one comparable element between the
/// two interpolations. Equality compares these elements in order, and hashing
/// visits the same sequence.
///
/// [CPython's `string.templatelib.Template`] has one more string than interpolation.
/// Interleaving the two sequences, starting with a string, recovers the reading
/// order. For example, `t"{foo}bar"` has string slots `("", "bar")`, while
/// `t"bar{foo}"` has `("bar", "")`. Here the interpolations already delimit
/// the slots, so we can omit empty t-string text. For f-strings, an explicit
/// empty literal part still participates in comparison, as in `f"{foo}" ""`.
///
/// [CPython's `string.templatelib.Template`]: https://github.com/python/cpython/blob/c91ad5da9d92eac4718e4da8d53689c3cc24535e/Python/codegen.c#L4052-L4103
fn normalized_elements(self) -> impl Iterator<Item = ComparableStringElement<'a>> {
let mut raw = self.raw_elements().peekable();
std::iter::from_fn(move || {
loop {
match raw.next()? {
element @ ComparableStringElement::Interpolation(_) => {
return Some(element);
}
ComparableStringElement::Literal(mut text) => {
// In `f"{x}a" "b"`, after the interpolation, `raw.next()`
// returns `Literal(Cow::Borrowed("a"))` by value. The pattern
// moves the `Cow` into the mutable local variable `text`.
// Its `&str` points into the AST. `text += next` appends "b" by
// replacing the local `Cow` with an owned `String` containing "ab".
// In `f"{x}ab"`, "ab" stays borrowed and compares equal by content.
while let Some(ComparableStringElement::Literal(next)) =
raw.next_if(|next| matches!(next, ComparableStringElement::Literal(_)))
{
text += next;
}
if !text.is_empty() || matches!(self, Self::FString(_)) {
return Some(ComparableStringElement::Literal(text));
}
}
}
}
})
}
/// Flatten the parts in source order. Each element borrows from the AST,
/// and adjacent literal pieces are still separate at this point.
fn raw_elements(self) -> impl Iterator<Item = ComparableStringElement<'a>> {
enum Parts<'a> {
FString(ast::FStringParts<'a>),
TString(std::slice::Iter<'a, ast::TString>),
}
let mut parts = match self {
Self::FString(value) => Parts::FString(value.iter()),
Self::TString(value) => Parts::TString(value.as_slice().iter()),
};
let mut elements = [].iter();
std::iter::from_fn(move || {
loop {
if let Some(element) = elements.next() {
return Some(ComparableStringElement::from(element));
}
elements = match &mut parts {
Parts::FString(parts) => match parts.next()? {
ast::FStringPartRef::FString(ast::FString {
elements,
range: _,
node_index: _,
flags: _,
}) => elements.iter(),
ast::FStringPartRef::Literal(part) => {
return Some(ComparableStringElement::Literal(Cow::Borrowed(
ComparableText::from(part).0,
)));
}
},
Parts::TString(parts) => {
let ast::TString {
elements,
range: _,
node_index: _,
flags: _,
} = parts.next()?;
elements.iter()
}
};
}
})
}
}
impl PartialEq for ComparableInterpolatedString<'_> {
fn eq(&self, other: &Self) -> bool {
std::mem::discriminant(self) == std::mem::discriminant(other)
&& self.normalized_elements().eq(other.normalized_elements())
}
}
impl fmt::Debug for ComparableInterpolatedString<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.normalized_elements()).finish()
}
}
impl Eq for ComparableInterpolatedString<'_> {}
impl Hash for ComparableInterpolatedString<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
for element in self.normalized_elements() {
Some(element).hash(state);
}
Option::<ComparableStringElement>::None.hash(state);
}
}
enum ComparableStringElement<'a> {
Literal(Cow<'a, str>),
Interpolation(&'a ast::InterpolatedElement),
}
impl<'a> From<&'a ast::InterpolatedStringElement> for ComparableStringElement<'a> {
fn from(element: &'a ast::InterpolatedStringElement) -> Self {
match element {
ast::InterpolatedStringElement::Literal(ast::InterpolatedStringLiteralElement {
value,
range: _,
node_index: _,
}) => Self::Literal(Cow::Borrowed(value)),
ast::InterpolatedStringElement::Interpolation(interpolation) => {
Self::Interpolation(interpolation)
}
}
}
}
impl PartialEq for ComparableStringElement<'_> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Literal(left), Self::Literal(right)) => left == right,
(Self::Interpolation(left), Self::Interpolation(right)) => {
interpolation_fields(left) == interpolation_fields(right)
}
(Self::Literal(_), Self::Interpolation(_))
| (Self::Interpolation(_), Self::Literal(_)) => false,
}
}
}
impl fmt::Debug for ComparableStringElement<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Literal(text) => text.fmt(f),
Self::Interpolation(element) => interpolation_fields(element).fmt(f),
}
}
}
impl Eq for ComparableStringElement<'_> {}
impl Hash for ComparableStringElement<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
Self::Literal(text) => text.hash(state),
Self::Interpolation(interpolation) => interpolation_fields(interpolation).hash(state),
}
}
}
/// The full debug text, including leading and trailing whitespace, appears in
/// the runtime value. If `x` is 1, `f"{x =}"` produces `"x =1"` and `f"{x=}"`
/// produces `"x=1"`. Python normalizes CR and CRLF to LF at compile time, so
/// these newline spellings produce identical text.
fn comparable_debug_text(text: &ast::DebugText) -> Cow<'_, str> {
normalize_newlines(text.as_str())
}
fn normalize_newlines(contents: &str) -> Cow<'_, str> {
if contents.contains('\r') {
Cow::Owned(contents.replace("\r\n", "\n").replace('\r', "\n"))
} else {
Cow::Borrowed(contents)
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct InterpolationFields<'a> {
expression: ComparableExpr<'a>,
debug_text: Option<Cow<'a, str>>,
conversion: ast::ConversionFlag,
format_spec:
Option<ComparableSlice<'a, ast::InterpolatedStringElement, ComparableStringElement<'a>>>,
}
fn interpolation_fields(node: &ast::InterpolatedElement) -> InterpolationFields<'_> {
let ast::InterpolatedElement {
runtime_str: _,
runtime_interpolation_format_spec: _,
runtime_formatted_value_format_spec: _,
expression,
debug_text,
conversion,
format_spec,
range: _,
node_index: _,
} = node;
InterpolationFields {
expression: expression.into(),
debug_text: debug_text.as_ref().map(comparable_debug_text),
conversion: *conversion,
format_spec: format_spec.as_deref().map(
|ast::InterpolatedStringFormatSpec {
elements,
range: _,
node_index: _,
}| ComparableSlice::new(elements),
),
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableElifElseClause<'a> {
test: Option<ComparableExpr<'a>>,
body: ComparableStmtSlice<'a>,
}
impl<'a> From<&'a ast::ElifElseClause> for ComparableElifElseClause<'a> {
fn from(elif_else_clause: &'a ast::ElifElseClause) -> Self {
let ast::ElifElseClause {
runtime_body: _,
runtime_orelse: _,
range: _,
node_index: _,
test,
body,
} = elif_else_clause;
Self {
test: test.as_ref().map(Into::into),
body: ComparableSlice::new(body),
}
}
}
/// A structural key for literal expressions that compares each string or bytes part separately.
#[derive(Clone, Copy)]
pub struct ComparableLiteral<'a>(ast::LiteralExpressionRef<'a>);
impl<'a> From<ast::LiteralExpressionRef<'a>> for ComparableLiteral<'a> {
fn from(literal: ast::LiteralExpressionRef<'a>) -> Self {
Self(literal)
}
}
compare_enum!(ComparableLiteral(LiteralExpressionRef) {
StringLiteral => string_literal_parts,
BytesLiteral => bytes_literal_parts,
NumberLiteral => number_literal_fields,
BooleanLiteral => boolean_literal_fields,
NoneLiteral(ast::ExprNoneLiteral { range: _, node_index: _ }),
EllipsisLiteral(ast::ExprEllipsisLiteral { range: _, node_index: _ }),
});
fn string_literal_parts(
node: &ast::ExprStringLiteral,
) -> ComparableSlice<'_, ast::StringLiteral, ComparableText<'_>> {
let ast::ExprStringLiteral {
value,
range: _,
node_index: _,
} = node;
ComparableSlice::new(value.as_slice())
}
fn bytes_literal_parts(
node: &ast::ExprBytesLiteral,
) -> ComparableSlice<'_, ast::BytesLiteral, ComparableBytesLiteral<'_>> {
let ast::ExprBytesLiteral {
value,
range: _,
node_index: _,
} = node;
ComparableSlice::new(value.as_slice())
}
impl<'a> From<&'a ast::StringLiteral> for ComparableText<'a> {
fn from(literal: &'a ast::StringLiteral) -> Self {
let ast::StringLiteral {
value,
range: _,
node_index: _,
flags: _,
} = literal;
Self(value)
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableBytesLiteral<'a>(&'a [u8]);
impl<'a> From<&'a ast::BytesLiteral> for ComparableBytesLiteral<'a> {
fn from(literal: &'a ast::BytesLiteral) -> Self {
let ast::BytesLiteral {
value,
range: _,
node_index: _,
flags: _,
} = literal;
Self(value)
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct ComparableDictItem<'a> {
key: Option<ComparableExpr<'a>>,
value: ComparableExpr<'a>,
}