• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Qiskit / qiskit / 18911928974

29 Oct 2025 02:46PM UTC coverage: 88.196% (-0.002%) from 88.198%
18911928974

Pull #15272

github

web-flow
Merge 56db82370 into a9365ee28
Pull Request #15272: Change the rust structure of expr.Value

39 of 42 new or added lines in 2 files covered. (92.86%)

9 existing lines in 4 files now uncovered.

93683 of 106221 relevant lines covered (88.2%)

1157770.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.88
/crates/circuit/src/classical/expr/expr.rs
1
// This code is part of Qiskit.
2
//
3
// (C) Copyright IBM 2025
4
//
5
// This code is licensed under the Apache License, Version 2.0. You may
6
// obtain a copy of this license in the LICENSE.txt file in the root directory
7
// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
//
9
// Any modifications or derivative works of this code must retain this
10
// copyright notice, and modified files need to carry a notice indicating
11
// that they have been altered from the originals.
12

13
use crate::classical::expr::{Binary, Cast, Index, Stretch, Unary, Value, Var};
14
use crate::classical::types::Type;
15
use pyo3::prelude::*;
16
use pyo3::{IntoPyObjectExt, intern};
17

18
/// A classical expression.
19
///
20
/// Variants that themselves contain [Expr]s are boxed. This is done instead
21
/// of boxing the contained [Expr]s within the specific type to reduce the
22
/// number of boxes we need (e.g. Binary would otherwise contain two boxed
23
/// expressions).
24
#[derive(Clone, Debug, PartialEq)]
25
pub enum Expr {
26
    Unary(Box<Unary>),
27
    Binary(Box<Binary>),
28
    Cast(Box<Cast>),
29
    Value(Value),
30
    Var(Var),
31
    Stretch(Stretch),
32
    Index(Box<Index>),
33
}
34

