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

Qiskit / qiskit / 21889818541

11 Feb 2026 01:59AM UTC coverage: 87.889% (-0.07%) from 87.958%
21889818541

Pull #14618

github

web-flow
Merge 45345b0f8 into e99db18c5
Pull Request #14618: New classical expr.Range specification

182 of 328 new or added lines in 16 files covered. (55.49%)

12 existing lines in 5 files now uncovered.

100304 of 114126 relevant lines covered (87.89%)

1161660.91 hits per line

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

89.69
/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 https://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, Range, 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
    Range(Box<Range>),
34
}
35

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

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

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

66
impl Expr {
67
    /// Converts from `&Expr` to `ExprRef`.
68
    pub fn as_ref(&self) -> ExprRef<'_> {
23,658✔
69
        match self {
23,658✔
70
            Expr::Unary(u) => ExprRef::Unary(u.as_ref()),
518✔
71
            Expr::Binary(b) => ExprRef::Binary(b.as_ref()),
7,070✔
72
            Expr::Cast(c) => ExprRef::Cast(c.as_ref()),
132✔
73
            Expr::Value(v) => ExprRef::Value(v),
9,239✔
74
            Expr::Var(v) => ExprRef::Var(v),
6,635✔
75
            Expr::Stretch(s) => ExprRef::Stretch(s),
38✔
76
            Expr::Index(i) => ExprRef::Index(i.as_ref()),
26✔
NEW
77
            Expr::Range(r) => ExprRef::Range(r.as_ref()),
×
78
        }
79
    }
23,658✔
80

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

95
    /// The const-ness of the expression.
96
    pub fn is_const(&self) -> bool {
5,404✔
97
        match self {
5,404✔
98
            Expr::Unary(u) => u.constant,
38✔
99
            Expr::Binary(b) => b.constant,
866✔
100
            Expr::Cast(c) => c.constant,
104✔
101
            Expr::Value(_) => true,
2,286✔
102
            Expr::Var(_) => false,
2,004✔
103
            Expr::Stretch(_) => true,
100✔
104
            Expr::Index(i) => i.constant,
6✔
NEW
105
            Expr::Range(r) => r.constant,
×
106
        }
107
    }
5,404✔
108

109
    /// The expression's [Type].
110
    pub fn ty(&self) -> Type {
318✔
111
        match self {
318✔
112
            Expr::Unary(u) => u.ty,
×
113
            Expr::Binary(b) => b.ty,
×
114
            Expr::Cast(c) => c.ty,
×
115
            Expr::Value(v) => match v {
266✔
116
                Value::Duration(_) => Type::Duration,
×
117
                Value::Float { ty, .. } => *ty,
8✔
118
                Value::Uint { ty, .. } => *ty,
258✔
119
            },
120
            Expr::Var(v) => match v {
52✔
121
                Var::Standalone { ty, .. } => *ty,
32✔
122
                Var::Bit { .. } => Type::Bool,
×
123
                Var::Register { ty, .. } => *ty,
20✔
124
            },
125
            Expr::Stretch(_) => Type::Duration,
×
126
            Expr::Index(i) => i.ty,
×
NEW
127
            Expr::Range(r) => r.ty,
×
128
        }
129
    }
318✔
130

131
    /// Returns an iterator over the identifier nodes in this expression in some
132
    /// deterministic order.
133
    pub fn identifiers(&self) -> impl Iterator<Item = IdentifierRef<'_>> {
1✔
134
        IdentIterator(ExprIterator { stack: vec![self] })
1✔
135
    }
1✔
136

137
    /// Returns an iterator over the [Var] nodes in this expression in some
138
    /// deterministic order.
139
    pub fn vars(&self) -> impl Iterator<Item = &Var> {
8,228✔
140
        VarIterator(ExprIterator { stack: vec![self] })
8,228✔
141
    }
8,228✔
142

143
    /// Returns an iterator over all nodes in this expression in some deterministic
144
    /// order.
145
    pub fn iter(&self) -> impl Iterator<Item = ExprRef<'_>> {
657✔
146
        ExprIterator { stack: vec![self] }
657✔
147
    }
657✔
148

149
    /// Visits all nodes by mutable reference, in a post-order traversal.
150
    pub fn visit_mut<F>(&mut self, mut visitor: F) -> PyResult<()>
26✔
151
    where
26✔
152
        F: FnMut(ExprRefMut) -> PyResult<()>,
26✔
153
    {
154
        self.visit_mut_impl(&mut visitor)
26✔
155
    }
26✔
156

157
    fn visit_mut_impl<F>(&mut self, visitor: &mut F) -> PyResult<()>
69✔
158
    where
69✔
159
        F: FnMut(ExprRefMut) -> PyResult<()>,
69✔
160
    {
161
        match self {
69✔
162
            Expr::Unary(u) => u.operand.visit_mut_impl(visitor)?,
7✔
163
            Expr::Binary(b) => {
16✔
164
                b.left.visit_mut_impl(visitor)?;
16✔
165
                b.right.visit_mut_impl(visitor)?;
16✔
166
            }
167
            Expr::Cast(c) => c.operand.visit_mut_impl(visitor)?,
4✔
168
            Expr::Value(_) => {}
10✔
169
            Expr::Var(_) => {}
30✔
170
            Expr::Stretch(_) => {}
2✔
171
            Expr::Index(i) => {
×
172
                i.target.visit_mut_impl(visitor)?;
×
173
                i.index.visit_mut_impl(visitor)?;
×
174
            }
NEW
175
            Expr::Range(r) => {
×
NEW
176
                r.start.visit_mut_impl(visitor)?;
×
NEW
177
                r.stop.visit_mut_impl(visitor)?;
×
NEW
178
                r.step.visit_mut_impl(visitor)?;
×
179
            }
180
        }
181
        visitor(self.as_mut())
69✔
182
    }
