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

Qiskit / qiskit / 24006313170

05 Apr 2026 05:07PM UTC coverage: 88.349% (+0.9%) from 87.497%
24006313170

Pull #14618

github

web-flow
Merge c93d928ce into 737060f50
Pull Request #14618: New classical expr.Range specification

191 of 320 new or added lines in 15 files covered. (59.69%)

20 existing lines in 4 files now uncovered.

94784 of 107284 relevant lines covered (88.35%)

1140241.6 hits per line

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

90.14
/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<'_> {
24,602✔
69
        match self {
24,602✔
70
            Expr::Unary(u) => ExprRef::Unary(u.as_ref()),
610✔
71
            Expr::Binary(b) => ExprRef::Binary(b.as_ref()),
7,318✔
72
            Expr::Cast(c) => ExprRef::Cast(c.as_ref()),
148✔
73
            Expr::Value(v) => ExprRef::Value(v),
9,487✔
74
            Expr::Var(v) => ExprRef::Var(v),
6,935✔
75
            Expr::Stretch(s) => ExprRef::Stretch(s),
78✔
76
            Expr::Index(i) => ExprRef::Index(i.as_ref()),
26✔
NEW
77
            Expr::Range(r) => ExprRef::Range(r.as_ref()),
×
78
        }
79
    }
24,602✔
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 {
6,318✔
97
        match self {
6,318✔
98
            Expr::Unary(u) => u.constant,
48✔
99
            Expr::Binary(b) => b.constant,
1,034✔
100
            Expr::Cast(c) => c.constant,
116✔
101
            Expr::Value(_) => true,
2,772✔
102
            Expr::Var(_) => false,
2,198✔
103
            Expr::Stretch(_) => true,
144✔
104
            Expr::Index(i) => i.constant,
6✔
NEW
105
            Expr::Range(r) => r.constant,
×
106
        }
107
    }
6,318✔
108

109
    /// The expression's [Type].
110
    pub fn ty(&self) -> Type {
610✔
111
        match self {
610✔
112
            Expr::Unary(u) => u.ty,
×
113
            Expr::Binary(b) => b.ty,
×
114
            Expr::Cast(c) => c.ty,
×
115
            Expr::Value(v) => match v {
558✔
116
                Value::Duration(_) => Type::Duration,
×
117
                Value::Float { ty, .. } => *ty,
8✔
118
                Value::Uint { ty, .. } => *ty,
550✔
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
    }
610✔
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,392✔
140
        VarIterator(ExprIterator { stack: vec![self] })
8,392✔
141
    }
8,392✔
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<'_>> {
833✔
146
        ExprIterator { stack: vec![self] }
833✔
147
    }
833✔
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>(
416✔
199
        &self,
416✔
200
        mut self_var_key: F1,
416✔
201
        other: &Expr,
416✔
202
        mut other_var_key: F2,
416✔
203
    ) -> bool
416✔
204
    where
416✔
205
        F1: FnMut(&Var) -> K,
416✔
206
        F2: FnMut(&Var) -> K,
416✔
207
        K: PartialEq,