35
#[derive(Debug, PartialEq)]
36
pub enum ExprRef<'a> {
37
    Unary(&'a Unary),
38
    Binary(&'a Binary),
39
    Cast(&'a Cast),
40
    Value(&'a Value),
41
    Var(&'a Var),
42
    Stretch(&'a Stretch),
43
    Index(&'a Index),
44
}
45

46
#[derive(Debug, PartialEq)]
47
pub enum ExprRefMut<'a> {
48
    Unary(&'a mut Unary),
49
    Binary(&'a mut Binary),
50
    Cast(&'a mut Cast),
51
    Value(&'a mut Value),
52
    Var(&'a mut Var),
53
    Stretch(&'a mut Stretch),
54
    Index(&'a mut Index),
55
}
56

57
#[derive(Clone, Debug, PartialEq)]
58
pub enum IdentifierRef<'a> {
59
    Var(&'a Var),
60
    Stretch(&'a Stretch),
61
}
62

63
impl Expr {
64
    /// Converts from `&Expr` to `ExprRef`.
65
    pub fn as_ref(&self) -> ExprRef<'_> {
21,182✔
66
        match self {
21,182✔
67
            Expr::Unary(u) => ExprRef::Unary(u.as_ref()),
400✔
68
            Expr::Binary(b) => ExprRef::Binary(b.as_ref()),
6,414✔
69
            Expr::Cast(c) => ExprRef::Cast(c.as_ref()),
84✔
70
            Expr::Value(v) => ExprRef::Value(v),
8,303✔
71
            Expr::Var(v) => ExprRef::Var(v),
5,957✔
72
            Expr::Stretch(s) => ExprRef::Stretch(s),
6✔
73
            Expr::Index(i) => ExprRef::Index(i.as_ref()),
18✔
74
        }
75
    }
21,182✔
76

77
    /// Converts from `&mut Expr` to `ExprRefMut`.
78
    pub fn as_mut(&mut self) -> ExprRefMut<'_> {
69✔
79
        match self {
69✔
80
            Expr::Unary(u) => ExprRefMut::Unary(u.as_mut()),
7✔
81
            Expr::Binary(b) => ExprRefMut::Binary(b.as_mut()),
16✔
82
            Expr::Cast(c) => ExprRefMut::Cast(c.as_mut()),
4✔
83
            Expr::Value(v) => ExprRefMut::Value(v),
10✔
84
            Expr::Var(v) => ExprRefMut::Var(v),
30✔
85
            Expr::Stretch(s) => ExprRefMut::Stretch(s),
2✔
86
            Expr::Index(i) => ExprRefMut::Index(i.as_mut()),
×
87
        }
88
    }
69✔
89

90
    /// The const-ness of the expression.
91
    pub fn is_const(&self) -> bool {
5,424✔
92
        match self {
5,424✔
93
            Expr::Unary(u) => u.constant,
38✔
94
            Expr::Binary(b) => b.constant,
866✔
95
            Expr::Cast(c) => c.constant,
104✔
96
            Expr::Value(_) => true,
2,106✔
97
            Expr::Var(_) => false,
2,204✔
98
            Expr::Stretch(_) => true,
100✔
99
            Expr::Index(i) => i.constant,
6✔
100
        }
101
    }
5,424✔
102

103
    /// The expression's [Type].
104
    pub fn ty(&self) -> Type {
×
105
        match self {
×
106
            Expr::Unary(u) => u.ty,
×
107
            Expr::Binary(b) => b.ty,
×
108
            Expr::Cast(c) => c.ty,
×
109
            Expr::Value(v) => match v {
×
110
                Value::Duration(_) => Type::Duration,
×
NEW
111
                Value::Float(_) => Type::Float,
×
NEW
112
                Value::Bool(_) => Type::Bool,
×
NEW
113
                Value::Uint(_, width) => Type::Uint(*width),
×
114
            },
115
            Expr::Var(v) => match v {
×
116
                Var::Standalone { ty, .. } => *ty,
×
117
                Var::Bit { .. } => Type::Bool,
×
118
                Var::Register { ty, .. } => *ty,
×
119
            },
120
            Expr::Stretch(_) => Type::Duration,
×
121
            Expr::Index(i) => i.ty,
×
122
        }
123
    }
×
124

125
    /// Returns an iterator over the identifier nodes in this expression in some
126
    /// deterministic order.
127
    pub fn identifiers(&self) -> impl Iterator<Item = IdentifierRef<'_>> {
1✔
128
        IdentIterator(ExprIterator { stack: vec![self] })
1✔
129
    }
1✔
130

131
    /// Returns an iterator over the [Var] nodes in this expression in some
132
    /// deterministic order.
133
    pub fn vars(&self) -> impl Iterator<Item = &Var> {
7,810✔
134
        VarIterator(ExprIterator { stack: vec![self] })
7,810✔
135
    }
7,810✔
136

137
    /// Returns an iterator over all nodes in this expression in some deterministic
138
    /// order.
139
    pub fn iter(&self) -> impl Iterator<Item = ExprRef<'_>> {
93✔
140
        ExprIterator { stack: vec![self] }
93✔
141
    }
93✔
142

143
    /// Visits all nodes by mutable reference, in a post-order traversal.
144
    pub fn visit_mut<F>(&mut self, mut visitor: F) -> PyResult<()>
26✔
145
    where
26✔
146
        F: FnMut(ExprRefMut) -> PyResult<()>,
26✔
147
    {
148
        self.visit_mut_impl(&mut visitor)
26✔
149
    }
26✔
150

151
    fn visit_mut_impl<F>(&mut self, visitor: &mut F) -> PyResult<()>
69✔
152
    where
69✔
153
        F: FnMut(ExprRefMut) -> PyResult<()>,
69✔
154
    {
155
        match self {
69✔
156
            Expr::Unary(u) => u.operand.visit_mut_impl(visitor)?,
7✔
157
            Expr::Binary(b) => {
16✔
158
                b.left.visit_mut_impl(visitor)?;
16✔
159
                b.right.visit_mut_impl(visitor)?;
16✔
160
            }
161
            Expr::Cast(c) => c.operand.visit_mut_impl(visitor)?,
4✔
162
            Expr::Value(_) => {}
10✔
163
            Expr::Var(_) => {}
30✔
164
            Expr::Stretch(_) => {}
2✔
165
            Expr::Index(i) => {
×
166
                i.target.visit_mut_impl(visitor)?;
×
167
                i.index.visit_mut_impl(visitor)?;
×
168
            }
169
        }
170
        visitor(self.as_mut())
69✔
171
    }
69✔
172

173
    /// Do these two expressions have exactly the same tree structure?
174
    pub fn structurally_equivalent(&self, other: &Expr) -> bool {
45✔
175
        let identity_key = |v: &Var| v.clone();
45✔
176
        self.structurally_equivalent_by_key(identity_key, other, identity_key)
45✔
177
    }
45✔
178

179
    /// Do these two expressions have exactly the same tree structure, up to some key function for
180
    /// [Var] nodes?
181
    ///
182
    /// In other words, are these two expressions the exact same trees, except we compare the
183
    /// [Var] nodes by calling the appropriate `*_var_key` function on them, and comparing
184
    /// that output for equality.  This function does not allow any semantic "equivalences" such as
185
    /// asserting that `a == b` is equivalent to `b == a`; the evaluation order of the operands
186
    /// could, in general, cause such a statement to be false.
187
    pub fn structurally_equivalent_by_key<F1, F2, K>(
46✔
188
        &self,
46✔
189
        mut self_var_key: F1,
46✔
190
        other: &Expr,
46✔
191
        mut other_var_key: F2,
46✔
192
    ) -> bool
46✔
193
    where
46✔
194
        F1: FnMut(&Var) -> K,
46✔
195
        F2: FnMut(&Var) -> K,
46✔
196
        K: PartialEq,
46✔
197
    {
198
        let mut self_nodes = self.iter();
46✔
199
        let mut other_nodes = other.iter();
46✔
200
        loop {
201
            match (self_nodes.next(), other_nodes.next()) {
114✔
202
                (Some(a), Some(b)) => match (a, b) {
103✔
203
                    (ExprRef::Unary(a), ExprRef::Unary(b)) => {
3✔
204
                        if a.op != b.op || a.ty != b.ty || a.constant != b.constant {
3✔
205
                            return false;
×
206
                        }
3✔
207
                    }
208
                    (ExprRef::Binary(a), ExprRef::Binary(b)) => {
43✔
209
                        if a.op != b.op || a.ty != b.ty || a.constant != b.constant {
43✔
210
                            return false;
×
211
                        }
43✔
212
                    }
213
                    (ExprRef::Cast(a), ExprRef::Cast(b)) => {
1✔
214
                        if a.ty != b.ty || a.constant != b.constant {
1✔
215
                            return false;
×
216
                        }
1✔
217
                    }
218
                    (ExprRef::Value(a), ExprRef::Value(b)) => {
9✔
219
                        if a != b {
9✔
220
                            return false;
×
221
                        }
9✔
222
                    }
223
                    (ExprRef::Var(a), ExprRef::Var(b)) => {
11✔
224
                        if a.ty() != b.ty() {
11✔
225
                            return false;
×
226
                        }
11✔
227
                        if self_var_key(a) != other_var_key(b) {
11✔
228
                            return false;
1✔
229
                        }
10✔
230
                    }
231
                    (ExprRef::Stretch(a), ExprRef::Stretch(b)) => {
1✔
232
                        if a.uuid != b.uuid {
1✔
233
                            return false;
×
234
                        }
1✔
235
                    }
236
                    (ExprRef::Index(a), ExprRef::Index(b)) => {
1✔
237
                        if a.ty != b.ty || a.constant != b.constant {
1✔
238
                            return false;
×
239
                        }
1✔
240
                    }
241
                    _ => return false,
34✔
242
                },
243
                (None, None) => return true,
11✔
244
                _ => return false,
×
245
            }
246
        }
247
    }
46✔
248
}
249

250
/// A private iterator over the [Expr] nodes of an expression
251
/// by reference.
252
///
253
/// The first node reference returned is the [Expr] itself.
254
struct ExprIterator<'a> {
255
    stack: Vec<&'a Expr>,
256
}
257

258
impl<'a> Iterator for ExprIterator<'a> {
259
    type Item = ExprRef<'a>;
260

261
    fn next(&mut self) -> Option<Self::Item> {
29,015✔
262
        let expr = self.stack.pop()?;
29,015✔
263
        match expr {
21,182✔
264
            Expr::Unary(u) => {
400✔
265
                self.stack.push(&u.operand);
400✔
266
            }
400✔
267
            Expr::Binary(b) => {
6,414✔
268
                self.stack.push(&b.left);
6,414✔
269
                self.stack.push(&b.right);
6,414✔
270
            }
6,414✔
271
            Expr::Cast(c) => self.stack.push(&c.operand),
84✔
272
            Expr::Value(_) => {}
8,303✔
273
            Expr::Var(_) => {}
5,957✔
274
            Expr::Stretch(_) => {}
6✔
275
            Expr::Index(i) => {
18✔
276
                self.stack.push(&i.index);
18✔
277
                self.stack.push(&i.target);
18✔
278
            }
18✔
279
        }
280
        Some(expr.as_ref())
21,182✔
281
    }
29,015✔
282
}
283

284
/// A private iterator over the [Var] nodes contained within an [Expr].
285
struct VarIterator<'a>(ExprIterator<'a>);
286

287
impl<'a> Iterator for VarIterator<'a> {
288
    type Item = &'a Var;
289

290
    fn next(&mut self) -> Option<Self::Item> {
13,708✔
291
        for expr in self.0.by_ref() {
20,962✔
292
            if let ExprRef::Var(v) = expr {
20,962✔
293
                return Some(v);
5,899✔
294
            }
15,063✔
295
        }
296
        None
7,809✔
297
    }
13,708✔
298
}
299

300
/// A private iterator over the [Var] and [Stretch] nodes contained within an [Expr].
301
struct IdentIterator<'a>(ExprIterator<'a>);
302

303
impl<'a> Iterator for IdentIterator<'a> {
304
    type Item = IdentifierRef<'a>;
305

306
    fn next(&mut self) -> Option<Self::Item> {
4✔
307
        for expr in self.0.by_ref() {
7✔
308
            if let ExprRef::Var(v) = expr {
7✔
309
                return Some(IdentifierRef::Var(v));
1✔
310
            }
6✔
311
            if let ExprRef::Stretch(s) = expr {
6✔
312
                return Some(IdentifierRef::Stretch(s));
2✔
313
            }
4✔
314
        }
315
        None
1✔
316
    }
4✔
317
}
318

319
impl From<Unary> for Expr {
320
    fn from(value: Unary) -> Self {
2✔
321
        Expr::Unary(Box::new(value))
2✔
322
    }
2✔
323
}
324

325
impl From<Box<Unary>> for Expr {
326
    fn from(value: Box<Unary>) -> Self {
×
327
        Expr::Unary(value)
×
328
    }
×
329
}
330

331
impl From<Binary> for Expr {
332
    fn from(value: Binary) -> Self {
11✔
333
        Expr::Binary(Box::new(value))
11✔
334
    }
11✔
335
}
336

337
impl From<Box<Binary>> for Expr {
338
    fn from(value: Box<Binary>) -> Self {
×
339
        Expr::Binary(value)
×
340
    }
×
341
}
342

343
impl From<Cast> for Expr {
344
    fn from(value: Cast) -> Self {
×
345
        Expr::Cast(Box::new(value))
×
346
    }
×
347
}
348

349
impl From<Box<Cast>> for Expr {
350
    fn from(value: Box<Cast>) -> Self {
×
351
        Expr::Cast(value)
×
352
    }
×
353
}
354

355
impl From<Value> for Expr {
356
    fn from(value: Value) -> Self {
4✔
357
        Expr::Value(value)
4✔
358
    }
4✔
359
}
360

361
impl From<Var> for Expr {
362
    fn from(value: Var) -> Self {
6✔
363
        Expr::Var(value)
6✔
364
    }
6✔
365
}
366

367
impl From<Stretch> for Expr {
368
    fn from(value: Stretch) -> Self {
6✔
369
        Expr::Stretch(value)
6✔
370
    }
6✔
371
}
372

373
impl From<Index> for Expr {
374
    fn from(value: Index) -> Self {
×
375
        Expr::Index(Box::new(value))
×
376
    }
×
377
}
378

379
impl From<Box<Index>> for Expr {
380
    fn from(value: Box<Index>) -> Self {
×
381
        Expr::Index(value)
×
382
    }
×
383
}
384

385
/// Root base class of all nodes in the expression tree.  The base case should never be
386
/// instantiated directly.
387
///
388
/// This must not be subclassed by users; subclasses form the internal data of the representation of
389
/// expressions, and it does not make sense to add more outside of Qiskit library code.
390
///
391
/// All subclasses are responsible for setting their ``type`` attribute in their ``__init__``, and
392
/// should not call the parent initializer."""
393
#[pyclass(
×
394
    eq,
×
395
    hash,
×
396
    subclass,
397
    frozen,
398
    name = "Expr",
399
    module = "qiskit._accelerate.circuit.classical.expr"
400
)]
×
401
#[derive(PartialEq, Clone, Copy, Debug, Hash)]
402
pub struct PyExpr(pub ExprKind); // ExprKind is used for fast extraction from Python
403

404
#[pymethods]
405
impl PyExpr {
406
    /// Call the relevant ``visit_*`` method on the given :class:`ExprVisitor`.  The usual entry
407
    /// point for a simple visitor is to construct it, and then call :meth:`accept` on the root
408
    /// object to be visited.  For example::
409
    ///
410
    ///     expr = ...
411
    ///     visitor = MyVisitor()
412
    ///     visitor.accept(expr)
413
    ///
414
    /// Subclasses of :class:`Expr` should override this to call the correct virtual method on the
415
    /// visitor.  This implements double dispatch with the visitor."""
416
    /// return visitor.visit_generic(self)
417
    fn accept<'py>(
×
418
        slf: PyRef<'py, Self>,
×
419
        visitor: &Bound<'py, PyAny>,
×
420
    ) -> PyResult<Bound<'py, PyAny>> {
×
421
        visitor.call_method1(intern!(visitor.py(), "visit_generic"), (slf,))
×
422
    }
×
423
}
424

425
/// The expression's kind, used internally during Python instance extraction to avoid
426
/// `isinstance` checks.
427
#[repr(u8)]
428
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
429
pub enum ExprKind {
430
    Unary,
431
    Binary,
432
    Value,
433
    Var,
434
    Cast,
435
    Stretch,
436
    Index,
437
}
438

439
impl<'py> IntoPyObject<'py> for Expr {
440
    type Target = PyAny;
441
    type Output = Bound<'py, PyAny>;
442
    type Error = PyErr;
443

444
    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
9,204✔
445
        match self {
9,204✔
446
            Expr::Unary(u) => u.into_bound_py_any(py),
148✔
447
            Expr::Binary(b) => b.into_bound_py_any(py),
2,274✔
448
            Expr::Cast(c) => c.into_bound_py_any(py),
48✔
449
            Expr::Value(v) => v.into_bound_py_any(py),
3,634✔
450
            Expr::Var(v) => v.into_bound_py_any(py),
2,950✔
451
            Expr::Stretch(s) => s.into_bound_py_any(py),
130✔
452
            Expr::Index(i) => i.into_bound_py_any(py),
20✔
453
        }
454
    }
9,204✔
455
}
456

457
impl<'a, 'py> FromPyObject<'a, 'py> for Expr {
458
    type Error = PyErr;
459

460
    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
27,434✔
461
        let expr: PyRef<'_, PyExpr> = ob.cast()?.borrow();
27,434✔
462
        match expr.0 {
15,146✔
463
            ExprKind::Unary => Ok(Expr::Unary(Box::new(ob.extract()?))),
420✔
464
            ExprKind::Binary => Ok(Expr::Binary(Box::new(ob.extract()?))),
3,212✔
465
            ExprKind::Value => Ok(Expr::Value(ob.extract()?)),
5,030✔
466
            ExprKind::Var => Ok(Expr::Var(ob.extract()?)),
6,210✔
467
            ExprKind::Cast => Ok(Expr::Cast(Box::new(ob.extract()?))),
154✔
468
            ExprKind::Stretch => Ok(Expr::Stretch(ob.extract()?)),
100✔
469
            ExprKind::Index => Ok(Expr::Index(Box::new(ob.extract()?))),
20✔
470
        }
471
    }
27,434✔
472
}
473