69✔
183

184
    /// Do these two expressions have exactly the same tree structure?
185
    pub fn structurally_equivalent(&self, other: &Expr) -> bool {
45✔
186
        let identity_key = |v: &Var| v.clone();
45✔
187
        self.structurally_equivalent_by_key(identity_key, other, identity_key)
45✔
188
    }
45✔
189

190
    /// Do these two expressions have exactly the same tree structure, up to some key function for
191
    /// [Var] nodes?
192
    ///
193
    /// In other words, are these two expressions the exact same trees, except we compare the
194
    /// [Var] nodes by calling the appropriate `*_var_key` function on them, and comparing
195
    /// that output for equality.  This function does not allow any semantic "equivalences" such as
196
    /// asserting that `a == b` is equivalent to `b == a`; the evaluation order of the operands
197
    /// could, in general, cause such a statement to be false.
198
    pub fn structurally_equivalent_by_key<F1, F2, K>(
328✔
199
        &self,
328✔
200
        mut self_var_key: F1,
328✔
201
        other: &Expr,
328✔
202
        mut other_var_key: F2,
328✔
203
    ) -> bool
328✔
204
    where
328✔
205
        F1: FnMut(&Var) -> K,
328✔
206
        F2: FnMut(&Var) -> K,
328✔
207
        K: PartialEq,
328✔
208
    {
209
        let mut self_nodes = self.iter();
328✔
210
        let mut other_nodes = other.iter();
328✔
211
        loop {
212
            match (self_nodes.next(), other_nodes.next()) {
1,486✔
213
                (Some(a), Some(b)) => match (a, b) {
1,193✔
214
                    (ExprRef::Unary(a), ExprRef::Unary(b)) => {
59✔
215
                        if a.op != b.op || a.ty != b.ty || a.constant != b.constant {
59✔
216
                            return false;
×
217
                        }
59✔
218
                    }
219
                    (ExprRef::Binary(a), ExprRef::Binary(b)) => {
403✔
220
                        if a.op != b.op || a.ty != b.ty || a.constant != b.constant {
403✔
221
                            return false;
×
222
                        }
403✔
223
                    }
224
                    (ExprRef::Cast(a), ExprRef::Cast(b)) => {
25✔
225
                        if a.ty != b.ty || a.constant != b.constant {
25✔
226
                            return false;
×
227
                        }
25✔
228
                    }
229
                    (ExprRef::Value(a), ExprRef::Value(b)) => {
363✔
230
                        if a != b {
363✔
231
                            return false;
×
232
                        }
363✔
233
                    }
234
                    (ExprRef::Var(a), ExprRef::Var(b)) => {
287✔
235
                        if a.ty() != b.ty() {
287✔
236
                            return false;
×
237
                        }
287✔
238
                        if self_var_key(a) != other_var_key(b) {
287✔
239
                            return false;
1✔
240
                        }
286✔
241
                    }
242
                    (ExprRef::Stretch(a), ExprRef::Stretch(b)) => {
17✔
243
                        if a.uuid != b.uuid {
17✔
244
                            return false;
×
245
                        }
17✔
246
                    }
247
                    (ExprRef::Index(a), ExprRef::Index(b)) => {
5✔
248
                        if a.ty != b.ty || a.constant != b.constant {
5✔
249
                            return false;
×
250
                        }
5✔
251
                    }
NEW
252
                    (ExprRef::Range(a), ExprRef::Range(b)) => {
×
NEW
253
                        if a.ty != b.ty || a.constant != b.constant {
×
NEW
254
                            return false;
×
NEW
255
                        }
×
256
                        // Compare the actual values of start, stop, and step expressions
NEW
257
                        if !a.start.structurally_equivalent(&b.start)
×
NEW
258
                            || !a.stop.structurally_equivalent(&b.stop)
×
NEW
259
                            || !a.step.structurally_equivalent(&b.step)
×
260
                        {
NEW
261
                            return false;
×
NEW
262
                        }
×
263
                    }
264
                    _ => return false,
34✔
265
                },
266
                (None, None) => return true,
293✔
267
                _ => return false,
×
268
            }
269
        }
270
    }
328✔
271
}
272

273
/// A private iterator over the [Expr] nodes of an expression
274
/// by reference.
275
///
276
/// The first node reference returned is the [Expr] itself.
277
struct ExprIterator<'a> {
278
    stack: Vec<&'a Expr>,
279
}
280

281
impl<'a> Iterator for ExprIterator<'a> {
282
    type Item = ExprRef<'a>;
283

284
    fn next(&mut self) -> Option<Self::Item> {
32,473✔
285
        let expr = self.stack.pop()?;
32,473✔
286
        match expr {
23,658✔
287
            Expr::Unary(u) => {
518✔
288
                self.stack.push(&u.operand);
518✔
289
            }
518✔
290
            Expr::Binary(b) => {
7,070✔
291
                self.stack.push(&b.left);
7,070✔
292
                self.stack.push(&b.right);
7,070✔
293
            }
7,070✔
294
            Expr::Cast(c) => self.stack.push(&c.operand),
132✔
295
            Expr::Value(_) => {}
9,239✔
296
            Expr::Var(_) => {}
6,635✔
297
            Expr::Stretch(_) => {}
38✔
298
            Expr::Index(i) => {
26✔
299
                self.stack.push(&i.index);
26✔
300
                self.stack.push(&i.target);
26✔
301
            }
26✔
NEW
302
            Expr::Range(r) => {
×
NEW
303
                self.stack.push(&r.stop);
×
NEW
304
                self.stack.push(&r.start);
×
NEW
305
                self.stack.push(&r.step);
×
NEW
306
            }
×
307
        }
308
        Some(expr.as_ref())
23,658✔
309
    }
32,473✔
310
}
311

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

315
impl<'a> Iterator for VarIterator<'a> {
316
    type Item = &'a Var;
317

318
    fn next(&mut self) -> Option<Self::Item> {
14,252✔
319
        for expr in self.0.by_ref() {
21,258✔
320
            if let ExprRef::Var(v) = expr {
21,258✔
321
                return Some(v);
6,025✔
322
            }
15,233✔
323
        }
324
        None
8,227✔
325
    }
14,252✔
326
}
327

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

331
impl<'a> Iterator for IdentIterator<'a> {
332
    type Item = IdentifierRef<'a>;
333

334
    fn next(&mut self) -> Option<Self::Item> {
4✔
335
        for expr in self.0.by_ref() {
7✔
336
            if let ExprRef::Var(v) = expr {
7✔
337
                return Some(IdentifierRef::Var(v));
1✔
338
            }
6✔
339
            if let ExprRef::Stretch(s) = expr {
6✔
340
                return Some(IdentifierRef::Stretch(s));
2✔
341
            }
4✔
342
        }
343
        None
1✔
344
    }
4✔
345
}
346

347
impl From<Unary> for Expr {
348
    fn from(value: Unary) -> Self {
2✔
349
        Expr::Unary(Box::new(value))
2✔
350
    }
2✔
351
}
352

353
impl From<Box<Unary>> for Expr {
354
    fn from(value: Box<Unary>) -> Self {
×
355
        Expr::Unary(value)
×
356
    }
×
357
}
358

359
impl From<Binary> for Expr {
360
    fn from(value: Binary) -> Self {
11✔
361
        Expr::Binary(Box::new(value))
11✔
362
    }
11✔
363
}
364

365
impl From<Box<Binary>> for Expr {
366
    fn from(value: Box<Binary>) -> Self {
×
367
        Expr::Binary(value)
×
368
    }
×
369
}
370

371
impl From<Cast> for Expr {
372
    fn from(value: Cast) -> Self {
×
373
        Expr::Cast(Box::new(value))
×
374
    }
×
375
}
376

377
impl From<Box<Cast>> for Expr {
378
    fn from(value: Box<Cast>) -> Self {
×
379
        Expr::Cast(value)
×
380
    }
×
381
}
382

383
impl From<Value> for Expr {
384
    fn from(value: Value) -> Self {
16✔
385
        Expr::Value(value)
16✔
386
    }
16✔
387
}
388

389
impl From<Var> for Expr {
390
    fn from(value: Var) -> Self {
6✔
391
        Expr::Var(value)
6✔
392
    }
6✔
393
}
394

395
impl From<Stretch> for Expr {
396
    fn from(value: Stretch) -> Self {
6✔
397
        Expr::Stretch(value)
6✔
398
    }
6✔
399
}
400

401
impl From<Index> for Expr {
402
    fn from(value: Index) -> Self {
×
403
        Expr::Index(Box::new(value))
×
404
    }
×
405
}
406

407
impl From<Box<Index>> for Expr {
408
    fn from(value: Box<Index>) -> Self {
×
409
        Expr::Index(value)
×
410
    }
×
411
}
412

413
impl From<Range> for Expr {
NEW
414
    fn from(value: Range) -> Self {
×
NEW
415
        Expr::Range(Box::new(value))
×
NEW
416
    }
×
417
}
418

419
impl From<Box<Range>> for Expr {
NEW
420
    fn from(value: Box<Range>) -> Self {
×
NEW
421
        Expr::Range(value)
×
NEW
422
    }
×
423
}
424

425
/// Root base class of all nodes in the expression tree.  The base case should never be
426
/// instantiated directly.
427
///
428
/// This must not be subclassed by users; subclasses form the internal data of the representation of
429
/// expressions, and it does not make sense to add more outside of Qiskit library code.
430
///
431
/// All subclasses are responsible for setting their ``type`` attribute in their ``__init__``, and
432
/// should not call the parent initializer."""
433
#[pyclass(
×
434
    eq,
×
435
    hash,
×
436
    subclass,
437
    frozen,
438
    name = "Expr",
439
    module = "qiskit._accelerate.circuit.classical.expr"
440
)]
×
441
#[derive(PartialEq, Clone, Copy, Debug, Hash)]
442
pub struct PyExpr(pub ExprKind); // ExprKind is used for fast extraction from Python
443

444
#[pymethods]
445
impl PyExpr {
446
    /// Call the relevant ``visit_*`` method on the given :class:`ExprVisitor`.  The usual entry
447
    /// point for a simple visitor is to construct it, and then call :meth:`accept` on the root
448
    /// object to be visited.  For example::
449
    ///
450
    ///     expr = ...
451
    ///     visitor = MyVisitor()
452
    ///     visitor.accept(expr)
453
    ///
454
    /// Subclasses of :class:`Expr` should override this to call the correct virtual method on the
455
    /// visitor.  This implements double dispatch with the visitor."""
456
    /// return visitor.visit_generic(self)
457
    fn accept<'py>(
×
458
        slf: PyRef<'py, Self>,
×
459
        visitor: &Bound<'py, PyAny>,
×
460
    ) -> PyResult<Bound<'py, PyAny>> {
×
461
        visitor.call_method1(intern!(visitor.py(), "visit_generic"), (slf,))
×
462
    }
×
463
}
464

465
/// The expression's kind, used internally during Python instance extraction to avoid
466
/// `isinstance` checks.
467
#[repr(u8)]
468
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
469
pub enum ExprKind {
470
    Unary,
471
    Binary,
472
    Value,
473
    Var,
474
    Cast,
475
    Stretch,
476
    Index,
477
    Range,
478
}
479

480
impl<'py> IntoPyObject<'py> for Expr {
481
    type Target = PyAny;
482
    type Output = Bound<'py, PyAny>;
483
    type Error = PyErr;
484

485
    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
8,114✔
486
        match self {
8,114✔
487
            Expr::Unary(u) => u.into_bound_py_any(py),
194✔
488
            Expr::Binary(b) => b.into_bound_py_any(py),
2,228✔
489
            Expr::Cast(c) => c.into_bound_py_any(py),
94✔
490
            Expr::Value(v) => v.into_bound_py_any(py),
2,710✔
491
            Expr::Var(v) => v.into_bound_py_any(py),
2,716✔
492
            Expr::Stretch(s) => s.into_bound_py_any(py),
150✔
493
            Expr::Index(i) => i.into_bound_py_any(py),
20✔
494
            Expr::Range(r) => r.into_bound_py_any(py),
2✔
495
        }
496
    }
8,114✔
497
}
498

499
impl<'a, 'py> FromPyObject<'a, 'py> for Expr {
500
    type Error = PyErr;
501

502
    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
14,290✔
503
        let expr: PyRef<'_, PyExpr> = ob.cast()?.borrow();
14,290✔
504
        match expr.0 {
14,084✔
505
            ExprKind::Unary => Ok(Expr::Unary(Box::new(ob.extract()?))),
356✔
506
            ExprKind::Binary => Ok(Expr::Binary(Box::new(ob.extract()?))),
2,552✔
507
            ExprKind::Value => Ok(Expr::Value(ob.extract()?)),
5,120✔
508
            ExprKind::Var => Ok(Expr::Var(ob.extract()?)),
5,724✔
509
            ExprKind::Cast => Ok(Expr::Cast(Box::new(ob.extract()?))),
148✔
510
            ExprKind::Stretch => Ok(Expr::Stretch(ob.extract()?)),
156✔
511
            ExprKind::Index => Ok(Expr::Index(Box::new(ob.extract()?))),
28✔
NEW
512
            ExprKind::Range => Ok(Expr::Range(Box::new(ob.extract()?))),
×
513
        }
514
    }
14,290✔
515
}
516

517
#[cfg(test)]
518
mod tests {
519
    use crate::bit::{ClassicalRegister, ShareableClbit};
520
    use crate::classical::expr::{
521
        Binary, BinaryOp, Cast, Expr, ExprRef, ExprRefMut, IdentifierRef, Index, Stretch, Unary,
522
        UnaryOp, Value, Var,
523
    };
524
    use crate::classical::types::Type;
525
    use crate::duration::Duration;
526
    use num_bigint::BigUint;
527
    use pyo3::PyResult;
528
    use uuid::Uuid;
529

530
    #[test]
531
    fn test_vars() {
1✔
532
        let expr: Expr = Binary {
1✔
533
            op: BinaryOp::BitAnd,
1✔
534
            left: Unary {
1✔
535
                op: UnaryOp::BitNot,
1✔
536
                operand: Var::Standalone {
1✔
537
                    uuid: Uuid::new_v4().as_u128(),
1✔
538
                    name: "test".to_string(),
1✔
539
                    ty: Type::Bool,
1✔
540
                }
1✔
541
                .into(),
1✔
542
                ty: Type::Bool,
1✔
543
                constant: false,
1✔
544
            }
1✔
545
            .into(),
1✔
546
            right: Var::Bit {
1✔
547
                bit: ShareableClbit::new_anonymous(),
1✔
548
            }
1✔
549
            .into(),
1✔
550
            ty: Type::Bool,
1✔
551
            constant: false,
1✔
552
        }
1✔
553
        .into();
1✔
554

555
        let vars: Vec<&Var> = expr.vars().collect();
1✔
556
        assert!(matches!(
1✔
557
            vars.as_slice(),
1✔
558
            [Var::Bit { .. }, Var::Standalone { .. }]
1✔
559
        ));
560
    }
1✔
561

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

600
        let identifiers: Vec<IdentifierRef> = expr.identifiers().collect();
1✔
601
        assert!(matches!(
1✔
602
            identifiers.as_slice(),
1✔
603
            [
1✔
604
                IdentifierRef::Stretch(Stretch { .. }),
1✔
605
                IdentifierRef::Stretch(Stretch { .. }),
1✔
606
                IdentifierRef::Var(Var::Standalone { .. }),
1✔
607
            ]
1✔
608
        ));
609
    }
1✔
610

611
    #[test]
612
    fn test_iter() {
1✔
613
        let expr: Expr = Binary {
1✔
614
            op: BinaryOp::Mul,
1✔
615
            left: Binary {
1✔
616
                op: BinaryOp::Add,
1✔
617
                left: Var::Standalone {
1✔
618
                    uuid: Uuid::new_v4().as_u128(),
1✔
619
                    name: "test".to_string(),
1✔
620
                    ty: Type::Duration,
1✔
621
                }
1✔
622
                .into(),
1✔
623
                right: Stretch {
1✔
624
                    uuid: Uuid::new_v4().as_u128(),
1✔
625
                    name: "test".to_string(),
1✔
626
                }
1✔
627
                .into(),
1✔
628
                ty: Type::Duration,
1✔
629
                constant: false,
1✔
630
            }
1✔
631
            .into(),
1✔
632
            right: Binary {
1✔
633
                op: BinaryOp::Div,
1✔
634
                left: Stretch {
1✔
635
                    uuid: Uuid::new_v4().as_u128(),
1✔
636
                    name: "test".to_string(),
1✔
637
                }
1✔
638
                .into(),
1✔
639
                right: Value::Duration(Duration::dt(1000)).into(),
1✔
640
                ty: Type::Float,
1✔
641
                constant: true,
1✔
642
            }
1✔
643
            .into(),
1✔
644
            ty: Type::Bool,
1✔
645
            constant: false,
1✔
646
        }
1✔
647
        .into();
1✔
648

649
        let exprs: Vec<ExprRef> = expr.iter().collect();
1✔
650
        assert!(matches!(
1✔
651
            exprs.as_slice(),
1✔
652
            [
1✔
653
                ExprRef::Binary(Binary {
1✔
654
                    op: BinaryOp::Mul,
1✔
655
                    ..
1✔
656
                }),
1✔
657
                ExprRef::Binary(Binary {
1✔
658
                    op: BinaryOp::Div,
1✔
659
                    ..
1✔
660
                }),
1✔
661
                ExprRef::Value(Value::Duration(..)),
1✔
662
                ExprRef::Stretch(Stretch { .. }),
1✔
663
                ExprRef::Binary(Binary {
1✔
664
                    op: BinaryOp::Add,
1✔
665
                    ..
1✔
666
                }),
1✔
667
                ExprRef::Stretch(Stretch { .. }),
1✔
668
                ExprRef::Var(Var::Standalone { .. }),
1✔
669
            ]
1✔
670
        ));
671
    }
1✔
672

673
    #[test]
674
    fn test_visit_mut_ordering() -> PyResult<()> {
1✔
675
        let mut expr: Expr = Binary {
1✔
676
            op: BinaryOp::Mul,
1✔
677
            left: Binary {
1✔
678
                op: BinaryOp::Add,
1✔
679
                left: Var::Standalone {
1✔
680
                    uuid: Uuid::new_v4().as_u128(),
1✔
681
                    name: "test".to_string(),
1✔
682
                    ty: Type::Duration,
1✔
683
                }
1✔
684
                .into(),
1✔
685
                right: Stretch {
1✔
686
                    uuid: Uuid::new_v4().as_u128(),
1✔
687
                    name: "test".to_string(),
1✔
688
                }
1✔
689
                .into(),
1✔
690
                ty: Type::Duration,
1✔
691
                constant: false,
1✔
692
            }
1✔
693
            .into(),
1✔
694
            right: Binary {
1✔
695
                op: BinaryOp::Div,
1✔
696
                left: Stretch {
1✔
697
                    uuid: Uuid::new_v4().as_u128(),
1✔
698
                    name: "test".to_string(),
1✔
699
                }
1✔
700
                .into(),
1✔
701
                right: Value::Duration(Duration::dt(1000)).into(),
1✔
702
                ty: Type::Float,
1✔
703
                constant: true,
1✔
704
            }
1✔
705
            .into(),
1✔
706
            ty: Type::Bool,
1✔
707
            constant: false,
1✔
708
        }
1✔
709
        .into();
1✔
710

711
        // These get *consumed* by every visit, so by the end we expect this
712
        // iterator to be empty. The ordering here is post-order, LRN.
713
        let mut order = [
1✔
714
            |x: &ExprRefMut| matches!(x, ExprRefMut::Var(Var::Standalone { .. })),
1✔
715
            |x: &ExprRefMut| matches!(x, ExprRefMut::Stretch(Stretch { .. })),
1✔
716
            |x: &ExprRefMut| {
1✔
717
                matches!(
×
718
                    x,
1✔
719
                    ExprRefMut::Binary(Binary {
720
                        op: BinaryOp::Add,
721
                        ..
722
                    })
723
                )
724
            },
1✔
725
            |x: &ExprRefMut| matches!(x, ExprRefMut::Stretch(Stretch { .. })),
1✔
726
            |x: &ExprRefMut| matches!(x, ExprRefMut::Value(Value::Duration(..))),
1✔
727
            |x: &ExprRefMut| {
1✔
728
                matches!(
×
729
                    x,
1✔
730
                    ExprRefMut::Binary(Binary {
731
                        op: BinaryOp::Div,
732
                        ..
733
                    })
734
                )
735
            },
1✔
736
            |x: &ExprRefMut| {
1✔
737
                matches!(
×
738
                    x,
1✔
739
                    ExprRefMut::Binary(Binary {
740
                        op: BinaryOp::Mul,
741
                        ..
742
                    })
743
                )
744
            },
1✔
745
        ]
746
        .into_iter();
1✔
747

748
        expr.visit_mut(|x| {
7✔
749
            assert!(order.next().unwrap()(&x));
7✔
750
            Ok(())
7✔
751
        })?;
7✔
752

753
        assert!(order.next().is_none());
1✔
754
        Ok(())
1✔
755
    }
1✔
756

757
    #[test]
758
    fn test_visit_mut() -> PyResult<()> {
1✔
759
        let mut expr: Expr = Binary {
1✔
760
            op: BinaryOp::BitAnd,
1✔
761
            left: Unary {
1✔
762
                op: UnaryOp::BitNot,
1✔
763
                operand: Var::Standalone {
1✔
764
                    uuid: Uuid::new_v4().as_u128(),
1✔
765
                    name: "test".to_string(),
1✔
766
                    ty: Type::Bool,
1✔
767
                }
1✔
768
                .into(),
1✔
769
                ty: Type::Bool,
1✔
770
                constant: false,
1✔
771
            }
1✔
772
            .into(),
1✔
773
            right: Value::Uint {
1✔
774
                raw: BigUint::from(1u8),
1✔
775
                ty: Type::Bool,
1✔
776
            }
1✔
777
            .into(),
1✔
778
            ty: Type::Bool,
1✔
779
            constant: false,
1✔
780
        }
1✔
781
        .into();
1✔
782

783
        expr.visit_mut(|x| match x {
1✔
784
            ExprRefMut::Var(Var::Standalone { name, .. }) => {
1✔
785
                *name = "updated".to_string();
1✔
786
                Ok(())
1✔
787
            }
788
            _ => Ok(()),
3✔
789
        })?;
4✔
790

791
        let Var::Standalone { name, .. } = expr.vars().next().unwrap() else {
1✔
792
            panic!("wrong var type")
×
793
        };
794
        assert_eq!(name.as_str(), "updated");
1✔
795
        Ok(())
1✔
796
    }
1✔
797

798
    #[test]
799
    fn test_structurally_eq_to_self() -> PyResult<()> {
1✔
800
        let exprs = [
1✔
801
            Expr::Var(Var::Bit {
1✔
802
                bit: ShareableClbit::new_anonymous(),
1✔
803
            }),
1✔
804
            Expr::Var(Var::Register {
1✔
805
                register: ClassicalRegister::new_owning("a", 3),
1✔
806
                ty: Type::Uint(3),
1✔
807
            }),
1✔
808
            Expr::Value(Value::Uint {
1✔
809
                raw: BigUint::from(3u8),
1✔
810
                ty: Type::Uint(2),
1✔
811
            }),
1✔
812
            Expr::Cast(
1✔
813
                Cast {
1✔
814
                    operand: Expr::Var(Var::Register {
1✔
815
                        register: ClassicalRegister::new_owning("a", 3),
1✔
816
                        ty: Type::Uint(3),
1✔
817
                    }),
1✔
818
                    ty: Type::Bool,
1✔
819
                    constant: false,
1✔
820
                    implicit: false,
1✔
821
                }
1✔
822
                .into(),
1✔
823
            ),
1✔
824
            Expr::Unary(
1✔
825
                Unary {
1✔
826
                    op: UnaryOp::LogicNot,
1✔
827
                    operand: Expr::Var(Var::Bit {
1✔
828
                        bit: ShareableClbit::new_anonymous(),
1✔
829
                    }),
1✔
830
                    ty: Type::Bool,
1✔
831
                    constant: false,
1✔
832
                }
1✔
833
                .into(),
1✔
834
            ),
1✔
835
            Expr::Binary(
1✔
836
                Binary {
1✔
837
                    op: BinaryOp::BitAnd,
1✔
838
                    left: Expr::Value(Value::Uint {
1✔
839
                        raw: BigUint::from(5u8),
1✔
840
                        ty: Type::Uint(3),
1✔
841
                    }),
1✔
842
                    right: Expr::Var(Var::Register {
1✔
843
                        register: ClassicalRegister::new_owning("a", 3),
1✔
844
                        ty: Type::Uint(3),
1✔
845
                    }),
1✔
846
                    ty: Type::Uint(3),
1✔
847
                    constant: false,
1✔
848
                }
1✔
849
                .into(),
1✔
850
            ),
1✔
851
            Expr::Binary(
1✔
852
                Binary {
1✔
853
                    op: BinaryOp::LogicAnd,
1✔
854
                    left: Expr::Binary(
1✔
855
                        Binary {
1✔
856
                            op: BinaryOp::Less,
1✔
857
                            left: Expr::Value(Value::Uint {
1✔
858
                                raw: BigUint::from(2u8),
1✔
859
                                ty: Type::Uint(3),
1✔
860
                            }),
1✔
861
                            right: Expr::Var(Var::Register {
1✔
862
                                register: ClassicalRegister::new_owning("a", 3),
1✔
863
                                ty: Type::Uint(3),
1✔
864
                            }),
1✔
865
                            ty: Type::Bool,
1✔
866
                            constant: false,
1✔
867
                        }
1✔
868
                        .into(),
1✔
869
                    ),
1✔
870
                    right: Expr::Var(Var::Bit {
1✔
871
                        bit: ShareableClbit::new_anonymous(),
1✔
872
                    }),
1✔
873
                    ty: Type::Bool,
1✔
874
                    constant: false,
1✔
875
                }
1✔
876
                .into(),
1✔
877
            ),
1✔
878
            Expr::Binary(
1✔
879
                Binary {
1✔
880
                    op: BinaryOp::ShiftLeft,
1✔
881
                    left: Expr::Binary(
1✔
882
                        Binary {
1✔
883
                            op: BinaryOp::ShiftRight,
1✔
884
                            left: Expr::Value(Value::Uint {
1✔
885
                                raw: BigUint::from(255u8),
1✔
886
                                ty: Type::Uint(8),
1✔
887
                            }),
1✔
888
                            right: Expr::Value(Value::Uint {
1✔
889
                                raw: BigUint::from(3u8),
1✔
890
                                ty: Type::Uint(8),
1✔
891
                            }),
1✔
892
                            ty: Type::Uint(8),
1✔
893
                            constant: true,
1✔
894
                        }
1✔
895
                        .into(),
1✔
896
                    ),
1✔
897
                    right: Expr::Value(Value::Uint {
1✔
898
                        raw: BigUint::from(3u8),
1✔
899
                        ty: Type::Uint(8),
1✔
900
                    }),
1✔
901
                    ty: Type::Uint(8),
1✔
902
                    constant: true,
1✔
903
                }
1✔
904
                .into(),
1✔
905
            ),
1✔
906
            Expr::Index(
1✔
907
                Index {
1✔
908
                    target: Expr::Var(Var::Standalone {
1✔
909
                        uuid: Uuid::new_v4().as_u128(),
1✔
910
                        name: "a".to_string(),
1✔
911
                        ty: Type::Uint(8),
1✔
912
                    }),
1✔
913
                    index: Expr::Value(Value::Uint {
1✔
914
                        raw: BigUint::from(0u8),
1✔
915
                        ty: Type::Uint(8),
1✔
916
                    }),
1✔
917
                    ty: Type::Uint(1),
1✔
918
                    constant: false,
1✔
919
                }
1✔
920
                .into(),
1✔
921
            ),
1✔
922
            Expr::Binary(
1✔
923
                Binary {
1✔
924
                    op: BinaryOp::Greater,
1✔
925
                    left: Expr::Stretch(Stretch {
1✔
926
                        uuid: Uuid::new_v4().as_u128(),
1✔
927
                        name: "a".to_string(),
1✔
928
                    }),
1✔
929
                    right: Expr::Value(Value::Duration(Duration::dt(100))),
1✔
930
                    ty: Type::Bool,
1✔
931
                    constant: false,
1✔
932
                }
1✔
933
                .into(),
1✔
934
            ),
1✔
935
        ];
1✔
936

937
        for expr in exprs.iter() {
10✔
938
            assert!(expr.structurally_equivalent(expr));
10✔
939
        }
940

941
        Ok(())
1✔
942
    }
1✔
943

944
    #[test]
945
    fn test_structurally_eq_does_not_compare_symmetrically() {
1✔
946
        let all_ops = [
1✔
947
            BinaryOp::BitAnd,
1✔
948
            BinaryOp::BitOr,
1✔
949
            BinaryOp::BitXor,
1✔
950
            BinaryOp::LogicAnd,
1✔
951
            BinaryOp::LogicOr,
1✔
952
            BinaryOp::Equal,
1✔
953
            BinaryOp::NotEqual,
1✔
954
            BinaryOp::Less,
1✔
955
            BinaryOp::LessEqual,
1✔
956
            BinaryOp::Greater,
1✔
957
            BinaryOp::GreaterEqual,
1✔
958
            BinaryOp::ShiftLeft,
1✔
959
            BinaryOp::ShiftRight,
1✔
960
            BinaryOp::Add,
1✔
961
            BinaryOp::Sub,
1✔
962
            BinaryOp::Mul,
1✔
963
            BinaryOp::Div,
1✔
964
        ];
1✔
965

966
        for op in all_ops.iter().copied() {
17✔
967
            let (left, right, out_ty) = match op {
17✔
968
                BinaryOp::LogicAnd | BinaryOp::LogicOr => (
2✔
969
                    Expr::Value(Value::Uint {
2✔
970
                        raw: BigUint::from(1u8),
2✔
971
                        ty: Type::Bool,
2✔
972
                    }),
2✔
973
                    Expr::Var(Var::Bit {
2✔
974
                        bit: ShareableClbit::new_anonymous(),
2✔
975
                    }),
2✔
976
                    Type::Bool,
2✔
977
                ),
2✔
978
                _ => (
979
                    Expr::Value(Value::Uint {
15✔
980
                        raw: BigUint::from(5u8),
15✔
981
                        ty: Type::Uint(3),
15✔
982
                    }),
15✔
983
                    Expr::Var(Var::Register {
15✔
984
                        register: ClassicalRegister::new_owning("a", 3),
15✔
985
                        ty: Type::Uint(3),
15✔
986
                    }),
15✔
987
                    match op {
15✔
988
                        BinaryOp::BitAnd | BinaryOp::BitOr | BinaryOp::BitXor => Type::Uint(3),
3✔
989
                        _ => Type::Bool,
12✔
990
                    },
991
                ),
992
            };
993

994
            let cis = Expr::Binary(
17✔
995
                Binary {
17✔
996
                    op,
17✔
997
                    left: left.clone(),
17✔
998
                    right: right.clone(),
17✔
999
                    ty: out_ty,
17✔
1000
                    constant: false,
17✔
1001
                }
17✔
1002
                .into(),
17✔
1003
            );
17✔
1004

1005
            let trans = Expr::Binary(
17✔
1006
                Binary {
17✔
1007
                    op,
17✔
1008
                    left: right,
17✔
1009
                    right: left,
17✔
1010
                    ty: out_ty,
17✔
1011
                    constant: false,
17✔
1012
                }
17✔
1013
                .into(),
17✔
1014
            );
17✔
1015

1016
            assert!(
17✔
1017
                !cis.structurally_equivalent(&trans),
17✔
1018
                "Expected {op:?} to not be structurally equivalent to its flipped form"
1019
            );
1020
            assert!(
17✔
1021
                !trans.structurally_equivalent(&cis),
17✔
1022
                "Expected flipped {op:?} to not be structurally equivalent to original form"
1023
            );
1024
        }
1025
    }
1✔
1026

1027
    #[test]
1028
    fn test_structurally_eq_key_function_both() -> PyResult<()> {
1✔
1029
        let left_clbit = ShareableClbit::new_anonymous();
1✔
1030
        let left_cr = ClassicalRegister::new_owning("a", 3);
1✔
1031
        let right_clbit = ShareableClbit::new_anonymous();
1✔
1032
        let right_cr = ClassicalRegister::new_owning("b", 3);
1✔
1033
        assert_ne!(left_clbit, right_clbit);
1✔
1034
        assert_ne!(left_cr, right_cr);
1✔
1035

1036
        let left = Expr::Unary(
1✔
1037
            Unary {
1✔
1038
                op: UnaryOp::LogicNot,
1✔
1039
                operand: Expr::Binary(
1✔
1040
                    Binary {
1✔
1041
                        op: BinaryOp::LogicAnd,
1✔
1042
                        left: Expr::Binary(
1✔
1043
                            Binary {
1✔
1044
                                op: BinaryOp::Less,
1✔
1045
                                left: Expr::Value(Value::Uint {
1✔
1046
                                    raw: BigUint::from(5u8),
1✔
1047
                                    ty: Type::Uint(3),
1✔
1048
                                }),
1✔
1049
                                right: Expr::Var(Var::Register {
1✔
1050
                                    register: left_cr.clone(),
1✔
1051
                                    ty: Type::Uint(3),
1✔
1052
                                }),
1✔
1053
                                ty: Type::Bool,
1✔
1054
                                constant: false,
1✔
1055
                            }
1✔
1056
                            .into(),
1✔
1057
                        ),
1✔
1058
                        right: Expr::Var(Var::Bit {
1✔
1059
                            bit: left_clbit.clone(),
1✔
1060
                        }),
1✔
1061
                        ty: Type::Bool,
1✔
1062
                        constant: false,
1✔
1063
                    }
1✔
1064
                    .into(),
1✔
1065
                ),
1✔
1066
                ty: Type::Bool,
1✔
1067
                constant: false,
1✔
1068
            }
1✔
1069
            .into(),
1✔
1070
        );
1✔
1071

1072
        let right = Expr::Unary(
1✔
1073
            Unary {
1✔
1074
                op: UnaryOp::LogicNot,
1✔
1075
                operand: Expr::Binary(
1✔
1076
                    Binary {
1✔
1077
                        op: BinaryOp::LogicAnd,
1✔
1078
                        left: Expr::Binary(
1✔
1079
                            Binary {
1✔
1080
                                op: BinaryOp::Less,
1✔
1081
                                left: Expr::Value(Value::Uint {
1✔
1082
                                    raw: BigUint::from(5u8),
1✔
1083
                                    ty: Type::Uint(3),
1✔
1084
                                }),
1✔
1085
                                right: Expr::Var(Var::Register {
1✔
1086
                                    register: right_cr.clone(),
1✔
1087
                                    ty: Type::Uint(3),
1✔
1088
                                }),
1✔
1089
                                ty: Type::Bool,
1✔
1090
                                constant: false,
1✔
1091
                            }
1✔
1092
                            .into(),
1✔
1093
                        ),
1✔
1094
                        right: Expr::Var(Var::Bit {
1✔
1095
                            bit: right_clbit.clone(),
1✔
1096
                        }),
1✔
1097
                        ty: Type::Bool,
1✔
1098
                        constant: false,
1✔
1099
                    }
1✔
1100
                    .into(),
1✔
1101
                ),
1✔
1102
                ty: Type::Bool,
1✔
1103
                constant: false,
1✔
1104
            }
1✔
1105
            .into(),
1✔
1106
        );
1✔
1107

1108
        assert!(
1✔
1109
            !left.structurally_equivalent(&right),
1✔
1110
            "Expressions using different registers/clbits should not be structurally equivalent"
1111
        );
1112

1113
        // We're happy as long as the variables are of the same kind.
1114
        let key_func = |v: &Var| -> &str {
4✔
1115
            match v {
4✔
1116
                Var::Standalone { .. } => "standalone",
×
1117
                Var::Bit { .. } => "bit",
2✔
1118
                Var::Register { .. } => "register",
2✔
1119
            }
1120
        };
4✔
1121

1122
        assert!(
1✔
1123
            left.structurally_equivalent_by_key(key_func, &right, key_func),
1✔
1124
            "Expressions that only care that their vars are of the same kind should be equivalent"
1125
        );
1126

1127
        Ok(())
1✔
1128
    }
1✔
1129
}
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