Skip to main content

ruff_python_ast/
comparable.rs

1//! An equivalent object hierarchy to the `RustPython` AST hierarchy, but with the
2//! ability to compare expressions for equality (via [`Eq`] and [`Hash`]).
3//!
4//! Two [`ComparableExpr`]s are considered equal if the underlying AST nodes have the
5//! same shape, ignoring trivia (e.g., parentheses, comments, and whitespace), the
6//! location in the source code, and other contextual information (e.g., whether they
7//! represent reads or writes, which is typically encoded in the Python AST).
8//!
9//! For example, in `[(a, b) for a, b in c]`, the `(a, b)` and `a, b` expressions are
10//! considered equal, despite the former being parenthesized, and despite the former
11//! being a write ([`ast::ExprContext::Store`]) and the latter being a read
12//! ([`ast::ExprContext::Load`]).
13//!
14//! Similarly, `"a" "b"` and `"ab"` would be considered equal, despite the former being
15//! an implicit concatenation of string literals, as these expressions are considered to
16//! have the same shape in that they evaluate to the same value.
17
18use crate as ast;
19use crate::{ConstantValue, Expr, Number};
20use std::borrow::Cow;
21use std::hash::Hash;
22
23#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
24pub enum ComparableBoolOp {
25    And,
26    Or,
27}
28
29impl From<ast::BoolOp> for ComparableBoolOp {
30    fn from(op: ast::BoolOp) -> Self {
31        match op {
32            ast::BoolOp::And => Self::And,
33            ast::BoolOp::Or => Self::Or,
34        }
35    }
36}
37
38#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
39pub enum ComparableOperator {
40    Add,
41    Sub,
42    Mult,
43    MatMult,
44    Div,
45    Mod,
46    Pow,
47    LShift,
48    RShift,
49    BitOr,
50    BitXor,
51    BitAnd,
52    FloorDiv,
53}
54
55impl From<ast::Operator> for ComparableOperator {
56    fn from(op: ast::Operator) -> Self {
57        match op {
58            ast::Operator::Add => Self::Add,
59            ast::Operator::Sub => Self::Sub,
60            ast::Operator::Mult => Self::Mult,
61            ast::Operator::MatMult => Self::MatMult,
62            ast::Operator::Div => Self::Div,
63            ast::Operator::Mod => Self::Mod,
64            ast::Operator::Pow => Self::Pow,
65            ast::Operator::LShift => Self::LShift,
66            ast::Operator::RShift => Self::RShift,
67            ast::Operator::BitOr => Self::BitOr,
68            ast::Operator::BitXor => Self::BitXor,
69            ast::Operator::BitAnd => Self::BitAnd,
70            ast::Operator::FloorDiv => Self::FloorDiv,
71        }
72    }
73}
74
75#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
76pub enum ComparableUnaryOp {
77    Invert,
78    Not,
79    UAdd,
80    USub,
81}
82
83impl From<ast::UnaryOp> for ComparableUnaryOp {
84    fn from(op: ast::UnaryOp) -> Self {
85        match op {
86            ast::UnaryOp::Invert => Self::Invert,
87            ast::UnaryOp::Not => Self::Not,
88            ast::UnaryOp::UAdd => Self::UAdd,
89            ast::UnaryOp::USub => Self::USub,
90        }
91    }
92}
93
94#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
95pub enum ComparableCmpOp {
96    Eq,
97    NotEq,
98    Lt,
99    LtE,
100    Gt,
101    GtE,
102    Is,
103    IsNot,
104    In,
105    NotIn,
106}
107
108impl From<ast::CmpOp> for ComparableCmpOp {
109    fn from(op: ast::CmpOp) -> Self {
110        match op {
111            ast::CmpOp::Eq => Self::Eq,
112            ast::CmpOp::NotEq => Self::NotEq,
113            ast::CmpOp::Lt => Self::Lt,
114            ast::CmpOp::LtE => Self::LtE,
115            ast::CmpOp::Gt => Self::Gt,
116            ast::CmpOp::GtE => Self::GtE,
117            ast::CmpOp::Is => Self::Is,
118            ast::CmpOp::IsNot => Self::IsNot,
119            ast::CmpOp::In => Self::In,
120            ast::CmpOp::NotIn => Self::NotIn,
121        }
122    }
123}
124
125#[derive(Debug, PartialEq, Eq, Hash)]
126pub struct ComparableAlias<'a> {
127    name: &'a str,
128    asname: Option<&'a str>,
129}
130
131impl<'a> From<&'a ast::Alias> for ComparableAlias<'a> {
132    fn from(alias: &'a ast::Alias) -> Self {
133        Self {
134            name: alias.name.as_str(),
135            asname: alias.asname.as_deref(),
136        }
137    }
138}
139
140#[derive(Debug, PartialEq, Eq, Hash)]
141pub struct ComparableWithItem<'a> {
142    context_expr: ComparableExpr<'a>,
143    optional_vars: Option<ComparableExpr<'a>>,
144}
145
146impl<'a> From<&'a ast::WithItem> for ComparableWithItem<'a> {
147    fn from(with_item: &'a ast::WithItem) -> Self {
148        Self {
149            context_expr: (&with_item.context_expr).into(),
150            optional_vars: with_item.optional_vars.as_ref().map(Into::into),
151        }
152    }
153}
154
155#[derive(Debug, PartialEq, Eq, Hash)]
156pub struct ComparablePatternArguments<'a> {
157    patterns: Vec<ComparablePattern<'a>>,
158    keywords: Vec<ComparablePatternKeyword<'a>>,
159}
160
161impl<'a> From<&'a ast::PatternArguments> for ComparablePatternArguments<'a> {
162    fn from(parameters: &'a ast::PatternArguments) -> Self {
163        Self {
164            patterns: parameters.patterns.iter().map(Into::into).collect(),
165            keywords: parameters.keywords.iter().map(Into::into).collect(),
166        }
167    }
168}
169
170#[derive(Debug, PartialEq, Eq, Hash)]
171pub struct ComparablePatternKeyword<'a> {
172    attr: &'a str,
173    pattern: ComparablePattern<'a>,
174}
175
176impl<'a> From<&'a ast::PatternKeyword> for ComparablePatternKeyword<'a> {
177    fn from(keyword: &'a ast::PatternKeyword) -> Self {
178        Self {
179            attr: keyword.attr.as_str(),
180            pattern: (&keyword.pattern).into(),
181        }
182    }
183}
184
185#[derive(Debug, PartialEq, Eq, Hash)]
186pub struct PatternMatchValue<'a> {
187    value: ComparableExpr<'a>,
188}
189
190#[derive(Debug, PartialEq, Eq, Hash)]
191pub struct PatternMatchSingleton {
192    value: ComparableSingleton,
193}
194
195#[derive(Debug, PartialEq, Eq, Hash)]
196pub struct PatternMatchSequence<'a> {
197    patterns: Vec<ComparablePattern<'a>>,
198}
199
200#[derive(Debug, PartialEq, Eq, Hash)]
201pub struct PatternMatchMapping<'a> {
202    keys: Vec<ComparableExpr<'a>>,
203    patterns: Vec<ComparablePattern<'a>>,
204    rest: Option<&'a str>,
205}
206
207#[derive(Debug, PartialEq, Eq, Hash)]
208pub struct PatternMatchClass<'a> {
209    cls: ComparableExpr<'a>,
210    arguments: ComparablePatternArguments<'a>,
211}
212
213#[derive(Debug, PartialEq, Eq, Hash)]
214pub struct PatternMatchStar<'a> {
215    name: Option<&'a str>,
216}
217
218#[derive(Debug, PartialEq, Eq, Hash)]
219pub struct PatternMatchAs<'a> {
220    pattern: Option<Box<ComparablePattern<'a>>>,
221    name: Option<&'a str>,
222}
223
224#[derive(Debug, PartialEq, Eq, Hash)]
225pub struct PatternMatchOr<'a> {
226    patterns: Vec<ComparablePattern<'a>>,
227}
228
229#[derive(Debug, PartialEq, Eq, Hash)]
230pub enum ComparablePattern<'a> {
231    MatchValue(PatternMatchValue<'a>),
232    MatchSingleton(PatternMatchSingleton),
233    MatchSequence(PatternMatchSequence<'a>),
234    MatchMapping(PatternMatchMapping<'a>),
235    MatchClass(PatternMatchClass<'a>),
236    MatchStar(PatternMatchStar<'a>),
237    MatchAs(PatternMatchAs<'a>),
238    MatchOr(PatternMatchOr<'a>),
239}
240
241impl<'a> From<&'a ast::Pattern> for ComparablePattern<'a> {
242    fn from(pattern: &'a ast::Pattern) -> Self {
243        match pattern {
244            ast::Pattern::MatchValue(ast::PatternMatchValue { value, .. }) => {
245                Self::MatchValue(PatternMatchValue {
246                    value: value.into(),
247                })
248            }
249            ast::Pattern::MatchSingleton(ast::PatternMatchSingleton { value, .. }) => {
250                Self::MatchSingleton(PatternMatchSingleton {
251                    value: value.into(),
252                })
253            }
254            ast::Pattern::MatchSequence(ast::PatternMatchSequence { patterns, .. }) => {
255                Self::MatchSequence(PatternMatchSequence {
256                    patterns: patterns.iter().map(Into::into).collect(),
257                })
258            }
259            ast::Pattern::MatchMapping(ast::PatternMatchMapping {
260                keys,
261                patterns,
262                rest,
263                ..
264            }) => Self::MatchMapping(PatternMatchMapping {
265                keys: keys.iter().map(Into::into).collect(),
266                patterns: patterns.iter().map(Into::into).collect(),
267                rest: rest.as_deref(),
268            }),
269            ast::Pattern::MatchClass(ast::PatternMatchClass { cls, arguments, .. }) => {
270                Self::MatchClass(PatternMatchClass {
271                    cls: cls.into(),
272                    arguments: arguments.into(),
273                })
274            }
275            ast::Pattern::MatchStar(ast::PatternMatchStar { name, .. }) => {
276                Self::MatchStar(PatternMatchStar {
277                    name: name.as_deref(),
278                })
279            }
280            ast::Pattern::MatchAs(ast::PatternMatchAs { pattern, name, .. }) => {
281                Self::MatchAs(PatternMatchAs {
282                    pattern: pattern.as_ref().map(Into::into),
283                    name: name.as_deref(),
284                })
285            }
286            ast::Pattern::MatchOr(ast::PatternMatchOr { patterns, .. }) => {
287                Self::MatchOr(PatternMatchOr {
288                    patterns: patterns.iter().map(Into::into).collect(),
289                })
290            }
291        }
292    }
293}
294
295impl<'a> From<&'a Box<ast::Pattern>> for Box<ComparablePattern<'a>> {
296    fn from(pattern: &'a Box<ast::Pattern>) -> Self {
297        Box::new((pattern.as_ref()).into())
298    }
299}
300
301#[derive(Debug, PartialEq, Eq, Hash)]
302pub struct ComparableMatchCase<'a> {
303    pattern: ComparablePattern<'a>,
304    guard: Option<ComparableExpr<'a>>,
305    body: Vec<ComparableStmt<'a>>,
306}
307
308impl<'a> From<&'a ast::MatchCase> for ComparableMatchCase<'a> {
309    fn from(match_case: &'a ast::MatchCase) -> Self {
310        Self {
311            pattern: (&match_case.pattern).into(),
312            guard: match_case.guard.as_ref().map(Into::into),
313            body: match_case.body.iter().map(Into::into).collect(),
314        }
315    }
316}
317
318#[derive(Debug, PartialEq, Eq, Hash)]
319pub struct ComparableDecorator<'a> {
320    expression: ComparableExpr<'a>,
321}
322
323impl<'a> From<&'a ast::Decorator> for ComparableDecorator<'a> {
324    fn from(decorator: &'a ast::Decorator) -> Self {
325        Self {
326            expression: (&decorator.expression).into(),
327        }
328    }
329}
330
331#[derive(Debug, PartialEq, Eq, Hash)]
332pub enum ComparableSingleton {
333    None,
334    True,
335    False,
336}
337
338impl From<&ast::Singleton> for ComparableSingleton {
339    fn from(singleton: &ast::Singleton) -> Self {
340        match singleton {
341            ast::Singleton::None => Self::None,
342            ast::Singleton::True => Self::True,
343            ast::Singleton::False => Self::False,
344        }
345    }
346}
347
348#[derive(Debug, PartialEq, Eq, Hash)]
349pub enum ComparableNumber<'a> {
350    Int(&'a ast::Int),
351    Float(u64),
352    Complex { real: u64, imag: u64 },
353}
354
355impl<'a> From<&'a ast::Number> for ComparableNumber<'a> {
356    fn from(number: &'a ast::Number) -> Self {
357        match number {
358            ast::Number::Int(value) => Self::Int(value),
359            ast::Number::Float(value) => Self::Float(value.to_bits()),
360            ast::Number::Complex { real, imag } => Self::Complex {
361                real: real.to_bits(),
362                imag: imag.to_bits(),
363            },
364        }
365    }
366}
367
368#[derive(Debug, PartialEq, Eq, Hash)]
369pub enum ComparableConstantValue<'a> {
370    None,
371    Boolean(bool),
372    Str(&'a str),
373    Bytes(Cow<'a, [u8]>),
374    Integer(&'a str),
375    Tuple(Vec<Self>),
376    Frozenset(Vec<Self>),
377    Float(u64),
378    Complex { real: u64, imag: u64 },
379    Ellipsis,
380}
381
382impl<'a> From<&'a ConstantValue> for ComparableConstantValue<'a> {
383    fn from(value: &'a ConstantValue) -> Self {
384        match value {
385            ConstantValue::None => Self::None,
386            ConstantValue::Boolean(value) => Self::Boolean(*value),
387            ConstantValue::Str(value) => Self::Str(value),
388            ConstantValue::Bytes(value) => Self::Bytes(Cow::from(value.as_ref())),
389            ConstantValue::Integer(value) => Self::Integer(value),
390            ConstantValue::Tuple(elements) => {
391                Self::Tuple(elements.iter().map(Into::into).collect())
392            }
393            ConstantValue::Frozenset(elements) => {
394                Self::Frozenset(elements.iter().map(Into::into).collect())
395            }
396            ConstantValue::Float(value) => Self::Float(value.to_bits()),
397            ConstantValue::Complex { real, imag } => Self::Complex {
398                real: real.to_bits(),
399                imag: imag.to_bits(),
400            },
401            ConstantValue::Ellipsis => Self::Ellipsis,
402        }
403    }
404}
405
406#[derive(Debug, Default, PartialEq, Eq, Hash)]
407pub struct ComparableArguments<'a> {
408    args: Vec<ComparableExpr<'a>>,
409    keywords: Vec<ComparableKeyword<'a>>,
410}
411
412impl<'a> From<&'a ast::Arguments> for ComparableArguments<'a> {
413    fn from(arguments: &'a ast::Arguments) -> Self {
414        Self {
415            args: arguments.args.iter().map(Into::into).collect(),
416            keywords: arguments.keywords.iter().map(Into::into).collect(),
417        }
418    }
419}
420
421impl<'a> From<&'a Box<ast::Arguments>> for ComparableArguments<'a> {
422    fn from(arguments: &'a Box<ast::Arguments>) -> Self {
423        (arguments.as_ref()).into()
424    }
425}
426
427#[derive(Debug, PartialEq, Eq, Hash)]
428pub struct ComparableParameters<'a> {
429    posonlyargs: Vec<ComparableParameterWithDefault<'a>>,
430    args: Vec<ComparableParameterWithDefault<'a>>,
431    vararg: Option<ComparableParameter<'a>>,
432    kwonlyargs: Vec<ComparableParameterWithDefault<'a>>,
433    kwarg: Option<ComparableParameter<'a>>,
434}
435
436impl<'a> From<&'a ast::Parameters> for ComparableParameters<'a> {
437    fn from(parameters: &'a ast::Parameters) -> Self {
438        Self {
439            posonlyargs: parameters.posonlyargs.iter().map(Into::into).collect(),
440            args: parameters.args.iter().map(Into::into).collect(),
441            vararg: parameters.vararg.as_ref().map(Into::into),
442            kwonlyargs: parameters.kwonlyargs.iter().map(Into::into).collect(),
443            kwarg: parameters.kwarg.as_ref().map(Into::into),
444        }
445    }
446}
447
448impl<'a> From<&'a Box<ast::Parameters>> for ComparableParameters<'a> {
449    fn from(parameters: &'a Box<ast::Parameters>) -> Self {
450        (parameters.as_ref()).into()
451    }
452}
453
454impl<'a> From<&'a Box<ast::Parameter>> for ComparableParameter<'a> {
455    fn from(arg: &'a Box<ast::Parameter>) -> Self {
456        (arg.as_ref()).into()
457    }
458}
459
460#[derive(Debug, PartialEq, Eq, Hash)]
461pub struct ComparableParameter<'a> {
462    arg: &'a str,
463    annotation: Option<Box<ComparableExpr<'a>>>,
464}
465
466impl<'a> From<&'a ast::Parameter> for ComparableParameter<'a> {
467    fn from(arg: &'a ast::Parameter) -> Self {
468        Self {
469            arg: arg.name.as_str(),
470            annotation: arg.annotation.as_ref().map(Into::into),
471        }
472    }
473}
474
475#[derive(Debug, PartialEq, Eq, Hash)]
476pub struct ComparableParameterWithDefault<'a> {
477    def: ComparableParameter<'a>,
478    default: Option<ComparableExpr<'a>>,
479}
480
481impl<'a> From<&'a ast::ParameterWithDefault> for ComparableParameterWithDefault<'a> {
482    fn from(arg: &'a ast::ParameterWithDefault) -> Self {
483        Self {
484            def: (&arg.parameter).into(),
485            default: arg.default.as_ref().map(Into::into),
486        }
487    }
488}
489
490#[derive(Debug, PartialEq, Eq, Hash)]
491pub struct ComparableKeyword<'a> {
492    arg: Option<&'a str>,
493    value: ComparableExpr<'a>,
494}
495
496impl<'a> From<&'a ast::Keyword> for ComparableKeyword<'a> {
497    fn from(keyword: &'a ast::Keyword) -> Self {
498        Self {
499            arg: keyword.arg.as_ref().map(ast::Identifier::as_str),
500            value: (&keyword.value).into(),
501        }
502    }
503}
504
505#[derive(Debug, PartialEq, Eq, Hash)]
506pub struct ComparableComprehension<'a> {
507    target: ComparableExpr<'a>,
508    iter: ComparableExpr<'a>,
509    ifs: Vec<ComparableExpr<'a>>,
510    is_async: bool,
511}
512
513impl<'a> From<&'a ast::Comprehension> for ComparableComprehension<'a> {
514    fn from(comprehension: &'a ast::Comprehension) -> Self {
515        Self {
516            target: (&comprehension.target).into(),
517            iter: (&comprehension.iter).into(),
518            ifs: comprehension.ifs.iter().map(Into::into).collect(),
519            is_async: comprehension.is_async,
520        }
521    }
522}
523
524#[derive(Debug, PartialEq, Eq, Hash)]
525pub struct ExceptHandlerExceptHandler<'a> {
526    type_: Option<Box<ComparableExpr<'a>>>,
527    name: Option<&'a str>,
528    body: Vec<ComparableStmt<'a>>,
529}
530
531#[derive(Debug, PartialEq, Eq, Hash)]
532pub enum ComparableExceptHandler<'a> {
533    ExceptHandler(ExceptHandlerExceptHandler<'a>),
534}
535
536impl<'a> From<&'a ast::ExceptHandler> for ComparableExceptHandler<'a> {
537    fn from(except_handler: &'a ast::ExceptHandler) -> Self {
538        let ast::ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler {
539            type_,
540            name,
541            body,
542            ..
543        }) = except_handler;
544        Self::ExceptHandler(ExceptHandlerExceptHandler {
545            type_: type_.as_ref().map(Into::into),
546            name: name.as_deref(),
547            body: body.iter().map(Into::into).collect(),
548        })
549    }
550}
551
552#[derive(Debug, PartialEq, Eq, Hash)]
553pub enum ComparableInterpolatedStringElement<'a> {
554    Literal(Cow<'a, str>),
555    InterpolatedElement(InterpolatedElement<'a>),
556}
557
558/// Comparable wrapper for [`ast::DebugText`].
559///
560/// Compares the full debug text (leading + expression source + trailing) rather than only the
561/// expression source, because whitespace is part of the f-string's runtime output: `f"{x =}"`
562/// produces `"x =<value>"` while `f"{x=}"` produces `"x=<value>"`, making them distinct
563/// `Literal` types.
564#[derive(Debug, PartialEq, Eq, Hash)]
565pub struct ComparableDebugText<'a> {
566    text: Cow<'a, str>,
567}
568
569impl<'a> From<&'a ast::DebugText> for ComparableDebugText<'a> {
570    fn from(debug_text: &'a ast::DebugText) -> Self {
571        // Normalizing newlines is safe because Python normalizes `\r\n` and `\r` to `\n`
572        // at compile time, so they produce identical runtime values.
573        Self {
574            text: normalize_newlines(debug_text.as_str()),
575        }
576    }
577}
578
579fn normalize_newlines(contents: &str) -> Cow<'_, str> {
580    if contents.contains('\r') {
581        Cow::Owned(contents.replace("\r\n", "\n").replace('\r', "\n"))
582    } else {
583        Cow::Borrowed(contents)
584    }
585}
586
587#[derive(Debug, PartialEq, Eq, Hash)]
588pub struct InterpolatedElement<'a> {
589    expression: ComparableExpr<'a>,
590    debug_text: Option<ComparableDebugText<'a>>,
591    conversion: ast::ConversionFlag,
592    format_spec: Option<Vec<ComparableInterpolatedStringElement<'a>>>,
593}
594
595impl<'a> From<&'a ast::InterpolatedStringElement> for ComparableInterpolatedStringElement<'a> {
596    fn from(interpolated_string_element: &'a ast::InterpolatedStringElement) -> Self {
597        match interpolated_string_element {
598            ast::InterpolatedStringElement::Literal(ast::InterpolatedStringLiteralElement {
599                value,
600                ..
601            }) => Self::Literal(value.as_ref().into()),
602            ast::InterpolatedStringElement::Interpolation(formatted_value) => {
603                formatted_value.into()
604            }
605        }
606    }
607}
608
609impl<'a> From<&'a ast::InterpolatedElement> for InterpolatedElement<'a> {
610    fn from(interpolated_element: &'a ast::InterpolatedElement) -> Self {
611        let ast::InterpolatedElement {
612            expression,
613            debug_text,
614            conversion,
615            format_spec,
616            ..
617        } = interpolated_element;
618
619        Self {
620            expression: (expression).into(),
621            debug_text: debug_text.as_ref().map(Into::into),
622            conversion: *conversion,
623            format_spec: format_spec
624                .as_ref()
625                .map(|spec| spec.elements.iter().map(Into::into).collect()),
626        }
627    }
628}
629
630impl<'a> From<&'a ast::InterpolatedElement> for ComparableInterpolatedStringElement<'a> {
631    fn from(interpolated_element: &'a ast::InterpolatedElement) -> Self {
632        Self::InterpolatedElement(interpolated_element.into())
633    }
634}
635
636#[derive(Debug, PartialEq, Eq, Hash)]
637pub struct ComparableElifElseClause<'a> {
638    test: Option<ComparableExpr<'a>>,
639    body: Vec<ComparableStmt<'a>>,
640}
641
642impl<'a> From<&'a ast::ElifElseClause> for ComparableElifElseClause<'a> {
643    fn from(elif_else_clause: &'a ast::ElifElseClause) -> Self {
644        let ast::ElifElseClause {
645            range: _,
646            node_index: _,
647            test,
648            body,
649            ..
650        } = elif_else_clause;
651        Self {
652            test: test.as_ref().map(Into::into),
653            body: body.iter().map(Into::into).collect(),
654        }
655    }
656}
657
658#[derive(Debug, PartialEq, Eq, Hash)]
659pub enum ComparableLiteral<'a> {
660    None,
661    Ellipsis,
662    Bool(&'a bool),
663    Str(Vec<ComparableStringLiteral<'a>>),
664    Bytes(Vec<ComparableBytesLiteral<'a>>),
665    Number(ComparableNumber<'a>),
666}
667
668impl<'a> From<ast::LiteralExpressionRef<'a>> for ComparableLiteral<'a> {
669    fn from(literal: ast::LiteralExpressionRef<'a>) -> Self {
670        match literal {
671            ast::LiteralExpressionRef::NoneLiteral(_) => Self::None,
672            ast::LiteralExpressionRef::EllipsisLiteral(_) => Self::Ellipsis,
673            ast::LiteralExpressionRef::BooleanLiteral(ast::ExprBooleanLiteral {
674                value, ..
675            }) => Self::Bool(value),
676            ast::LiteralExpressionRef::StringLiteral(ast::ExprStringLiteral { value, .. }) => {
677                Self::Str(value.iter().map(Into::into).collect())
678            }
679            ast::LiteralExpressionRef::BytesLiteral(ast::ExprBytesLiteral { value, .. }) => {
680                Self::Bytes(value.iter().map(Into::into).collect())
681            }
682            ast::LiteralExpressionRef::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => {
683                Self::Number(value.into())
684            }
685        }
686    }
687}
688
689#[derive(Debug, PartialEq, Eq, Hash)]
690pub struct ComparableFString<'a> {
691    elements: Box<[ComparableInterpolatedStringElement<'a>]>,
692}
693
694impl<'a> From<&'a ast::FStringValue> for ComparableFString<'a> {
695    // The approach below is somewhat complicated, so it may
696    // require some justification.
697    //
698    // Suppose given an f-string of the form
699    // `f"{foo!r} one" " and two " f" and three {bar!s}"`
700    // This decomposes as:
701    // - An `FStringPart::FString`, `f"{foo!r} one"` with elements
702    //      - `FStringElement::Expression` encoding `{foo!r}`
703    //      - `FStringElement::Literal` encoding " one"
704    // - An `FStringPart::Literal` capturing `" and two "`
705    // - An `FStringPart::FString`, `f" and three {bar!s}"` with elements
706    //      - `FStringElement::Literal` encoding " and three "
707    //      - `FStringElement::Expression` encoding `{bar!s}`
708    //
709    // We would like to extract from this a vector of (comparable) f-string
710    // _elements_ which alternate between expression elements and literal
711    // elements. In order to do so, we need to concatenate adjacent string
712    // literals. String literals may be separated for two reasons: either
713    // they appear in adjacent string literal parts, or else a string literal
714    // part is adjacent to a string literal _element_ inside of an f-string part.
715    fn from(value: &'a ast::FStringValue) -> Self {
716        #[derive(Default)]
717        struct Collector<'a> {
718            elements: Vec<ComparableInterpolatedStringElement<'a>>,
719        }
720
721        impl<'a> Collector<'a> {
722            // The logic for concatenating adjacent string literals
723            // occurs here, implicitly: when we encounter a sequence
724            // of string literals, the first gets pushed to the
725            // `elements` vector, while subsequent strings
726            // are concatenated onto this top string.
727            fn push_literal(&mut self, literal: &'a str) {
728                if let Some(ComparableInterpolatedStringElement::Literal(existing_literal)) =
729                    self.elements.last_mut()
730                {
731                    existing_literal.to_mut().push_str(literal);
732                } else {
733                    self.elements
734                        .push(ComparableInterpolatedStringElement::Literal(literal.into()));
735                }
736            }
737
738            fn push_expression(&mut self, expression: &'a ast::InterpolatedElement) {
739                self.elements.push(expression.into());
740            }
741        }
742
743        let mut collector = Collector::default();
744
745        for part in value {
746            match part {
747                ast::FStringPartRef::Literal(string_literal) => {
748                    collector.push_literal(&string_literal.value);
749                }
750                ast::FStringPartRef::FString(fstring) => {
751                    for element in &fstring.elements {
752                        match element {
753                            ast::InterpolatedStringElement::Literal(literal) => {
754                                collector.push_literal(&literal.value);
755                            }
756                            ast::InterpolatedStringElement::Interpolation(expression) => {
757                                collector.push_expression(expression);
758                            }
759                        }
760                    }
761                }
762            }
763        }
764
765        Self {
766            elements: collector.elements.into_boxed_slice(),
767        }
768    }
769}
770
771#[derive(Debug, PartialEq, Eq, Hash)]
772pub struct ComparableTString<'a> {
773    strings: Box<[ComparableInterpolatedStringElement<'a>]>,
774    interpolations: Box<[InterpolatedElement<'a>]>,
775}
776
777impl<'a> From<&'a ast::TStringValue> for ComparableTString<'a> {
778    // We model a [`ComparableTString`] on the actual
779    // [CPython implementation] of a `string.templatelib.Template` object.
780    //
781    // As in CPython, we must be careful to ensure that the length
782    // of `strings` is always one more than the length of `interpolations` -
783    // that way we can recover the original reading order by interleaving
784    // starting with `strings`. This is how we can tell the
785    // difference between, e.g. `t"{foo}bar"` and `t"bar{foo}"`.
786    //
787    // - [CPython implementation](https://github.com/python/cpython/blob/c91ad5da9d92eac4718e4da8d53689c3cc24535e/Python/codegen.c#L4052-L4103)
788    fn from(value: &'a ast::TStringValue) -> Self {
789        struct Collector<'a> {
790            strings: Vec<ComparableInterpolatedStringElement<'a>>,
791            interpolations: Vec<InterpolatedElement<'a>>,
792        }
793
794        impl Default for Collector<'_> {
795            fn default() -> Self {
796                Self {
797                    strings: vec![ComparableInterpolatedStringElement::Literal("".into())],
798                    interpolations: vec![],
799                }
800            }
801        }
802
803        impl<'a> Collector<'a> {
804            // The logic for concatenating adjacent string literals
805            // occurs here, implicitly: when we encounter a sequence
806            // of string literals, the first gets pushed to the
807            // `strings` vector, while subsequent strings
808            // are concatenated onto this top string.
809            fn push_literal(&mut self, literal: &'a str) {
810                if let Some(ComparableInterpolatedStringElement::Literal(existing_literal)) =
811                    self.strings.last_mut()
812                {
813                    existing_literal.to_mut().push_str(literal);
814                } else {
815                    self.strings
816                        .push(ComparableInterpolatedStringElement::Literal(literal.into()));
817                }
818            }
819
820            fn start_new_literal(&mut self) {
821                self.strings
822                    .push(ComparableInterpolatedStringElement::Literal("".into()));
823            }
824
825            fn push_tstring_interpolation(&mut self, expression: &'a ast::InterpolatedElement) {
826                self.interpolations.push(expression.into());
827                self.start_new_literal();
828            }
829        }
830
831        let mut collector = Collector::default();
832
833        for element in value.elements() {
834            match element {
835                ast::InterpolatedStringElement::Literal(literal) => {
836                    collector.push_literal(&literal.value);
837                }
838                ast::InterpolatedStringElement::Interpolation(interpolation) => {
839                    collector.push_tstring_interpolation(interpolation);
840                }
841            }
842        }
843
844        Self {
845            strings: collector.strings.into_boxed_slice(),
846            interpolations: collector.interpolations.into_boxed_slice(),
847        }
848    }
849}
850
851#[derive(Debug, PartialEq, Eq, Hash)]
852pub struct ComparableStringLiteral<'a> {
853    value: &'a str,
854}
855
856impl<'a> From<&'a ast::StringLiteral> for ComparableStringLiteral<'a> {
857    fn from(string_literal: &'a ast::StringLiteral) -> Self {
858        Self {
859            value: &string_literal.value,
860        }
861    }
862}
863
864#[derive(Debug, PartialEq, Eq, Hash)]
865pub struct ComparableBytesLiteral<'a> {
866    value: Cow<'a, [u8]>,
867}
868
869impl<'a> From<&'a ast::BytesLiteral> for ComparableBytesLiteral<'a> {
870    fn from(bytes_literal: &'a ast::BytesLiteral) -> Self {
871        Self {
872            value: Cow::Borrowed(&bytes_literal.value),
873        }
874    }
875}
876
877#[derive(Debug, PartialEq, Eq, Hash)]
878pub struct ExprBoolOp<'a> {
879    op: ComparableBoolOp,
880    values: Vec<ComparableExpr<'a>>,
881}
882
883#[derive(Debug, PartialEq, Eq, Hash)]
884pub struct ExprNamed<'a> {
885    target: Box<ComparableExpr<'a>>,
886    value: Box<ComparableExpr<'a>>,
887}
888
889#[derive(Debug, PartialEq, Eq, Hash)]
890pub struct ExprBinOp<'a> {
891    left: Box<ComparableExpr<'a>>,
892    op: ComparableOperator,
893    right: Box<ComparableExpr<'a>>,
894}
895
896#[derive(Debug, PartialEq, Eq, Hash)]
897pub struct ExprUnaryOp<'a> {
898    op: ComparableUnaryOp,
899    operand: Box<ComparableExpr<'a>>,
900}
901
902#[derive(Debug, PartialEq, Eq, Hash)]
903pub struct ExprLambda<'a> {
904    parameters: Option<ComparableParameters<'a>>,
905    body: Box<ComparableExpr<'a>>,
906}
907
908#[derive(Debug, PartialEq, Eq, Hash)]
909pub struct ExprIf<'a> {
910    test: Box<ComparableExpr<'a>>,
911    body: Box<ComparableExpr<'a>>,
912    orelse: Box<ComparableExpr<'a>>,
913}
914
915#[derive(Debug, PartialEq, Eq, Hash)]
916pub struct ComparableDictItem<'a> {
917    key: Option<ComparableExpr<'a>>,
918    value: ComparableExpr<'a>,
919}
920
921impl<'a> From<&'a ast::DictItem> for ComparableDictItem<'a> {
922    fn from(ast::DictItem { key, value }: &'a ast::DictItem) -> Self {
923        Self {
924            key: key.as_ref().map(ComparableExpr::from),
925            value: value.into(),
926        }
927    }
928}
929
930#[derive(Debug, PartialEq, Eq, Hash)]
931pub struct ExprDict<'a> {
932    items: Vec<ComparableDictItem<'a>>,
933}
934
935#[derive(Debug, PartialEq, Eq, Hash)]
936pub struct ExprSet<'a> {
937    elts: Vec<ComparableExpr<'a>>,
938}
939
940#[derive(Debug, PartialEq, Eq, Hash)]
941pub struct ExprListComp<'a> {
942    elt: Box<ComparableExpr<'a>>,
943    generators: Vec<ComparableComprehension<'a>>,
944}
945
946#[derive(Debug, PartialEq, Eq, Hash)]
947pub struct ExprSetComp<'a> {
948    elt: Box<ComparableExpr<'a>>,
949    generators: Vec<ComparableComprehension<'a>>,
950}
951
952#[derive(Debug, PartialEq, Eq, Hash)]
953pub struct ExprDictComp<'a> {
954    key: Option<Box<ComparableExpr<'a>>>,
955    value: Box<ComparableExpr<'a>>,
956    generators: Vec<ComparableComprehension<'a>>,
957}
958
959#[derive(Debug, PartialEq, Eq, Hash)]
960pub struct ExprGenerator<'a> {
961    elt: Box<ComparableExpr<'a>>,
962    generators: Vec<ComparableComprehension<'a>>,
963}
964
965#[derive(Debug, PartialEq, Eq, Hash)]
966pub struct ExprAwait<'a> {
967    value: Box<ComparableExpr<'a>>,
968}
969
970#[derive(Debug, PartialEq, Eq, Hash)]
971pub struct ExprYield<'a> {
972    value: Option<Box<ComparableExpr<'a>>>,
973}
974
975#[derive(Debug, PartialEq, Eq, Hash)]
976pub struct ExprYieldFrom<'a> {
977    value: Box<ComparableExpr<'a>>,
978}
979
980#[derive(Debug, PartialEq, Eq, Hash)]
981pub struct ExprCompare<'a> {
982    ops: Vec<ComparableCmpOp>,
983    operands: Vec<ComparableExpr<'a>>,
984}
985
986#[derive(Debug, PartialEq, Eq, Hash)]
987pub struct ExprCall<'a> {
988    func: Box<ComparableExpr<'a>>,
989    arguments: ComparableArguments<'a>,
990}
991
992#[derive(Debug, PartialEq, Eq, Hash)]
993pub struct ExprInterpolatedElement<'a> {
994    value: Box<ComparableExpr<'a>>,
995    debug_text: Option<ComparableDebugText<'a>>,
996    conversion: ast::ConversionFlag,
997    format_spec: Vec<ComparableInterpolatedStringElement<'a>>,
998}
999
1000#[derive(Debug, PartialEq, Eq, Hash)]
1001pub struct ExprFString<'a> {
1002    value: ComparableFString<'a>,
1003}
1004
1005#[derive(Debug, PartialEq, Eq, Hash)]
1006pub struct ExprTString<'a> {
1007    value: ComparableTString<'a>,
1008}
1009
1010#[derive(Debug, PartialEq, Eq, Hash)]
1011pub struct ExprStringLiteral<'a> {
1012    value: ComparableStringLiteral<'a>,
1013}
1014
1015#[derive(Debug, PartialEq, Eq, Hash)]
1016pub struct ExprBytesLiteral<'a> {
1017    value: ComparableBytesLiteral<'a>,
1018}
1019
1020#[derive(Debug, PartialEq, Eq, Hash)]
1021pub struct ExprNumberLiteral<'a> {
1022    value: ComparableNumber<'a>,
1023}
1024
1025#[derive(Debug, PartialEq, Eq, Hash)]
1026pub struct ExprConstant<'a> {
1027    value: ComparableConstantValue<'a>,
1028}
1029
1030#[derive(Debug, PartialEq, Eq, Hash)]
1031pub struct ExprBoolLiteral {
1032    value: bool,
1033}
1034
1035#[derive(Debug, PartialEq, Eq, Hash)]
1036pub struct ExprAttribute<'a> {
1037    value: Box<ComparableExpr<'a>>,
1038    attr: &'a str,
1039}
1040
1041#[derive(Debug, PartialEq, Eq, Hash)]
1042pub struct ExprSubscript<'a> {
1043    value: Box<ComparableExpr<'a>>,
1044    slice: Box<ComparableExpr<'a>>,
1045}
1046
1047#[derive(Debug, PartialEq, Eq, Hash)]
1048pub struct ExprStarred<'a> {
1049    value: Box<ComparableExpr<'a>>,
1050}
1051
1052#[derive(Debug, PartialEq, Eq, Hash)]
1053pub struct ExprName<'a> {
1054    id: &'a str,
1055}
1056
1057#[derive(Debug, PartialEq, Eq, Hash)]
1058pub struct ExprList<'a> {
1059    elts: Vec<ComparableExpr<'a>>,
1060}
1061
1062#[derive(Debug, PartialEq, Eq, Hash)]
1063pub struct ExprTuple<'a> {
1064    elts: Vec<ComparableExpr<'a>>,
1065}
1066
1067#[derive(Debug, PartialEq, Eq, Hash)]
1068pub struct ExprSlice<'a> {
1069    lower: Option<Box<ComparableExpr<'a>>>,
1070    upper: Option<Box<ComparableExpr<'a>>>,
1071    step: Option<Box<ComparableExpr<'a>>>,
1072}
1073
1074#[derive(Debug, PartialEq, Eq, Hash)]
1075pub struct ExprIpyEscapeCommand<'a> {
1076    kind: ast::IpyEscapeKind,
1077    value: &'a str,
1078}
1079
1080#[derive(Debug, PartialEq, Eq, Hash)]
1081pub enum ComparableExpr<'a> {
1082    BoolOp(ExprBoolOp<'a>),
1083    NamedExpr(ExprNamed<'a>),
1084    BinOp(ExprBinOp<'a>),
1085    UnaryOp(ExprUnaryOp<'a>),
1086    Lambda(ExprLambda<'a>),
1087    IfExp(ExprIf<'a>),
1088    Dict(ExprDict<'a>),
1089    Set(ExprSet<'a>),
1090    ListComp(ExprListComp<'a>),
1091    SetComp(ExprSetComp<'a>),
1092    DictComp(ExprDictComp<'a>),
1093    GeneratorExp(ExprGenerator<'a>),
1094    Await(ExprAwait<'a>),
1095    Yield(ExprYield<'a>),
1096    YieldFrom(ExprYieldFrom<'a>),
1097    Compare(ExprCompare<'a>),
1098    Call(ExprCall<'a>),
1099    FStringExpressionElement(ExprInterpolatedElement<'a>),
1100    FString(ExprFString<'a>),
1101    TStringInterpolationElement(ExprInterpolatedElement<'a>),
1102    TString(ExprTString<'a>),
1103    StringLiteral(ExprStringLiteral<'a>),
1104    BytesLiteral(ExprBytesLiteral<'a>),
1105    NumberLiteral(ExprNumberLiteral<'a>),
1106    Constant(ExprConstant<'a>),
1107    BoolLiteral(ExprBoolLiteral),
1108    NoneLiteral,
1109    EllipsisLiteral,
1110    Attribute(ExprAttribute<'a>),
1111    Subscript(ExprSubscript<'a>),
1112    Starred(ExprStarred<'a>),
1113    Name(ExprName<'a>),
1114    List(ExprList<'a>),
1115    Tuple(ExprTuple<'a>),
1116    Slice(ExprSlice<'a>),
1117    IpyEscapeCommand(ExprIpyEscapeCommand<'a>),
1118}
1119
1120impl<'a> From<&'a Box<ast::Expr>> for Box<ComparableExpr<'a>> {
1121    fn from(expr: &'a Box<ast::Expr>) -> Self {
1122        Box::new((expr.as_ref()).into())
1123    }
1124}
1125
1126impl<'a> From<&'a Box<ast::Expr>> for ComparableExpr<'a> {
1127    fn from(expr: &'a Box<ast::Expr>) -> Self {
1128        (expr.as_ref()).into()
1129    }
1130}
1131
1132impl<'a> From<&'a ast::Expr> for ComparableExpr<'a> {
1133    fn from(expr: &'a ast::Expr) -> Self {
1134        match expr {
1135            ast::Expr::BoolOp(ast::ExprBoolOp { op, values, .. }) => Self::BoolOp(ExprBoolOp {
1136                op: (*op).into(),
1137                values: values.iter().map(Into::into).collect(),
1138            }),
1139            ast::Expr::Named(ast::ExprNamed { target, value, .. }) => Self::NamedExpr(ExprNamed {
1140                target: target.into(),
1141                value: value.into(),
1142            }),
1143            ast::Expr::BinOp(ast::ExprBinOp {
1144                left, op, right, ..
1145            }) => Self::BinOp(ExprBinOp {
1146                left: left.into(),
1147                op: (*op).into(),
1148                right: right.into(),
1149            }),
1150            ast::Expr::UnaryOp(ast::ExprUnaryOp { op, operand, .. }) => {
1151                Self::UnaryOp(ExprUnaryOp {
1152                    op: (*op).into(),
1153                    operand: operand.into(),
1154                })
1155            }
1156            ast::Expr::Lambda(ast::ExprLambda {
1157                parameters, body, ..
1158            }) => Self::Lambda(ExprLambda {
1159                parameters: parameters.as_ref().map(Into::into),
1160                body: body.into(),
1161            }),
1162            ast::Expr::If(ast::ExprIf {
1163                test, body, orelse, ..
1164            }) => Self::IfExp(ExprIf {
1165                test: test.into(),
1166                body: body.into(),
1167                orelse: orelse.into(),
1168            }),
1169            ast::Expr::Dict(ast::ExprDict { items, .. }) => Self::Dict(ExprDict {
1170                items: items.iter().map(ComparableDictItem::from).collect(),
1171            }),
1172            ast::Expr::Set(ast::ExprSet { elts, .. }) => Self::Set(ExprSet {
1173                elts: elts.iter().map(Into::into).collect(),
1174            }),
1175            ast::Expr::ListComp(ast::ExprListComp {
1176                elt, generators, ..
1177            }) => Self::ListComp(ExprListComp {
1178                elt: elt.into(),
1179                generators: generators.iter().map(Into::into).collect(),
1180            }),
1181            ast::Expr::SetComp(ast::ExprSetComp {
1182                elt, generators, ..
1183            }) => Self::SetComp(ExprSetComp {
1184                elt: elt.into(),
1185                generators: generators.iter().map(Into::into).collect(),
1186            }),
1187            ast::Expr::DictComp(ast::ExprDictComp {
1188                key,
1189                value,
1190                generators,
1191                ..
1192            }) => Self::DictComp(ExprDictComp {
1193                key: key.as_ref().map(Into::into),
1194                value: value.into(),
1195                generators: generators.iter().map(Into::into).collect(),
1196            }),
1197            ast::Expr::Generator(ast::ExprGenerator {
1198                elt, generators, ..
1199            }) => Self::GeneratorExp(ExprGenerator {
1200                elt: elt.into(),
1201                generators: generators.iter().map(Into::into).collect(),
1202            }),
1203            ast::Expr::Await(ast::ExprAwait { value, .. }) => Self::Await(ExprAwait {
1204                value: value.into(),
1205            }),
1206            ast::Expr::Yield(ast::ExprYield { value, .. }) => Self::Yield(ExprYield {
1207                value: value.as_ref().map(Into::into),
1208            }),
1209            ast::Expr::YieldFrom(ast::ExprYieldFrom { value, .. }) => {
1210                Self::YieldFrom(ExprYieldFrom {
1211                    value: value.into(),
1212                })
1213            }
1214            ast::Expr::Compare(ast::ExprCompare {
1215                ops,
1216                operands,
1217                range: _,
1218                node_index: _,
1219                runtime_comparators: _,
1220            }) => Self::Compare(ExprCompare {
1221                ops: ops.iter().copied().map(Into::into).collect(),
1222                operands: operands.iter().map(Into::into).collect(),
1223            }),
1224            ast::Expr::Call(ast::ExprCall {
1225                func, arguments, ..
1226            }) => Self::Call(ExprCall {
1227                func: func.into(),
1228                arguments: arguments.into(),
1229            }),
1230            ast::Expr::FString(ast::ExprFString { value, .. }) => Self::FString(ExprFString {
1231                value: value.into(),
1232            }),
1233            ast::Expr::TString(ast::ExprTString { value, .. }) => Self::TString(ExprTString {
1234                value: value.into(),
1235            }),
1236            ast::Expr::StringLiteral(ast::ExprStringLiteral { value, .. }) => {
1237                Self::StringLiteral(ExprStringLiteral {
1238                    value: ComparableStringLiteral {
1239                        value: value.to_str(),
1240                    },
1241                })
1242            }
1243            ast::Expr::BytesLiteral(ast::ExprBytesLiteral { value, .. }) => {
1244                Self::BytesLiteral(ExprBytesLiteral {
1245                    value: ComparableBytesLiteral {
1246                        value: Cow::from(value),
1247                    },
1248                })
1249            }
1250            ast::Expr::NumberLiteral(ast::ExprNumberLiteral { value, .. }) => {
1251                Self::NumberLiteral(ExprNumberLiteral {
1252                    value: value.into(),
1253                })
1254            }
1255            ast::Expr::Constant(ast::ExprConstant { value, .. }) => Self::Constant(ExprConstant {
1256                value: value.into(),
1257            }),
1258            ast::Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) => {
1259                Self::BoolLiteral(ExprBoolLiteral { value: *value })
1260            }
1261            ast::Expr::NoneLiteral(_) => Self::NoneLiteral,
1262            ast::Expr::EllipsisLiteral(_) => Self::EllipsisLiteral,
1263            ast::Expr::Attribute(ast::ExprAttribute { value, attr, .. }) => {
1264                Self::Attribute(ExprAttribute {
1265                    value: value.into(),
1266                    attr: attr.as_str(),
1267                })
1268            }
1269            ast::Expr::Subscript(ast::ExprSubscript { value, slice, .. }) => {
1270                Self::Subscript(ExprSubscript {
1271                    value: value.into(),
1272                    slice: slice.into(),
1273                })
1274            }
1275            ast::Expr::Starred(ast::ExprStarred { value, .. }) => Self::Starred(ExprStarred {
1276                value: value.into(),
1277            }),
1278            ast::Expr::Name(name) => name.into(),
1279            ast::Expr::List(ast::ExprList { elts, .. }) => Self::List(ExprList {
1280                elts: elts.iter().map(Into::into).collect(),
1281            }),
1282            ast::Expr::Tuple(ast::ExprTuple { elts, .. }) => Self::Tuple(ExprTuple {
1283                elts: elts.iter().map(Into::into).collect(),
1284            }),
1285            ast::Expr::Slice(ast::ExprSlice {
1286                lower, upper, step, ..
1287            }) => Self::Slice(ExprSlice {
1288                lower: lower.as_ref().map(Into::into),
1289                upper: upper.as_ref().map(Into::into),
1290                step: step.as_ref().map(Into::into),
1291            }),
1292            ast::Expr::IpyEscapeCommand(ast::ExprIpyEscapeCommand { kind, value, .. }) => {
1293                Self::IpyEscapeCommand(ExprIpyEscapeCommand { kind: *kind, value })
1294            }
1295        }
1296    }
1297}
1298
1299impl<'a> From<&'a ast::ExprName> for ComparableExpr<'a> {
1300    fn from(expr: &'a ast::ExprName) -> Self {
1301        Self::Name(ExprName {
1302            id: expr.id.as_str(),
1303        })
1304    }
1305}
1306
1307#[derive(Debug, PartialEq, Eq, Hash)]
1308pub struct StmtFunctionDef<'a> {
1309    is_async: bool,
1310    decorator_list: Vec<ComparableDecorator<'a>>,
1311    name: &'a str,
1312    type_params: Option<ComparableTypeParams<'a>>,
1313    parameters: ComparableParameters<'a>,
1314    returns: Option<ComparableExpr<'a>>,
1315    body: Vec<ComparableStmt<'a>>,
1316}
1317
1318#[derive(Debug, PartialEq, Eq, Hash)]
1319pub struct StmtClassDef<'a> {
1320    decorator_list: Vec<ComparableDecorator<'a>>,
1321    name: &'a str,
1322    type_params: Option<ComparableTypeParams<'a>>,
1323    arguments: ComparableArguments<'a>,
1324    body: Vec<ComparableStmt<'a>>,
1325}
1326
1327#[derive(Debug, PartialEq, Eq, Hash)]
1328pub struct StmtReturn<'a> {
1329    value: Option<ComparableExpr<'a>>,
1330}
1331
1332#[derive(Debug, PartialEq, Eq, Hash)]
1333pub struct StmtDelete<'a> {
1334    targets: Vec<ComparableExpr<'a>>,
1335}
1336
1337#[derive(Debug, PartialEq, Eq, Hash)]
1338pub struct StmtTypeAlias<'a> {
1339    pub name: Box<ComparableExpr<'a>>,
1340    pub type_params: Option<ComparableTypeParams<'a>>,
1341    pub value: Box<ComparableExpr<'a>>,
1342}
1343
1344#[derive(Debug, PartialEq, Eq, Hash)]
1345pub struct ComparableTypeParams<'a> {
1346    pub type_params: Vec<ComparableTypeParam<'a>>,
1347}
1348
1349impl<'a> From<&'a ast::TypeParams> for ComparableTypeParams<'a> {
1350    fn from(type_params: &'a ast::TypeParams) -> Self {
1351        Self {
1352            type_params: type_params.iter().map(Into::into).collect(),
1353        }
1354    }
1355}
1356
1357impl<'a> From<&'a Box<ast::TypeParams>> for ComparableTypeParams<'a> {
1358    fn from(type_params: &'a Box<ast::TypeParams>) -> Self {
1359        type_params.as_ref().into()
1360    }
1361}
1362
1363#[derive(Debug, PartialEq, Eq, Hash)]
1364pub enum ComparableTypeParam<'a> {
1365    TypeVar(TypeParamTypeVar<'a>),
1366    ParamSpec(TypeParamParamSpec<'a>),
1367    TypeVarTuple(TypeParamTypeVarTuple<'a>),
1368}
1369
1370impl<'a> From<&'a ast::TypeParam> for ComparableTypeParam<'a> {
1371    fn from(type_param: &'a ast::TypeParam) -> Self {
1372        match type_param {
1373            ast::TypeParam::TypeVar(ast::TypeParamTypeVar {
1374                name,
1375                bound,
1376                default,
1377                ..
1378            }) => Self::TypeVar(TypeParamTypeVar {
1379                name: name.as_str(),
1380                bound: bound.as_ref().map(Into::into),
1381                default: default.as_ref().map(Into::into),
1382            }),
1383            ast::TypeParam::TypeVarTuple(ast::TypeParamTypeVarTuple { name, default, .. }) => {
1384                Self::TypeVarTuple(TypeParamTypeVarTuple {
1385                    name: name.as_str(),
1386                    default: default.as_ref().map(Into::into),
1387                })
1388            }
1389            ast::TypeParam::ParamSpec(ast::TypeParamParamSpec { name, default, .. }) => {
1390                Self::ParamSpec(TypeParamParamSpec {
1391                    name: name.as_str(),
1392                    default: default.as_ref().map(Into::into),
1393                })
1394            }
1395        }
1396    }
1397}
1398
1399#[derive(Debug, PartialEq, Eq, Hash)]
1400pub struct TypeParamTypeVar<'a> {
1401    pub name: &'a str,
1402    pub bound: Option<Box<ComparableExpr<'a>>>,
1403    pub default: Option<Box<ComparableExpr<'a>>>,
1404}
1405
1406#[derive(Debug, PartialEq, Eq, Hash)]
1407pub struct TypeParamParamSpec<'a> {
1408    pub name: &'a str,
1409    pub default: Option<Box<ComparableExpr<'a>>>,
1410}
1411
1412#[derive(Debug, PartialEq, Eq, Hash)]
1413pub struct TypeParamTypeVarTuple<'a> {
1414    pub name: &'a str,
1415    pub default: Option<Box<ComparableExpr<'a>>>,
1416}
1417
1418#[derive(Debug, PartialEq, Eq, Hash)]
1419pub struct StmtAssign<'a> {
1420    targets: Vec<ComparableExpr<'a>>,
1421    value: ComparableExpr<'a>,
1422}
1423
1424#[derive(Debug, PartialEq, Eq, Hash)]
1425pub struct StmtAugAssign<'a> {
1426    target: ComparableExpr<'a>,
1427    op: ComparableOperator,
1428    value: ComparableExpr<'a>,
1429}
1430
1431#[derive(Debug, PartialEq, Eq, Hash)]
1432pub struct StmtAnnAssign<'a> {
1433    target: ComparableExpr<'a>,
1434    annotation: ComparableExpr<'a>,
1435    value: Option<ComparableExpr<'a>>,
1436    simple: bool,
1437}
1438
1439#[derive(Debug, PartialEq, Eq, Hash)]
1440pub struct StmtFor<'a> {
1441    is_async: bool,
1442    target: ComparableExpr<'a>,
1443    iter: ComparableExpr<'a>,
1444    body: Vec<ComparableStmt<'a>>,
1445    orelse: Vec<ComparableStmt<'a>>,
1446}
1447
1448#[derive(Debug, PartialEq, Eq, Hash)]
1449pub struct StmtWhile<'a> {
1450    test: ComparableExpr<'a>,
1451    body: Vec<ComparableStmt<'a>>,
1452    orelse: Vec<ComparableStmt<'a>>,
1453}
1454
1455#[derive(Debug, PartialEq, Eq, Hash)]
1456pub struct StmtIf<'a> {
1457    test: ComparableExpr<'a>,
1458    body: Vec<ComparableStmt<'a>>,
1459    elif_else_clauses: Vec<ComparableElifElseClause<'a>>,
1460}
1461
1462#[derive(Debug, PartialEq, Eq, Hash)]
1463pub struct StmtWith<'a> {
1464    is_async: bool,
1465    items: Vec<ComparableWithItem<'a>>,
1466    body: Vec<ComparableStmt<'a>>,
1467}
1468
1469#[derive(Debug, PartialEq, Eq, Hash)]
1470pub struct StmtMatch<'a> {
1471    subject: ComparableExpr<'a>,
1472    cases: Vec<ComparableMatchCase<'a>>,
1473}
1474
1475#[derive(Debug, PartialEq, Eq, Hash)]
1476pub struct StmtRaise<'a> {
1477    exc: Option<ComparableExpr<'a>>,
1478    cause: Option<ComparableExpr<'a>>,
1479}
1480
1481#[derive(Debug, PartialEq, Eq, Hash)]
1482pub struct StmtTry<'a> {
1483    body: Vec<ComparableStmt<'a>>,
1484    handlers: Vec<ComparableExceptHandler<'a>>,
1485    orelse: Vec<ComparableStmt<'a>>,
1486    finalbody: Vec<ComparableStmt<'a>>,
1487    is_star: bool,
1488}
1489
1490#[derive(Debug, PartialEq, Eq, Hash)]
1491pub struct StmtAssert<'a> {
1492    test: ComparableExpr<'a>,
1493    msg: Option<ComparableExpr<'a>>,
1494}
1495
1496#[derive(Debug, PartialEq, Eq, Hash)]
1497pub struct StmtImport<'a> {
1498    names: Vec<ComparableAlias<'a>>,
1499    is_lazy: bool,
1500}
1501
1502#[derive(Debug, PartialEq, Eq, Hash)]
1503pub struct StmtImportFrom<'a> {
1504    module: Option<&'a str>,
1505    names: Vec<ComparableAlias<'a>>,
1506    level: u32,
1507    is_lazy: bool,
1508}
1509
1510#[derive(Debug, PartialEq, Eq, Hash)]
1511pub struct StmtGlobal<'a> {
1512    names: Vec<&'a str>,
1513}
1514
1515#[derive(Debug, PartialEq, Eq, Hash)]
1516pub struct StmtNonlocal<'a> {
1517    names: Vec<&'a str>,
1518}
1519
1520#[derive(Debug, PartialEq, Eq, Hash)]
1521pub struct StmtExpr<'a> {
1522    value: ComparableExpr<'a>,
1523}
1524
1525#[derive(Debug, PartialEq, Eq, Hash)]
1526pub struct StmtIpyEscapeCommand<'a> {
1527    kind: ast::IpyEscapeKind,
1528    value: &'a str,
1529}
1530
1531#[derive(Debug, PartialEq, Eq, Hash)]
1532pub enum ComparableStmt<'a> {
1533    FunctionDef(StmtFunctionDef<'a>),
1534    ClassDef(StmtClassDef<'a>),
1535    Return(StmtReturn<'a>),
1536    Delete(StmtDelete<'a>),
1537    Assign(StmtAssign<'a>),
1538    AugAssign(StmtAugAssign<'a>),
1539    AnnAssign(StmtAnnAssign<'a>),
1540    For(StmtFor<'a>),
1541    While(StmtWhile<'a>),
1542    If(StmtIf<'a>),
1543    With(StmtWith<'a>),
1544    Match(StmtMatch<'a>),
1545    Raise(StmtRaise<'a>),
1546    Try(StmtTry<'a>),
1547    TypeAlias(StmtTypeAlias<'a>),
1548    Assert(StmtAssert<'a>),
1549    Import(StmtImport<'a>),
1550    ImportFrom(StmtImportFrom<'a>),
1551    Global(StmtGlobal<'a>),
1552    Nonlocal(StmtNonlocal<'a>),
1553    IpyEscapeCommand(StmtIpyEscapeCommand<'a>),
1554    Expr(StmtExpr<'a>),
1555    Pass,
1556    Break,
1557    Continue,
1558}
1559
1560impl<'a> From<&'a ast::Stmt> for ComparableStmt<'a> {
1561    fn from(stmt: &'a ast::Stmt) -> Self {
1562        match stmt {
1563            ast::Stmt::FunctionDef(ast::StmtFunctionDef {
1564                is_async,
1565                name,
1566                parameters,
1567                body,
1568                decorator_list,
1569                returns,
1570                type_params,
1571                ..
1572            }) => Self::FunctionDef(StmtFunctionDef {
1573                is_async: *is_async,
1574                name: name.as_str(),
1575                parameters: parameters.into(),
1576                body: body.iter().map(Into::into).collect(),
1577                decorator_list: decorator_list.iter().map(Into::into).collect(),
1578                returns: returns.as_ref().map(Into::into),
1579                type_params: type_params.as_ref().map(Into::into),
1580            }),
1581            ast::Stmt::ClassDef(ast::StmtClassDef {
1582                name,
1583                arguments,
1584                body,
1585                decorator_list,
1586                type_params,
1587                ..
1588            }) => Self::ClassDef(StmtClassDef {
1589                name: name.as_str(),
1590                arguments: arguments.as_ref().map(Into::into).unwrap_or_default(),
1591                body: body.iter().map(Into::into).collect(),
1592                decorator_list: decorator_list.iter().map(Into::into).collect(),
1593                type_params: type_params.as_ref().map(Into::into),
1594            }),
1595            ast::Stmt::Return(ast::StmtReturn { value, .. }) => Self::Return(StmtReturn {
1596                value: value.as_ref().map(Into::into),
1597            }),
1598            ast::Stmt::Delete(ast::StmtDelete { targets, .. }) => Self::Delete(StmtDelete {
1599                targets: targets.iter().map(Into::into).collect(),
1600            }),
1601            ast::Stmt::TypeAlias(ast::StmtTypeAlias {
1602                range: _,
1603                node_index: _,
1604                name,
1605                type_params,
1606                value,
1607            }) => Self::TypeAlias(StmtTypeAlias {
1608                name: name.into(),
1609                type_params: type_params.as_ref().map(Into::into),
1610                value: value.into(),
1611            }),
1612            ast::Stmt::Assign(ast::StmtAssign { targets, value, .. }) => Self::Assign(StmtAssign {
1613                targets: targets.iter().map(Into::into).collect(),
1614                value: value.into(),
1615            }),
1616            ast::Stmt::AugAssign(ast::StmtAugAssign {
1617                target, op, value, ..
1618            }) => Self::AugAssign(StmtAugAssign {
1619                target: target.into(),
1620                op: (*op).into(),
1621                value: value.into(),
1622            }),
1623            ast::Stmt::AnnAssign(ast::StmtAnnAssign {
1624                target,
1625                annotation,
1626                value,
1627                simple,
1628                ..
1629            }) => Self::AnnAssign(StmtAnnAssign {
1630                target: target.into(),
1631                annotation: annotation.into(),
1632                value: value.as_ref().map(Into::into),
1633                simple: *simple,
1634            }),
1635            ast::Stmt::For(ast::StmtFor {
1636                is_async,
1637                target,
1638                iter,
1639                body,
1640                orelse,
1641                ..
1642            }) => Self::For(StmtFor {
1643                is_async: *is_async,
1644                target: target.into(),
1645                iter: iter.into(),
1646                body: body.iter().map(Into::into).collect(),
1647                orelse: orelse.iter().map(Into::into).collect(),
1648            }),
1649            ast::Stmt::While(ast::StmtWhile {
1650                test, body, orelse, ..
1651            }) => Self::While(StmtWhile {
1652                test: test.into(),
1653                body: body.iter().map(Into::into).collect(),
1654                orelse: orelse.iter().map(Into::into).collect(),
1655            }),
1656            ast::Stmt::If(ast::StmtIf {
1657                test,
1658                body,
1659                elif_else_clauses,
1660                ..
1661            }) => Self::If(StmtIf {
1662                test: test.into(),
1663                body: body.iter().map(Into::into).collect(),
1664                elif_else_clauses: elif_else_clauses.iter().map(Into::into).collect(),
1665            }),
1666            ast::Stmt::With(ast::StmtWith {
1667                is_async,
1668                items,
1669                body,
1670                ..
1671            }) => Self::With(StmtWith {
1672                is_async: *is_async,
1673                items: items.iter().map(Into::into).collect(),
1674                body: body.iter().map(Into::into).collect(),
1675            }),
1676            ast::Stmt::Match(ast::StmtMatch { subject, cases, .. }) => Self::Match(StmtMatch {
1677                subject: subject.into(),
1678                cases: cases.iter().map(Into::into).collect(),
1679            }),
1680            ast::Stmt::Raise(ast::StmtRaise { exc, cause, .. }) => Self::Raise(StmtRaise {
1681                exc: exc.as_ref().map(Into::into),
1682                cause: cause.as_ref().map(Into::into),
1683            }),
1684            ast::Stmt::Try(ast::StmtTry {
1685                body,
1686                handlers,
1687                orelse,
1688                finalbody,
1689                is_star,
1690                ..
1691            }) => Self::Try(StmtTry {
1692                body: body.iter().map(Into::into).collect(),
1693                handlers: handlers.iter().map(Into::into).collect(),
1694                orelse: orelse.iter().map(Into::into).collect(),
1695                finalbody: finalbody.iter().map(Into::into).collect(),
1696                is_star: *is_star,
1697            }),
1698            ast::Stmt::Assert(ast::StmtAssert { test, msg, .. }) => Self::Assert(StmtAssert {
1699                test: test.into(),
1700                msg: msg.as_ref().map(Into::into),
1701            }),
1702            ast::Stmt::Import(ast::StmtImport { names, is_lazy, .. }) => Self::Import(StmtImport {
1703                names: names.iter().map(Into::into).collect(),
1704                is_lazy: *is_lazy,
1705            }),
1706            ast::Stmt::ImportFrom(ast::StmtImportFrom {
1707                module,
1708                names,
1709                level,
1710                is_lazy,
1711                ..
1712            }) => Self::ImportFrom(StmtImportFrom {
1713                module: module.as_deref(),
1714                names: names.iter().map(Into::into).collect(),
1715                level: *level,
1716                is_lazy: *is_lazy,
1717            }),
1718            ast::Stmt::Global(ast::StmtGlobal { names, .. }) => Self::Global(StmtGlobal {
1719                names: names.iter().map(ast::Identifier::as_str).collect(),
1720            }),
1721            ast::Stmt::Nonlocal(ast::StmtNonlocal { names, .. }) => Self::Nonlocal(StmtNonlocal {
1722                names: names.iter().map(ast::Identifier::as_str).collect(),
1723            }),
1724            ast::Stmt::IpyEscapeCommand(ast::StmtIpyEscapeCommand { kind, value, .. }) => {
1725                Self::IpyEscapeCommand(StmtIpyEscapeCommand { kind: *kind, value })
1726            }
1727            ast::Stmt::Expr(ast::StmtExpr { value, .. }) => Self::Expr(StmtExpr {
1728                value: value.into(),
1729            }),
1730            ast::Stmt::Pass(_) => Self::Pass,
1731            ast::Stmt::Break(_) => Self::Break,
1732            ast::Stmt::Continue(_) => Self::Continue,
1733        }
1734    }
1735}
1736
1737#[derive(Debug, PartialEq, Eq, Hash)]
1738pub enum ComparableMod<'a> {
1739    Module(ComparableModModule<'a>),
1740    Expression(ComparableModExpression<'a>),
1741}
1742
1743#[derive(Debug, PartialEq, Eq, Hash)]
1744pub struct ComparableModModule<'a> {
1745    body: Vec<ComparableStmt<'a>>,
1746}
1747
1748#[derive(Debug, PartialEq, Eq, Hash)]
1749pub struct ComparableModExpression<'a> {
1750    body: Box<ComparableExpr<'a>>,
1751}
1752
1753impl<'a> From<&'a ast::Mod> for ComparableMod<'a> {
1754    fn from(mod_: &'a ast::Mod) -> Self {
1755        match mod_ {
1756            ast::Mod::Module(module) => Self::Module(module.into()),
1757            ast::Mod::Expression(expr) => Self::Expression(expr.into()),
1758        }
1759    }
1760}
1761
1762impl<'a> From<&'a ast::ModModule> for ComparableModModule<'a> {
1763    fn from(module: &'a ast::ModModule) -> Self {
1764        Self {
1765            body: module.body.iter().map(Into::into).collect(),
1766        }
1767    }
1768}
1769
1770impl<'a> From<&'a ast::ModExpression> for ComparableModExpression<'a> {
1771    fn from(expr: &'a ast::ModExpression) -> Self {
1772        Self {
1773            body: (&expr.body).into(),
1774        }
1775    }
1776}
1777
1778/// Wrapper around [`Expr`] that implements [`Hash`] and [`PartialEq`] according to Python
1779/// semantics:
1780///
1781/// > Values that compare equal (such as 1, 1.0, and True) can be used interchangeably to index the
1782/// > same dictionary entry.
1783///
1784/// For example, considers `True`, `1`, and `1.0` to be equal, as they hash to the same value
1785/// in Python, along with `False`, `0`, and `0.0`.
1786///
1787/// See: <https://docs.python.org/3/library/stdtypes.html#mapping-types-dict>
1788#[derive(Debug, PartialEq, Eq, Hash)]
1789pub struct HashableExpr<'a>(HashableExprKind<'a>);
1790
1791#[derive(Debug, PartialEq, Eq, Hash)]
1792enum HashableExprKind<'a> {
1793    Comparable(ComparableExpr<'a>),
1794    Number(HashableNumber),
1795    NamedExpr {
1796        target: ComparableExpr<'a>,
1797        value: Box<HashableExprKind<'a>>,
1798    },
1799    Tuple(Vec<HashableExprKind<'a>>),
1800}
1801
1802#[derive(Debug, PartialEq, Eq, Hash)]
1803struct HashableNumber {
1804    real: HashableReal,
1805    imag: HashableReal,
1806}
1807
1808impl HashableNumber {
1809    fn real(real: HashableReal) -> Self {
1810        Self {
1811            real,
1812            imag: HashableReal::Integer(0),
1813        }
1814    }
1815
1816    fn complex(real: HashableReal, imag: HashableReal) -> Self {
1817        Self { real, imag }
1818    }
1819
1820    fn negate(mut self) -> Self {
1821        self.real.negate();
1822        self.imag.negate();
1823        self
1824    }
1825
1826    fn into_real(self) -> Option<HashableReal> {
1827        self.imag.is_zero().then_some(self.real)
1828    }
1829}
1830
1831#[derive(Debug, PartialEq, Eq, Hash)]
1832enum HashableReal {
1833    Integer(i128),
1834    Float(u64),
1835}
1836
1837impl HashableReal {
1838    fn from_int(value: &ast::Int) -> Option<Self> {
1839        value.as_u64().map(i128::from).map(Self::Integer)
1840    }
1841
1842    #[expect(
1843        clippy::cast_possible_truncation,
1844        clippy::cast_precision_loss,
1845        clippy::float_cmp,
1846        reason = "the round-trip check guarantees that the float is exactly representable as an integer"
1847    )]
1848    fn from_float(value: f64) -> Self {
1849        if value.is_finite() && value.abs() < U64_EXCLUSIVE_UPPER_BOUND {
1850            let integer = value as i128;
1851            if integer as f64 == value {
1852                return Self::Integer(integer);
1853            }
1854        }
1855        Self::Float(value.to_bits())
1856    }
1857
1858    #[expect(
1859        clippy::cast_precision_loss,
1860        reason = "Python converts real components to floats before complex arithmetic"
1861    )]
1862    fn into_float(self) -> Self {
1863        match self {
1864            Self::Integer(integer) => Self::from_float(integer as f64),
1865            Self::Float(_) => self,
1866        }
1867    }
1868
1869    fn is_zero(&self) -> bool {
1870        matches!(self, Self::Integer(0))
1871    }
1872
1873    fn negate(&mut self) {
1874        match self {
1875            Self::Integer(integer) => *integer = -*integer,
1876            Self::Float(bits) => *bits ^= 1 << 63,
1877        }
1878    }
1879}
1880
1881// `2^64`, the exclusive upper bound for values representable as a `u64`.
1882const U64_EXCLUSIVE_UPPER_BOUND: f64 = 18_446_744_073_709_551_616.0;
1883
1884impl<'a> From<&'a Expr> for HashableExpr<'a> {
1885    fn from(expr: &'a Expr) -> Self {
1886        /// Returns a version of the given expression that can be hashed and compared according to
1887        /// Python  semantics.
1888        fn as_hashable(expr: &Expr) -> HashableExprKind<'_> {
1889            if let Some(constant) = as_hashable_constant(expr) {
1890                return constant;
1891            }
1892
1893            match expr {
1894                Expr::Named(named) => HashableExprKind::NamedExpr {
1895                    target: ComparableExpr::from(&named.target),
1896                    value: Box::new(as_hashable(&named.value)),
1897                },
1898                _ => HashableExprKind::Comparable(ComparableExpr::from(expr)),
1899            }
1900        }
1901
1902        /// Returns a hashable representation if the expression's value is statically known.
1903        fn as_hashable_constant(expr: &Expr) -> Option<HashableExprKind<'_>> {
1904            if let Some(number) = as_number(expr) {
1905                return Some(HashableExprKind::Number(number));
1906            }
1907
1908            let kind = match expr {
1909                Expr::Tuple(tuple) => HashableExprKind::Tuple(
1910                    tuple
1911                        .iter()
1912                        .map(as_hashable_constant)
1913                        .collect::<Option<_>>()?,
1914                ),
1915                _ if expr.is_literal_expr() => {
1916                    HashableExprKind::Comparable(ComparableExpr::from(expr))
1917                }
1918                _ => return None,
1919            };
1920
1921            Some(kind)
1922        }
1923
1924        fn as_number(expr: &Expr) -> Option<HashableNumber> {
1925            match expr {
1926                Expr::BooleanLiteral(boolean) => Some(HashableNumber::real(HashableReal::Integer(
1927                    i128::from(u8::from(boolean.value)),
1928                ))),
1929                Expr::Constant(ast::ExprConstant {
1930                    value: ConstantValue::Boolean(value),
1931                    ..
1932                }) => Some(HashableNumber::real(HashableReal::Integer(i128::from(
1933                    u8::from(*value),
1934                )))),
1935                Expr::NumberLiteral(number) => match &number.value {
1936                    Number::Int(int) => HashableReal::from_int(int).map(HashableNumber::real),
1937                    Number::Float(float) => {
1938                        Some(HashableNumber::real(HashableReal::from_float(*float)))
1939                    }
1940                    Number::Complex { real, imag } => Some(HashableNumber::complex(
1941                        HashableReal::from_float(*real),
1942                        HashableReal::from_float(*imag),
1943                    )),
1944                },
1945                Expr::UnaryOp(ast::ExprUnaryOp { op, operand, .. }) => match op {
1946                    ast::UnaryOp::UAdd => as_number(operand),
1947                    ast::UnaryOp::USub => as_number(operand).map(HashableNumber::negate),
1948                    ast::UnaryOp::Invert | ast::UnaryOp::Not => None,
1949                },
1950                Expr::BinOp(ast::ExprBinOp {
1951                    left,
1952                    op: op @ (ast::Operator::Add | ast::Operator::Sub),
1953                    right,
1954                    ..
1955                }) => {
1956                    let real = as_number(left)?.into_real()?.into_float();
1957                    let Expr::NumberLiteral(ast::ExprNumberLiteral {
1958                        value:
1959                            Number::Complex {
1960                                real: complex_real,
1961                                imag,
1962                            },
1963                        ..
1964                    }) = right.as_ref()
1965                    else {
1966                        return None;
1967                    };
1968                    let complex_real = HashableReal::from_float(*complex_real);
1969                    if !complex_real.is_zero() {
1970                        return None;
1971                    }
1972                    let mut imag = HashableReal::from_float(*imag);
1973                    if op.is_sub() {
1974                        imag.negate();
1975                    }
1976                    Some(HashableNumber::complex(real, imag))
1977                }
1978                _ => None,
1979            }
1980        }
1981
1982        Self(as_hashable(expr))
1983    }
1984}