416✔
208
    {
209
        let mut self_nodes = self.iter();
416✔
210
        let mut other_nodes = other.iter();
416✔
211
        loop {
212
            match (self_nodes.next(), other_nodes.next()) {
1,828✔
213
                (Some(a), Some(b)) => match (a, b) {
1,447✔
214
                    (ExprRef::Unary(a), ExprRef::Unary(b)) => {
81✔
215
                        if a.op != b.op || a.ty != b.ty || a.constant != b.constant {
81✔
216
                            return false;
×
217
                        }
81✔
218
                    }
219
                    (ExprRef::Binary(a), ExprRef::Binary(b)) => {
473✔
220
                        if a.op != b.op || a.ty != b.ty || a.constant != b.constant {
473✔
221
                            return false;
×
222
                        }
473✔
223
                    }
224
                    (ExprRef::Cast(a), ExprRef::Cast(b)) => {
29✔
225
                        if a.ty != b.ty || a.constant != b.constant {
29✔
226
                            return false;
×
227
                        }
29✔
228
                    }
229
                    (ExprRef::Value(a), ExprRef::Value(b)) => {
433✔
230
                        if a != b {
433✔
231
                            return false;
×
232
                        }
433✔
233
                    }
234
                    (ExprRef::Var(a), ExprRef::Var(b)) => {
355✔
235
                        if a.ty() != b.ty() {
355✔
236
                            return false;
×
237
                        }
355✔
238
                        if self_var_key(a) != other_var_key(b) {
355✔
239
                            return false;
1✔
240
                        }
354✔
241
                    }
242
                    (ExprRef::Stretch(a), ExprRef::Stretch(b)) => {
37✔
243
                        if a.uuid != b.uuid {
37✔
244
                            return false;
×
245
                        }
37✔
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
                    }
257
                    _ => return false,
34✔
258
                },
259
                (None, None) => return true,
381✔
260
                _ => return false,
×
261
            }
262
        }
263
    }
416✔
264
}
265

266
/// A private iterator over the [Expr] nodes of an expression
267
/// by reference.
268
///
269
/// The first node reference returned is the [Expr] itself.
270
struct ExprIterator<'a> {
271
    stack: Vec<&'a Expr>,
272
}
273

274
impl<'a> Iterator for ExprIterator<'a> {
275
    type Item = ExprRef<'a>;
276

277
    fn next(&mut self) -> Option<Self::Item> {
33,757✔
278
        let expr = self.stack.pop()?;
33,757✔
279
        match expr {
24,602✔
280
            Expr::Unary(u) => {
610✔
281
                self.stack.push(&u.operand);
610✔
282
            }
610✔
283
            Expr::Binary(b) => {
7,318✔
284
                self.stack.push(&b.left);
7,318✔
285
                self.stack.push(&b.right);
7,318✔
286
            }
7,318✔
287
            Expr::Cast(c) => self.stack.push(&c.operand),
148✔
288
            Expr::Value(_) => {}
9,487✔
289
            Expr::Var(_) => {}
6,935✔
290
            Expr::Stretch(_) => {}
78✔
291
            Expr::Index(i) => {
26✔
292
                self.stack.push(&i.index);
26✔
293
                self.stack.push(&i.target);
26✔
294
            }
26✔
NEW
295
            Expr::Range(r) => {
×
NEW
296
                self.stack.push(&r.stop);
×
NEW
297
                self.stack.push(&r.start);
×
NEW
298
                self.stack.push(&r.step);
×
NEW
299
            }
×
300
        }
301
        Some(expr.as_ref())
24,602✔
302
    }
33,757✔
303
}
304

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

308
impl<'a> Iterator for VarIterator<'a> {
309
    type Item = &'a Var;
310

311
    fn next(&mut self) -> Option<Self::Item> {
14,580✔
312
        for expr in self.0.by_ref() {
21,694✔
313
            if let ExprRef::Var(v) = expr {
21,694✔
314
                return Some(v);
6,189✔
315
            }
15,505✔
316
        }
317
        None
8,391✔
318
    }
14,580✔
319
}
320

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

324
impl<'a> Iterator for IdentIterator<'a> {
325
    type Item = IdentifierRef<'a>;
326

327
    fn next(&mut self) -> Option<Self::Item> {
4✔
328
        for expr in self.0.by_ref() {
7✔
329
            if let ExprRef::Var(v) = expr {
7✔
330
                return Some(IdentifierRef::Var(v));
1✔
331
            }
6✔
332
            if let ExprRef::Stretch(s) = expr {
6✔
333
                return Some(IdentifierRef::Stretch(s));
2✔
334
            }
4✔
335
        }
336
        None
1✔
337
    }
4✔
338
}
339

340
impl From<Unary> for Expr {
341
    fn from(value: Unary) -> Self {
2✔
342
        Expr::Unary(Box::new(value))
2✔
343
    }
2✔
344
}
345

346
impl From<Box<Unary>> for Expr {
347
    fn from(value: Box<Unary>) -> Self {
×
348
        Expr::Unary(value)
×
349
    }
×
350
}
351

352
impl From<Binary> for Expr {
353
    fn from(value: Binary) -> Self {
11✔
354
        Expr::Binary(Box::new(value))
11✔
355
    }
11✔
356
}
357

358
impl From<Box<Binary>> for Expr {
359
    fn from(value: Box<Binary>) -> Self {
×
360
        Expr::Binary(value)
×
361
    }
×
362
}
363

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

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

376
impl From<Value> for Expr {
377
    fn from(value: Value) -> Self {
16✔
378
        Expr::Value(value)
16✔
379
    }
16✔
380
}
381

382
impl From<Var> for Expr {
383
    fn from(value: Var) -> Self {
6✔
384
        Expr::Var(value)
6✔
385
    }
6✔
386
}
387

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

394
impl From<Index> for Expr {
395
    fn from(value: Index) -> Self {
×
396
        Expr::Index(Box::new(value))
×
397
    }
×
398
}
399

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

406
impl From<Range> for Expr {
NEW
407
    fn from(value: Range) -> Self {
×
NEW
408
        Expr::Range(Box::new(value))
×
NEW
409
    }
×
410
}
411

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

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

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

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

474
impl<'py> IntoPyObject<'py> for Expr {
475
    type Target = PyAny;
476
    type Output = Bound<'py, PyAny>;
477
    type Error = PyErr;
478

479
    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
8,612✔
480
        match self {
8,612✔
481
            Expr::Unary(u) => u.into_bound_py_any(py),
192✔
482
            Expr::Binary(b) => b.into_bound_py_any(py),
2,242✔
483
            Expr::Cast(c) => c.into_bound_py_any(py),
98✔
484
            Expr::Value(v) => v.into_bound_py_any(py),
3,004✔
485
            Expr::Var(v) => v.into_bound_py_any(py),
2,864✔
486
            Expr::Stretch(s) => s.into_bound_py_any(py),
192✔
487
            Expr::Index(i) => i.into_bound_py_any(py),
20✔
NEW
488
            Expr::Range(r) => r.into_bound_py_any(py),
×
489
        }
490
    }
8,612✔
491
}
492

493
impl<'a, 'py> FromPyObject<'a, 'py> for Expr {
494
    type Error = PyErr;
495

496
    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
14,888✔
497
        let expr: PyRef<'_, PyExpr> = ob.cast()?.borrow();
14,888✔
498
        match expr.0 {
14,674✔
499
            ExprKind::Unary => Ok(Expr::Unary(Box::new(ob.extract()?))),
392✔
500
            ExprKind::Binary => Ok(Expr::Binary(Box::new(ob.extract()?))),
2,702✔
501
            ExprKind::Value => Ok(Expr::Value(ob.extract()?)),
5,368✔
502
            ExprKind::Var => Ok(Expr::Var(ob.extract()?)),
5,840✔
503
            ExprKind::Cast => Ok(Expr::Cast(Box::new(ob.extract()?))),
152✔
504
            ExprKind::Stretch => Ok(Expr::Stretch(ob.extract()?)),
192✔
505
            ExprKind::Index => Ok(Expr::Index(Box::new(ob.extract()?))),
28✔
NEW
506
            ExprKind::Range => Ok(Expr::Range(Box::new(ob.extract()?))),
×
507
        }
508
    }
14,888✔
509
}
510

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

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

549
        let vars: Vec<&Var> = expr.vars().collect();
1✔
550
        assert!(matches!(
1✔
551
            vars.as_slice(),
1✔
552
            [Var::Bit { .. }, Var::Standalone { .. }]
1✔
553
        ));
554
    }
1✔
555

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

594
        let identifiers: Vec<IdentifierRef> = expr.identifiers().collect();
1✔
595
        assert!(matches!(
1✔
596
            identifiers.as_slice(),
1✔
597
            [
1✔
598
                IdentifierRef::Stretch(Stretch { .. }),
1✔
599
                IdentifierRef::Stretch(Stretch { .. }),
1✔
600
                IdentifierRef::Var(Var::Standalone { .. }),
1✔
601
            ]
1✔
602
        ));
603
    }
1✔
604

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

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

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

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

742
        expr.visit_mut(|x| {
7✔
743
            assert!(order.next().unwrap()(&x));
7✔
744
            Ok(())
7✔
745
        })?;
7✔
746

747
        assert!(order.next().is_none());
1✔
748
        Ok(())
1✔
749
    }
1✔
750

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

777
        expr.visit_mut(|x| match x {
1✔
778
            ExprRefMut::Var(Var::Standalone { name, .. }) => {
1✔
779
                *name = "updated".to_string();
1✔
780
                Ok(())
1✔
781
            }
782
            _ => Ok(()),
3✔
783
        })?;
4✔
784

785
        let Var::Standalone { name, .. } = expr.vars().next().unwrap() else {
1✔
786
            panic!("wrong var type")
×
787
        };
788
        assert_eq!(name.as_str(), "updated");
1✔
789
        Ok(())
1✔
790
    }
1✔
791

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

931
        for expr in exprs.iter() {
10✔
932
            assert!(expr.structurally_equivalent(expr));
10✔
933
        }
934

935
        Ok(())
1✔
936
    }
1✔
937

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

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

988
            let cis = Expr::Binary(
17✔
989
                Binary {
17✔
990
                    op,
17✔
991
                    left: left.clone(),
17✔
992
                    right: right.clone(),
17✔
993
                    ty: out_ty,
17✔
994
                    constant: false,
17✔
995
                }
17✔
996
                .into(),
17✔
997
            );
17✔
998

999
            let trans = Expr::Binary(
17✔
1000
                Binary {
17✔
1001
                    op,
17✔
1002
                    left: right,
17✔
1003
                    right: left,
17✔
1004
                    ty: out_ty,
17✔
1005
                    constant: false,
17✔
1006
                }
17✔
1007
                .into(),
17✔
1008
            );
17✔
1009

1010
            assert!(
17✔
1011
                !cis.structurally_equivalent(&trans),
17✔
1012
                "Expected {op:?} to not be structurally equivalent to its flipped form"
1013
            );
1014
            assert!(
17✔
1015
                !trans.structurally_equivalent(&cis),
17✔
1016
                "Expected flipped {op:?} to not be structurally equivalent to original form"
1017
            );
1018
        }
1019
    }
1✔
1020

1021
    #[test]
1022
    fn test_structurally_eq_key_function_both() -> PyResult<()> {
1✔
1023
        let left_clbit = ShareableClbit::new_anonymous();
1✔
1024
        let left_cr = ClassicalRegister::new_owning("a", 3);
1✔
1025
        let right_clbit = ShareableClbit::new_anonymous();
1✔
1026
        let right_cr = ClassicalRegister::new_owning("b", 3);
1✔
1027
        assert_ne!(left_clbit, right_clbit);
1✔
1028
        assert_ne!(left_cr, right_cr);
1✔
1029

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

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

1102
        assert!(
1✔
1103
            !left.structurally_equivalent(&right),
1✔
1104
            "Expressions using different registers/clbits should not be structurally equivalent"
1105
        );
1106

1107
        // We're happy as long as the variables are of the same kind.
1108
        let key_func = |v: &Var| -> &str {
4✔
1109
            match v {
4✔
1110
                Var::Standalone { .. } => "standalone",
×
1111
                Var::Bit { .. } => "bit",
2✔
1112
                Var::Register { .. } => "register",
2✔
1113
            }
1114
        };
4✔
1115

1116
        assert!(
1✔
1117
            left.structurally_equivalent_by_key(key_func, &right, key_func),
1✔
1118
            "Expressions that only care that their vars are of the same kind should be equivalent"
1119
        );
1120

1121
        Ok(())
1✔
1122
    }
1✔
1123
}
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