474
#[cfg(test)]
475
mod tests {
476
    use crate::bit::{ClassicalRegister, ShareableClbit};
477
    use crate::classical::expr::{
478
        Binary, BinaryOp, Cast, Expr, ExprRef, ExprRefMut, IdentifierRef, Index, Stretch, Unary,
479
        UnaryOp, Value, Var,
480
    };
481
    use crate::classical::types::Type;
482
    use crate::duration::Duration;
483
    use pyo3::PyResult;
484
    use uuid::Uuid;
485

486
    #[test]
487
    fn test_vars() {
1✔
488
        let expr: Expr = Binary {
1✔
489
            op: BinaryOp::BitAnd,
1✔
490
            left: Unary {
1✔
491
                op: UnaryOp::BitNot,
1✔
492
                operand: Var::Standalone {
1✔
493
                    uuid: Uuid::new_v4().as_u128(),
1✔
494
                    name: "test".to_string(),
1✔
495
                    ty: Type::Bool,
1✔
496
                }
1✔
497
                .into(),
1✔
498
                ty: Type::Bool,
1✔
499
                constant: false,
1✔
500
            }
1✔
501
            .into(),
1✔
502
            right: Var::Bit {
1✔
503
                bit: ShareableClbit::new_anonymous(),
1✔
504
            }
1✔
505
            .into(),
1✔
506
            ty: Type::Bool,
1✔
507
            constant: false,
1✔
508
        }
1✔
509
        .into();
1✔
510

511
        let vars: Vec<&Var> = expr.vars().collect();
1✔
512
        assert!(matches!(
1✔
513
            vars.as_slice(),
1✔
514
            [Var::Bit { .. }, Var::Standalone { .. }]
1✔
515
        ));
516
    }
1✔
517

518
    #[test]
519
    fn test_identifiers() {
1✔
520
        let expr: Expr = Binary {
1✔
521
            op: BinaryOp::Mul,
1✔
522
            left: Binary {
1✔
523
                op: BinaryOp::Add,
1✔
524
                left: Var::Standalone {
1✔
525
                    uuid: Uuid::new_v4().as_u128(),
1✔
526
                    name: "test".to_string(),
1✔
527
                    ty: Type::Duration,
1✔
528
                }
1✔
529
                .into(),
1✔
530
                right: Stretch {
1✔
531
                    uuid: Uuid::new_v4().as_u128(),
1✔
532
                    name: "test".to_string(),
1✔
533
                }
1✔
534
                .into(),
1✔
535
                ty: Type::Duration,
1✔
536
                constant: false,
1✔
537
            }
1✔
538
            .into(),
1✔
539
            right: Binary {
1✔
540
                op: BinaryOp::Div,
1✔
541
                left: Stretch {
1✔
542
                    uuid: Uuid::new_v4().as_u128(),
1✔
543
                    name: "test".to_string(),
1✔
544
                }
1✔
545
                .into(),
1✔
546
                right: Value::Duration(Duration::dt(1000)).into(),
1✔
547
                ty: Type::Float,
1✔
548
                constant: true,
1✔
549
            }
1✔
550
            .into(),
1✔
551
            ty: Type::Bool,
1✔
552
            constant: false,
1✔
553
        }
1✔
554
        .into();
1✔
555

556
        let identifiers: Vec<IdentifierRef> = expr.identifiers().collect();
1✔
557
        assert!(matches!(
1✔
558
            identifiers.as_slice(),
1✔
559
            [
1✔
560
                IdentifierRef::Stretch(Stretch { .. }),
1✔
561
                IdentifierRef::Stretch(Stretch { .. }),
1✔
562
                IdentifierRef::Var(Var::Standalone { .. }),
1✔
563
            ]
1✔
564
        ));
565
    }
1✔
566

567
    #[test]
568
    fn test_iter() {
1✔
569
        let expr: Expr = Binary {
1✔
570
            op: BinaryOp::Mul,
1✔
571
            left: Binary {
1✔
572
                op: BinaryOp::Add,
1✔
573
                left: Var::Standalone {
1✔
574
                    uuid: Uuid::new_v4().as_u128(),
1✔
575
                    name: "test".to_string(),
1✔
576
                    ty: Type::Duration,
1✔
577
                }
1✔
578
                .into(),
1✔
579
                right: Stretch {
1✔
580
                    uuid: Uuid::new_v4().as_u128(),
1✔
581
                    name: "test".to_string(),
1✔
582
                }
1✔
583
                .into(),
1✔
584
                ty: Type::Duration,
1✔
585
                constant: false,
1✔
586
            }
1✔
587
            .into(),
1✔
588
            right: Binary {
1✔
589
                op: BinaryOp::Div,
1✔
590
                left: Stretch {
1✔
591
                    uuid: Uuid::new_v4().as_u128(),
1✔
592
                    name: "test".to_string(),
1✔
593
                }
1✔
594
                .into(),
1✔
595
                right: Value::Duration(Duration::dt(1000)).into(),
1✔
596
                ty: Type::Float,
1✔
597
                constant: true,
1✔
598
            }
1✔
599
            .into(),
1✔
600
            ty: Type::Bool,
1✔
601
            constant: false,
1✔
602
        }
1✔
603
        .into();
1✔
604

605
        let exprs: Vec<ExprRef> = expr.iter().collect();
1✔
606
        assert!(matches!(
1✔
607
            exprs.as_slice(),
1✔
608
            [
1✔
609
                ExprRef::Binary(Binary {
1✔
610
                    op: BinaryOp::Mul,
1✔
611
                    ..
1✔
612
                }),
1✔
613
                ExprRef::Binary(Binary {
1✔
614
                    op: BinaryOp::Div,
1✔
615
                    ..
1✔
616
                }),
1✔
617
                ExprRef::Value(Value::Duration(..)),
1✔
618
                ExprRef::Stretch(Stretch { .. }),
1✔
619
                ExprRef::Binary(Binary {
1✔
620
                    op: BinaryOp::Add,
1✔
621
                    ..
1✔
622
                }),
1✔
623
                ExprRef::Stretch(Stretch { .. }),
1✔
624
                ExprRef::Var(Var::Standalone { .. }),
1✔
625
            ]
1✔
626
        ));
627
    }
1✔
628

629
    #[test]
630
    fn test_visit_mut_ordering() -> PyResult<()> {
1✔
631
        let mut expr: Expr = Binary {
1✔
632
            op: BinaryOp::Mul,
1✔
633
            left: Binary {
1✔
634
                op: BinaryOp::Add,
1✔
635
                left: Var::Standalone {
1✔
636
                    uuid: Uuid::new_v4().as_u128(),
1✔
637
                    name: "test".to_string(),
1✔
638
                    ty: Type::Duration,
1✔
639
                }
1✔
640
                .into(),
1✔
641
                right: Stretch {
1✔
642
                    uuid: Uuid::new_v4().as_u128(),
1✔
643
                    name: "test".to_string(),
1✔
644
                }
1✔
645
                .into(),
1✔
646
                ty: Type::Duration,
1✔
647
                constant: false,
1✔
648
            }
1✔
649
            .into(),
1✔
650
            right: Binary {
1✔
651
                op: BinaryOp::Div,
1✔
652
                left: Stretch {
1✔
653
                    uuid: Uuid::new_v4().as_u128(),
1✔
654
                    name: "test".to_string(),
1✔
655
                }
1✔
656
                .into(),
1✔
657
                right: Value::Duration(Duration::dt(1000)).into(),
1✔
658
                ty: Type::Float,
1✔
659
                constant: true,
1✔
660
            }
1✔
661
            .into(),
1✔
662
            ty: Type::Bool,
1✔
663
            constant: false,
1✔
664
        }
1✔
665
        .into();
1✔
666

667
        // These get *consumed* by every visit, so by the end we expect this
668
        // iterator to be empty. The ordering here is post-order, LRN.
669
        let mut order = [
1✔
670
            |x: &ExprRefMut| matches!(x, ExprRefMut::Var(Var::Standalone { .. })),
1✔
671
            |x: &ExprRefMut| matches!(x, ExprRefMut::Stretch(Stretch { .. })),
1✔
672
            |x: &ExprRefMut| {
1✔
673
                matches!(
×
674
                    x,
1✔
675
                    ExprRefMut::Binary(Binary {
676
                        op: BinaryOp::Add,
677
                        ..
678
                    })
679
                )
680
            },
1✔
681
            |x: &ExprRefMut| matches!(x, ExprRefMut::Stretch(Stretch { .. })),
1✔
682
            |x: &ExprRefMut| matches!(x, ExprRefMut::Value(Value::Duration(..))),
1✔
683
            |x: &ExprRefMut| {
1✔
684
                matches!(
×
685
                    x,
1✔
686
                    ExprRefMut::Binary(Binary {
687
                        op: BinaryOp::Div,
688
                        ..
689
                    })
690
                )
691
            },
1✔
692
            |x: &ExprRefMut| {
1✔
693
                matches!(
×
694
                    x,
1✔
695
                    ExprRefMut::Binary(Binary {
696
                        op: BinaryOp::Mul,
697
                        ..
698
                    })
699
                )
700
            },
1✔
701
        ]
702
        .into_iter();
1✔
703

704
        expr.visit_mut(|x| {
7✔
705
            assert!(order.next().unwrap()(&x));
7✔
706
            Ok(())
7✔
707
        })?;
7✔
708

709
        assert!(order.next().is_none());
1✔
710
        Ok(())
1✔
711
    }
1✔
712

713
    #[test]
714
    fn test_visit_mut() -> PyResult<()> {
1✔
715
        let mut expr: Expr = Binary {
1✔
716
            op: BinaryOp::BitAnd,
1✔
717
            left: Unary {
1✔
718
                op: UnaryOp::BitNot,
1✔
719
                operand: Var::Standalone {
1✔
720
                    uuid: Uuid::new_v4().as_u128(),
1✔
721
                    name: "test".to_string(),
1✔
722
                    ty: Type::Bool,
1✔
723
                }
1✔
724
                .into(),
1✔
725
                ty: Type::Bool,
1✔
726
                constant: false,
1✔
727
            }
1✔
728
            .into(),
1✔
729
            right: Value::Bool(true).into(),
1✔
730
            ty: Type::Bool,
1✔
731
            constant: false,
1✔
732
        }
1✔
733
        .into();
1✔
734

735
        expr.visit_mut(|x| match x {
1✔
736
            ExprRefMut::Var(Var::Standalone { name, .. }) => {
1✔
737
                *name = "updated".to_string();
1✔
738
                Ok(())
1✔
739
            }
740
            _ => Ok(()),
3✔
741
        })?;
4✔
742

743
        let Var::Standalone { name, .. } = expr.vars().next().unwrap() else {
1✔
744
            panic!("wrong var type")
×
745
        };
746
        assert_eq!(name.as_str(), "updated");
1✔
747
        Ok(())
1✔
748
    }
1✔
749

750
    #[test]
751
    fn test_structurally_eq_to_self() -> PyResult<()> {
1✔
752
        let exprs = [
1✔
753
            Expr::Var(Var::Bit {
1✔
754
                bit: ShareableClbit::new_anonymous(),
1✔
755
            }),
1✔
756
            Expr::Var(Var::Register {
1✔
757
                register: ClassicalRegister::new_owning("a", 3),
1✔
758
                ty: Type::Uint(3),
1✔
759
            }),
1✔
760
            Expr::Value(Value::new_small_int(3, 2)),
1✔
761
            Expr::Cast(
1✔
762
                Cast {
1✔
763
                    operand: Expr::Var(Var::Register {
1✔
764
                        register: ClassicalRegister::new_owning("a", 3),
1✔
765
                        ty: Type::Uint(3),
1✔
766
                    }),
1✔
767
                    ty: Type::Bool,
1✔
768
                    constant: false,
1✔
769
                    implicit: false,
1✔
770
                }
1✔
771
                .into(),
1✔
772
            ),
1✔
773
            Expr::Unary(
1✔
774
                Unary {
1✔
775
                    op: UnaryOp::LogicNot,
1✔
776
                    operand: Expr::Var(Var::Bit {
1✔
777
                        bit: ShareableClbit::new_anonymous(),
1✔
778
                    }),
1✔
779
                    ty: Type::Bool,
1✔
780
                    constant: false,
1✔
781
                }
1✔
782
                .into(),
1✔
783
            ),
1✔
784
            Expr::Binary(
1✔
785
                Binary {
1✔
786
                    op: BinaryOp::BitAnd,
1✔
787
                    left: Expr::Value(Value::new_small_int(5, 3)),
1✔
788
                    right: Expr::Var(Var::Register {
1✔
789
                        register: ClassicalRegister::new_owning("a", 3),
1✔
790
                        ty: Type::Uint(3),
1✔
791
                    }),
1✔
792
                    ty: Type::Uint(3),
1✔
793
                    constant: false,
1✔
794
                }
1✔
795
                .into(),
1✔
796
            ),
1✔
797
            Expr::Binary(
1✔
798
                Binary {
1✔
799
                    op: BinaryOp::LogicAnd,
1✔
800
                    left: Expr::Binary(
1✔
801
                        Binary {
1✔
802
                            op: BinaryOp::Less,
1✔
803
                            left: Expr::Value(Value::new_small_int(2, 3)),
1✔
804
                            right: Expr::Var(Var::Register {
1✔
805
                                register: ClassicalRegister::new_owning("a", 3),
1✔
806
                                ty: Type::Uint(3),
1✔
807
                            }),
1✔
808
                            ty: Type::Bool,
1✔
809
                            constant: false,
1✔
810
                        }
1✔
811
                        .into(),
1✔
812
                    ),
1✔
813
                    right: Expr::Var(Var::Bit {
1✔
814
                        bit: ShareableClbit::new_anonymous(),
1✔
815
                    }),
1✔
816
                    ty: Type::Bool,
1✔
817
                    constant: false,
1✔
818
                }
1✔
819
                .into(),
1✔
820
            ),
1✔
821
            Expr::Binary(
1✔
822
                Binary {
1✔
823
                    op: BinaryOp::ShiftLeft,
1✔
824
                    left: Expr::Binary(
1✔
825
                        Binary {
1✔
826
                            op: BinaryOp::ShiftRight,
1✔
827
                            left: Expr::Value(Value::new_small_int(255, 8)),
1✔
828
                            right: Expr::Value(Value::new_small_int(3, 8)),
1✔
829
                            ty: Type::Uint(8),
1✔
830
                            constant: true,
1✔
831
                        }
1✔
832
                        .into(),
1✔
833
                    ),
1✔
834
                    right: Expr::Value(Value::new_small_int(3, 8)),
1✔
835
                    ty: Type::Uint(8),
1✔
836
                    constant: true,
1✔
837
                }
1✔
838
                .into(),
1✔
839
            ),
1✔
840
            Expr::Index(
1✔
841
                Index {
1✔
842
                    target: Expr::Var(Var::Standalone {
1✔
843
                        uuid: Uuid::new_v4().as_u128(),
1✔
844
                        name: "a".to_string(),
1✔
845
                        ty: Type::Uint(8),
1✔
846
                    }),
1✔
847
                    index: Expr::Value(Value::new_small_int(0, 8)),
1✔
848
                    ty: Type::Uint(1),
1✔
849
                    constant: false,
1✔
850
                }
1✔
851
                .into(),
1✔
852
            ),
1✔
853
            Expr::Binary(
1✔
854
                Binary {
1✔
855
                    op: BinaryOp::Greater,
1✔
856
                    left: Expr::Stretch(Stretch {
1✔
857
                        uuid: Uuid::new_v4().as_u128(),
1✔
858
                        name: "a".to_string(),
1✔
859
                    }),
1✔
860
                    right: Expr::Value(Value::Duration(Duration::dt(100))),
1✔
861
                    ty: Type::Bool,
1✔
862
                    constant: false,
1✔
863
                }
1✔
864
                .into(),
1✔
865
            ),
1✔
866
        ];
1✔
867

868
        for expr in exprs.iter() {
10✔
869
            assert!(expr.structurally_equivalent(expr));
10✔
870
        }
871

872
        Ok(())
1✔
873
    }
1✔
874

875
    #[test]
876
    fn test_structurally_eq_does_not_compare_symmetrically() {
1✔
877
        let all_ops = [
1✔
878
            BinaryOp::BitAnd,
1✔
879
            BinaryOp::BitOr,
1✔
880
            BinaryOp::BitXor,
1✔
881
            BinaryOp::LogicAnd,
1✔
882
            BinaryOp::LogicOr,
1✔
883
            BinaryOp::Equal,
1✔
884
            BinaryOp::NotEqual,
1✔
885
            BinaryOp::Less,
1✔
886
            BinaryOp::LessEqual,
1✔
887
            BinaryOp::Greater,
1✔
888
            BinaryOp::GreaterEqual,
1✔
889
            BinaryOp::ShiftLeft,
1✔
890
            BinaryOp::ShiftRight,
1✔
891
            BinaryOp::Add,
1✔
892
            BinaryOp::Sub,
1✔
893
            BinaryOp::Mul,
1✔
894
            BinaryOp::Div,
1✔
895
        ];
1✔
896

897
        for op in all_ops.iter().copied() {
17✔
898
            let (left, right, out_ty) = match op {
17✔
899
                BinaryOp::LogicAnd | BinaryOp::LogicOr => (
2✔
900
                    Expr::Value(Value::Bool(true)),
2✔
901
                    Expr::Var(Var::Bit {
2✔
902
                        bit: ShareableClbit::new_anonymous(),
2✔
903
                    }),
2✔
904
                    Type::Bool,
2✔
905
                ),
2✔
906
                _ => (
907
                    Expr::Value(Value::new_small_int(5, 3)),
15✔
908
                    Expr::Var(Var::Register {
15✔
909
                        register: ClassicalRegister::new_owning("a", 3),
15✔
910
                        ty: Type::Uint(3),
15✔
911
                    }),
15✔
912
                    match op {
15✔
913
                        BinaryOp::BitAnd | BinaryOp::BitOr | BinaryOp::BitXor => Type::Uint(3),
3✔
914
                        _ => Type::Bool,
12✔
915
                    },
916
                ),
917
            };
918

919
            let cis = Expr::Binary(
17✔
920
                Binary {
17✔
921
                    op,
17✔
922
                    left: left.clone(),
17✔
923
                    right: right.clone(),
17✔
924
                    ty: out_ty,
17✔
925
                    constant: false,
17✔
926
                }
17✔
927
                .into(),
17✔
928
            );
17✔
929

930
            let trans = Expr::Binary(
17✔
931
                Binary {
17✔
932
                    op,
17✔
933
                    left: right,
17✔
934
                    right: left,
17✔
935
                    ty: out_ty,
17✔
936
                    constant: false,
17✔
937
                }
17✔
938
                .into(),
17✔
939
            );
17✔
940

941
            assert!(
17✔
942
                !cis.structurally_equivalent(&trans),
17✔
943
                "Expected {op:?} to not be structurally equivalent to its flipped form"
×
944
            );
945
            assert!(
17✔
946
                !trans.structurally_equivalent(&cis),
17✔
947
                "Expected flipped {op:?} to not be structurally equivalent to original form"
×
948
            );
949
        }
950
    }
1✔
951

952
    #[test]
953
    fn test_structurally_eq_key_function_both() -> PyResult<()> {
1✔
954
        let left_clbit = ShareableClbit::new_anonymous();
1✔
955
        let left_cr = ClassicalRegister::new_owning("a", 3);
1✔
956
        let right_clbit = ShareableClbit::new_anonymous();
1✔
957
        let right_cr = ClassicalRegister::new_owning("b", 3);
1✔
958
        assert_ne!(left_clbit, right_clbit);
1✔
959
        assert_ne!(left_cr, right_cr);
1✔
960

961
        let left = Expr::Unary(
1✔
962
            Unary {
1✔
963
                op: UnaryOp::LogicNot,
1✔
964
                operand: Expr::Binary(
1✔
965
                    Binary {
1✔
966
                        op: BinaryOp::LogicAnd,
1✔
967
                        left: Expr::Binary(
1✔
968
                            Binary {
1✔
969
                                op: BinaryOp::Less,
1✔
970
                                left: Expr::Value(Value::new_small_int(5, 3)),
1✔
971
                                right: Expr::Var(Var::Register {
1✔
972
                                    register: left_cr.clone(),
1✔
973
                                    ty: Type::Uint(3),
1✔
974
                                }),
1✔
975
                                ty: Type::Bool,
1✔
976
                                constant: false,
1✔
977
                            }
1✔
978
                            .into(),
1✔
979
                        ),
1✔
980
                        right: Expr::Var(Var::Bit {
1✔
981
                            bit: left_clbit.clone(),
1✔
982
                        }),
1✔
983
                        ty: Type::Bool,
1✔
984
                        constant: false,
1✔
985
                    }
1✔
986
                    .into(),
1✔
987
                ),
1✔
988
                ty: Type::Bool,
1✔
989
                constant: false,
1✔
990
            }
1✔
991
            .into(),
1✔
992
        );
1✔
993

994
        let right = Expr::Unary(
1✔
995
            Unary {
1✔
996
                op: UnaryOp::LogicNot,
1✔
997
                operand: Expr::Binary(
1✔
998
                    Binary {
1✔
999
                        op: BinaryOp::LogicAnd,
1✔
1000
                        left: Expr::Binary(
1✔
1001
                            Binary {
1✔
1002
                                op: BinaryOp::Less,
1✔
1003
                                left: Expr::Value(Value::new_small_int(5, 3)),
1✔
1004
                                right: Expr::Var(Var::Register {
1✔
1005
                                    register: right_cr.clone(),
1✔
1006
                                    ty: Type::Uint(3),
1✔
1007
                                }),
1✔
1008
                                ty: Type::Bool,
1✔
1009
                                constant: false,
1✔
1010
                            }
1✔
1011
                            .into(),
1✔
1012
                        ),
1✔
1013
                        right: Expr::Var(Var::Bit {
1✔
1014
                            bit: right_clbit.clone(),
1✔
1015
                        }),
1✔
1016
                        ty: Type::Bool,
1✔
1017
                        constant: false,
1✔
1018
                    }
1✔
1019
                    .into(),
1✔
1020
                ),
1✔
1021
                ty: Type::Bool,
1✔
1022
                constant: false,
1✔
1023
            }
1✔
1024
            .into(),
1✔
1025
        );
1✔
1026

1027
        assert!(
1✔
1028
            !left.structurally_equivalent(&right),
1✔
1029
            "Expressions using different registers/clbits should not be structurally equivalent"
×
1030
        );
1031

1032
        // We're happy as long as the variables are of the same kind.
1033
        let key_func = |v: &Var| -> &str {
4✔
1034
            match v {
4✔
1035
                Var::Standalone { .. } => "standalone",
×
1036
                Var::Bit { .. } => "bit",
2✔
1037
                Var::Register { .. } => "register",
2✔
1038
            }
1039
        };
4✔
1040

1041
        assert!(
1✔
1042
            left.structurally_equivalent_by_key(key_func, &right, key_func),
1✔
1043
            "Expressions that only care that their vars are of the same kind should be equivalent"
×
1044
        );
1045

1046
        Ok(())
1✔
1047
    }
1✔
1048
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc