haloumi-ir 0.5.3

Intermediate representation of the haloumi framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Structs for representing statements of the circuit's logic.

use super::expr::IRBexpr;
use crate::{
    diagnostics::{Diagnostic, Validation},
    error::Error,
    expr::{ExprProperties, IRAexpr, IRConstBexpr},
    meta::{HasMeta, Meta},
    printer::IRPrintable,
    traits::{Canonicalize, ConstantFolding, Evaluate, Validatable},
};
use eqv::{EqvRelation, equiv};
use haloumi_core::{cmp::CmpOp, eqv::SymbolicEqv, slot::Slot};
use haloumi_lowering::{
    Lowering,
    lowerable::{LowerableExpr, LowerableStmt},
    lowering_err,
};
use std::fmt::Write;

mod assert;
mod assume_determ;
mod call;
mod comment;
mod cond_block;
mod constraint;
mod post_cond;
mod seq;

use assert::Assert;
use assume_determ::AssumeDeterministic;
use call::Call;
use comment::Comment;
use cond_block::CondBlock;
use constraint::Constraint;
use post_cond::PostCond;
use seq::Seq;

mod sealed {
    pub trait EmitIfSealed {}
}

/// Trait that enables wrapping IR statements into conditionally emitted blocks.
pub trait EmitIf<T>: sealed::EmitIfSealed {
    /// Creates a conditional block.
    fn emit_if(self, cond: IRConstBexpr<T>) -> IRStmt<T>;
}

impl<T, I> EmitIf<T> for I
where
    I: IntoIterator<Item = IRStmt<T>>,
{
    fn emit_if(self, cond: IRConstBexpr<T>) -> IRStmt<T> {
        CondBlock::new(cond, self.into_iter().collect()).into()
    }
}
impl<T, I> sealed::EmitIfSealed for I where I: IntoIterator<Item = IRStmt<T>> {}

/// IR for operations that occur in the main circuit.
pub struct IRStmt<T>(IRStmtImpl<T>, Meta);

enum IRStmtImpl<T> {
    /// A call to another module.
    ConstraintCall(Call<T>),
    /// A constraint between two expressions.
    Constraint(Constraint<T>),
    /// A text comment.
    Comment(Comment),
    /// Indicates that a [`Slot`] must be assumed deterministic by the backend.
    AssumeDeterministic(AssumeDeterministic),
    /// A constraint that a [`IRBexpr`] must be true.
    Assert(Assert<T>),
    /// A sequence of statements.
    Seq(Seq<T>),
    /// A post-condition expression.
    PostCond(PostCond<T>),
    /// A conditionally emitted block.
    CondBlock(CondBlock<T>),
}

impl<T> HasMeta for IRStmt<T> {
    fn meta(&self) -> &Meta {
        &self.1
    }

    fn meta_mut(&mut self) -> &mut Meta {
        &mut self.1
    }
}

impl<T: PartialEq> PartialEq for IRStmt<T> {
    /// Equality is defined by the sequence of statements regardless of how they are structured
    /// inside.
    ///
    /// For example:
    ///     Seq([a, Seq([b, c])]) == Seq([a, b, c])
    ///     a == Seq([a])
    fn eq(&self, other: &Self) -> bool {
        std::iter::zip(self.iter(), other.iter()).all(|(lhs, rhs)| match (&lhs.0, &rhs.0) {
            (IRStmtImpl::ConstraintCall(lhs), IRStmtImpl::ConstraintCall(rhs)) => lhs.eq(rhs),
            (IRStmtImpl::Constraint(lhs), IRStmtImpl::Constraint(rhs)) => lhs.eq(rhs),
            (IRStmtImpl::Comment(lhs), IRStmtImpl::Comment(rhs)) => lhs.eq(rhs),
            (IRStmtImpl::AssumeDeterministic(lhs), IRStmtImpl::AssumeDeterministic(rhs)) => {
                lhs.eq(rhs)
            }
            (IRStmtImpl::Assert(lhs), IRStmtImpl::Assert(rhs)) => lhs.eq(rhs),
            (IRStmtImpl::PostCond(lhs), IRStmtImpl::PostCond(rhs)) => lhs.eq(rhs),
            (IRStmtImpl::CondBlock(lhs), IRStmtImpl::CondBlock(rhs)) => lhs.eq(rhs),
            (IRStmtImpl::Seq(_), _) | (_, IRStmtImpl::Seq(_)) => unreachable!(),
            _ => false,
        })
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for IRStmt<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            IRStmtImpl::ConstraintCall(call) => write!(f, "{call:?}"),
            IRStmtImpl::Constraint(constraint) => write!(f, "{constraint:?}"),
            IRStmtImpl::Comment(comment) => write!(f, "{comment:?}"),
            IRStmtImpl::AssumeDeterministic(assume_deterministic) => {
                write!(f, "{assume_deterministic:?}")
            }
            IRStmtImpl::Assert(assert) => write!(f, "{assert:?}"),
            IRStmtImpl::PostCond(pc) => write!(f, "{pc:?}"),
            IRStmtImpl::CondBlock(cb) => write!(f, "{cb:?}"),
            IRStmtImpl::Seq(seq) => write!(f, "{seq:?}"),
        }
    }
}

impl<T> IRStmt<T> {
    /// Creates a call to another module.
    pub fn call(
        callee: impl AsRef<str>,
        inputs: impl IntoIterator<Item = T>,
        outputs: impl IntoIterator<Item = Slot>,
    ) -> Self {
        Call::new(callee, inputs, outputs).into()
    }

    /// Creates a post condition formula.
    pub fn post_cond(cond: IRBexpr<T>) -> Self {
        PostCond::new(cond).into()
    }

    /// Creates a constraint between two expressions.
    pub fn constraint(op: CmpOp, lhs: T, rhs: T) -> Self {
        Constraint::new(op, lhs, rhs).into()
    }

    #[inline]
    /// Creates a constraint with [`CmpOp::Eq`] between two expressions.
    pub fn eq(lhs: T, rhs: T) -> Self {
        Self::constraint(CmpOp::Eq, lhs, rhs)
    }

    #[inline]
    /// Creates a constraint with [`CmpOp::Lt`] between two expressions.
    pub fn lt(lhs: T, rhs: T) -> Self {
        Self::constraint(CmpOp::Lt, lhs, rhs)
    }

    #[inline]
    /// Creates a constraint with [`CmpOp::Le`] between two expressions.
    pub fn le(lhs: T, rhs: T) -> Self {
        Self::constraint(CmpOp::Le, lhs, rhs)
    }

    #[inline]
    /// Creates a constraint with [`CmpOp::Gt`] between two expressions.
    pub fn gt(lhs: T, rhs: T) -> Self {
        Self::constraint(CmpOp::Gt, lhs, rhs)
    }

    #[inline]
    /// Creates a constraint with [`CmpOp::Ge`] between two expressions.
    pub fn ge(lhs: T, rhs: T) -> Self {
        Self::constraint(CmpOp::Ge, lhs, rhs)
    }

    /// Creates a text comment.
    pub fn comment(s: impl AsRef<str>) -> Self {
        Comment::new(s).into()
    }

    /// Indicates that the [`Slot`] must be assumed deterministic by the backend.
    pub fn assume_deterministic(f: impl Into<Slot>) -> Self {
        AssumeDeterministic::new(f.into()).into()
    }

    /// Creates an assertion in the circuit.
    pub fn assert(cond: IRBexpr<T>) -> Self {
        Assert::new(cond).into()
    }

    /// Creates a statement that is a sequence of other statements.
    pub fn seq<I>(stmts: impl IntoIterator<Item = IRStmt<I>>) -> Self
    where
        I: Into<T>,
    {
        Seq::new(stmts).into()
    }

    /// Creates an empty statement.
    pub fn empty() -> Self {
        Seq::empty().into()
    }

    /// Returns true if the statement is empty.
    pub fn is_empty(&self) -> bool {
        match &self.0 {
            IRStmtImpl::Seq(s) => s.is_empty(),
            _ => false,
        }
    }

    /// Transforms the inner expression type into another.
    pub fn map<O>(self, f: &mut impl FnMut(T) -> O) -> IRStmt<O> {
        match self.0 {
            IRStmtImpl::ConstraintCall(call) => call.map(f).into(),
            IRStmtImpl::Constraint(constraint) => constraint.map(f).into(),
            IRStmtImpl::Comment(comment) => Comment::new(comment.value()).into(),
            IRStmtImpl::AssumeDeterministic(ad) => AssumeDeterministic::new(ad.value()).into(),
            IRStmtImpl::Assert(assert) => assert.map(f).into(),
            IRStmtImpl::PostCond(pc) => pc.map(f).into(),
            IRStmtImpl::CondBlock(cb) => cb.map(f).into(),
            IRStmtImpl::Seq(seq) => Seq::new(seq.into_iter().map(|s| s.map(f))).into(),
        }
    }

    /// Maps the statement's inner type to a tuple with the passed value.
    pub fn with<O>(self, other: O) -> IRStmt<(O, T)>
    where
        O: Clone,
    {
        self.map(&mut |t| (other.clone(), t))
    }

    /// Maps the statement's inner type to a tuple with the result of the closure.
    pub fn with_fn<O>(self, other: impl Fn() -> O) -> IRStmt<(O, T)> {
        self.map(&mut |t| (other(), t))
    }

    /// Transforms the inner expression type using [`Into::into`].
    pub fn into<O>(self) -> IRStmt<O>
    where
        O: From<T> + Evaluate<ExprProperties>,
    {
        self.map(&mut Into::into)
    }

    /// Transforms the inner expression type using [`From::from`].
    pub fn from<O>(value: IRStmt<O>) -> Self
    where
        O: Into<T>,
    {
        value.map(&mut Into::into)
    }

    /// Appends the given statement to the current one.
    pub fn then(self, other: impl Into<Self>) -> Self {
        match self.0 {
            IRStmtImpl::Seq(mut seq) => {
                seq.push(other.into());
                seq.into()
            }
            this => Seq::new([Self(this, self.1), other.into()]).into(),
        }
    }

    /// Transforms the inner expression type into another, without moving.
    pub fn map_into<O>(&self, f: &mut impl FnMut(&T) -> O) -> IRStmt<O> {
        match &self.0 {
            IRStmtImpl::ConstraintCall(call) => call.map_into(f).into(),
            IRStmtImpl::Constraint(constraint) => constraint.map_into(f).into(),
            IRStmtImpl::Comment(comment) => Comment::new(comment.value()).into(),
            IRStmtImpl::AssumeDeterministic(ad) => AssumeDeterministic::new(ad.value()).into(),
            IRStmtImpl::Assert(assert) => assert.map_into(f).into(),
            IRStmtImpl::PostCond(pc) => pc.map_into(f).into(),
            IRStmtImpl::CondBlock(cb) => cb.map_into(f).into(),
            IRStmtImpl::Seq(seq) => Seq::new(seq.iter().map(|s| s.map_into(f))).into(),
        }
    }

    /// Tries to transform the inner expression type into another.
    pub fn try_map<O, E>(self, f: &mut impl FnMut(T) -> Result<O, E>) -> Result<IRStmt<O>, E> {
        Ok(match self.0 {
            IRStmtImpl::ConstraintCall(call) => call.try_map(f)?.into(),
            IRStmtImpl::Constraint(constraint) => constraint.try_map(f)?.into(),
            IRStmtImpl::Comment(comment) => Comment::new(comment.value()).into(),
            IRStmtImpl::AssumeDeterministic(ad) => AssumeDeterministic::new(ad.value()).into(),
            IRStmtImpl::Assert(assert) => assert.try_map(f)?.into(),
            IRStmtImpl::PostCond(pc) => pc.try_map(f)?.into(),
            IRStmtImpl::CondBlock(cb) => cb.try_map(f)?.into(),
            IRStmtImpl::Seq(seq) => Seq::new(
                seq.into_iter()
                    .map(|s| s.try_map(f))
                    .collect::<Result<Vec<_>, _>>()?,
            )
            .into(),
        })
    }

    /// Modifies the inner expression type in place.
    pub fn map_inplace(&mut self, f: &mut impl FnMut(&mut T)) {
        match &mut self.0 {
            IRStmtImpl::ConstraintCall(call) => call.map_inplace(f),
            IRStmtImpl::Constraint(constraint) => constraint.map_inplace(f),
            IRStmtImpl::Assert(assert) => assert.map_inplace(f),
            IRStmtImpl::PostCond(pc) => pc.map_inplace(f),
            IRStmtImpl::CondBlock(cb) => cb.map_inplace(f),
            IRStmtImpl::Seq(seq) => seq.iter_mut().for_each(|stmt| stmt.map_inplace(f)),
            _ => {}
        }
    }

    /// Tries to modify the inner expression type in place.
    pub fn try_map_inplace<E>(
        &mut self,
        f: &mut impl FnMut(&mut T) -> Result<(), E>,
    ) -> Result<(), E> {
        match &mut self.0 {
            IRStmtImpl::ConstraintCall(call) => call.try_map_inplace(f),
            IRStmtImpl::Constraint(constraint) => constraint.try_map_inplace(f),
            IRStmtImpl::Assert(assert) => assert.try_map_inplace(f),
            IRStmtImpl::PostCond(pc) => pc.try_map_inplace(f),
            IRStmtImpl::CondBlock(cb) => cb.try_map_inplace(f),
            IRStmtImpl::Seq(seq) => seq.iter_mut().try_for_each(|stmt| stmt.try_map_inplace(f)),
            _ => Ok(()),
        }
    }

    /// Modifies the inner slots in place.
    pub fn map_slot_inplace(&mut self, f: &mut impl FnMut(&mut Slot)) {
        match &mut self.0 {
            IRStmtImpl::ConstraintCall(call) => call.outputs_mut().iter_mut().for_each(f),
            IRStmtImpl::AssumeDeterministic(det) => f(det.value_mut()),
            IRStmtImpl::Seq(seq) => seq.iter_mut().for_each(|stmt| stmt.map_slot_inplace(f)),
            _ => {}
        }
    }

    /// Tries to modify the inner slots n place.
    pub fn try_map_slot_inplace<E>(
        &mut self,
        f: &mut impl FnMut(&mut Slot) -> Result<(), E>,
    ) -> Result<(), E> {
        match &mut self.0 {
            IRStmtImpl::ConstraintCall(call) => call.outputs_mut().iter_mut().try_for_each(f),
            IRStmtImpl::AssumeDeterministic(det) => f(det.value_mut()),
            IRStmtImpl::Seq(seq) => seq
                .iter_mut()
                .try_for_each(|stmt| stmt.try_map_slot_inplace(f)),
            _ => Ok(()),
        }
    }

    /// Returns an iterator of references to the statements.
    pub fn iter(&self) -> IRStmtRefIter<'_, T> {
        IRStmtRefIter { stack: vec![self] }
    }

    /// Returns an iterator of mutable references to the statements.
    pub fn iter_mut(&mut self) -> IRStmtRefMutIter<'_, T> {
        IRStmtRefMutIter { stack: vec![self] }
    }

    /// Propagates the metadata of this statement to the inner statements.
    pub fn propagate_meta(&mut self) {
        match &mut self.0 {
            IRStmtImpl::Seq(s) => {
                for stmt in s.iter_mut() {
                    stmt.meta_mut().complete_with(self.1);
                }
            }
            _ => {}
        }
    }
}

impl<T> ConstantFolding for IRStmt<T>
where
    T: ConstantFolding + std::fmt::Debug + Clone,
    Error: From<T::Error>,
    T::T: Eq + Ord,
{
    type Error = Error;
    type T = ();

    /// Folds the statements if the expressions are constant.
    /// If a assert-like statement folds into a tautology (i.e. `(= 0 0 )`) gets removed. If it
    /// folds into a unsatisfiable proposition the method returns an error.
    fn constant_fold(&mut self) -> Result<(), Error> {
        match &mut self.0 {
            IRStmtImpl::ConstraintCall(call) => call.constant_fold()?,
            IRStmtImpl::Constraint(constraint) => {
                if let Some(replacement) = constraint.constant_fold(self.1)? {
                    *self = replacement;
                }
            }
            IRStmtImpl::Comment(_) => {}
            IRStmtImpl::AssumeDeterministic(_) => {}
            IRStmtImpl::Assert(assert) => {
                if let Some(replacement) = assert.constant_fold(self.1)? {
                    *self = replacement;
                }
            }
            IRStmtImpl::PostCond(pc) => {
                if let Some(replacement) = pc.constant_fold(self.1)? {
                    *self = replacement;
                }
            }
            IRStmtImpl::CondBlock(cb) => {
                if let Some(replacement) = cb.constant_fold()? {
                    *self = replacement;
                }
            }
            IRStmtImpl::Seq(seq) => seq.constant_fold()?,
        }
        Ok(())
    }
}

impl Canonicalize for IRStmt<IRAexpr> {
    /// Matches the statements against a series of known patterns and applies rewrites if able to.
    fn canonicalize(&mut self) {
        match &mut self.0 {
            IRStmtImpl::ConstraintCall(call) => call.canonicalize(),
            IRStmtImpl::Constraint(constraint) => constraint.canonicalize(),
            IRStmtImpl::Comment(_) => {}
            IRStmtImpl::AssumeDeterministic(_) => {}
            IRStmtImpl::Assert(assert) => assert.canonicalize(),
            IRStmtImpl::PostCond(pc) => pc.canonicalize(),
            IRStmtImpl::CondBlock(cb) => cb.canonicalize(),
            IRStmtImpl::Seq(seq) => seq.canonicalize(),
        }
    }
}

impl<T, D> Validatable for IRStmt<T>
where
    IRConstBexpr<T>: Validatable<Diagnostic = D, Context = ()>,
    D: Diagnostic,
{
    type Diagnostic = D;

    type Context = ();

    fn validate_with_context(
        &self,
        _: &Self::Context,
    ) -> Result<Vec<Self::Diagnostic>, Vec<Self::Diagnostic>> {
        match &self.0 {
            IRStmtImpl::Seq(seq) => {
                let mut validation = Validation::new();
                for stmt in seq.iter() {
                    validation.append_from_result(stmt.validate(), "");
                }
                validation.into()
            }
            IRStmtImpl::CondBlock(cond_block) => cond_block.validate(),
            _ => Validation::new().into(),
        }
    }
}

/// IRStmt transilitively inherits the [`SymbolicEqv`] equivalence relation.
impl<L, R> EqvRelation<IRStmt<L>, IRStmt<R>> for SymbolicEqv
where
    SymbolicEqv: EqvRelation<L, R> + EqvRelation<Slot, Slot>,
{
    /// Two statements are equivalent if they are structurally equal and their inner entities
    /// are equivalent.
    fn equivalent(lhs: &IRStmt<L>, rhs: &IRStmt<R>) -> bool {
        std::iter::zip(lhs.iter(), rhs.iter()).all(|(lhs, rhs)| match (&lhs.0, &rhs.0) {
            (IRStmtImpl::ConstraintCall(lhs), IRStmtImpl::ConstraintCall(rhs)) => {
                equiv! { SymbolicEqv | lhs, rhs }
            }
            (IRStmtImpl::Constraint(lhs), IRStmtImpl::Constraint(rhs)) => {
                equiv! { SymbolicEqv | lhs, rhs }
            }
            (IRStmtImpl::Comment(_), IRStmtImpl::Comment(_)) => true,
            (IRStmtImpl::AssumeDeterministic(lhs), IRStmtImpl::AssumeDeterministic(rhs)) => {
                equiv! { SymbolicEqv | lhs, rhs }
            }
            (IRStmtImpl::Assert(lhs), IRStmtImpl::Assert(rhs)) => {
                equiv! { SymbolicEqv | lhs, rhs }
            }
            (IRStmtImpl::PostCond(lhs), IRStmtImpl::PostCond(rhs)) => {
                equiv! { SymbolicEqv | lhs, rhs }
            }
            (IRStmtImpl::CondBlock(lhs), IRStmtImpl::CondBlock(rhs)) => {
                equiv! { SymbolicEqv | lhs, rhs }
            }
            (IRStmtImpl::Seq(_), _) | (_, IRStmtImpl::Seq(_)) => unreachable!(),
            _ => false,
        })
    }
}

/// Iterator over references.
#[derive(Debug)]
pub struct IRStmtRefIter<'a, T> {
    stack: Vec<&'a IRStmt<T>>,
}

impl<'a, T> Iterator for IRStmtRefIter<'a, T> {
    type Item = &'a IRStmt<T>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(node) = self.stack.pop() {
            match &node.0 {
                IRStmtImpl::Seq(children) => {
                    // Reverse to preserve left-to-right order
                    self.stack.extend(children.iter().rev());
                }
                _ => return Some(node),
            }
        }
        None
    }
}

/// Iterator over mutable references.
#[derive(Debug)]
pub struct IRStmtRefMutIter<'a, T> {
    stack: Vec<&'a mut IRStmt<T>>,
}

impl<'a, T> Iterator for IRStmtRefMutIter<'a, T> {
    type Item = &'a mut IRStmt<T>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(node) = self.stack.pop() {
            if let IRStmt(IRStmtImpl::Seq(children), _) = node {
                // Reverse to preserve left-to-right order
                self.stack.extend(children.iter_mut().rev());
            } else {
                return Some(node);
            }
        }
        None
    }
}

impl<T> Default for IRStmt<T> {
    fn default() -> Self {
        Self::empty()
    }
}

/// Iterator of statements.
#[derive(Debug)]
pub struct IRStmtIter<T> {
    stack: Vec<IRStmt<T>>,
}

impl<T> Iterator for IRStmtIter<T> {
    type Item = IRStmt<T>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(node) = self.stack.pop() {
            match node {
                IRStmt(IRStmtImpl::Seq(children), _) => {
                    // Reverse to preserve left-to-right order
                    self.stack.extend(children.into_iter().rev());
                }
                stmt => return Some(stmt),
            }
        }
        None
    }
}

impl<T> IntoIterator for IRStmt<T> {
    type Item = Self;

    type IntoIter = IRStmtIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        IRStmtIter { stack: vec![self] }
    }
}

impl<'a, T> IntoIterator for &'a IRStmt<T> {
    type Item = Self;

    type IntoIter = IRStmtRefIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut IRStmt<T> {
    type Item = Self;

    type IntoIter = IRStmtRefMutIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<I> FromIterator<IRStmt<I>> for IRStmt<I> {
    fn from_iter<T: IntoIterator<Item = IRStmt<I>>>(iter: T) -> Self {
        Self::seq(iter)
    }
}

impl<T> From<Call<T>> for IRStmt<T> {
    fn from(value: Call<T>) -> Self {
        Self(IRStmtImpl::ConstraintCall(value), Default::default())
    }
}
impl<T> From<Constraint<T>> for IRStmt<T> {
    fn from(value: Constraint<T>) -> Self {
        Self(IRStmtImpl::Constraint(value), Default::default())
    }
}
impl<T> From<Comment> for IRStmt<T> {
    fn from(value: Comment) -> Self {
        Self(IRStmtImpl::Comment(value), Default::default())
    }
}
impl<T> From<AssumeDeterministic> for IRStmt<T> {
    fn from(value: AssumeDeterministic) -> Self {
        Self(IRStmtImpl::AssumeDeterministic(value), Default::default())
    }
}
impl<T> From<Assert<T>> for IRStmt<T> {
    fn from(value: Assert<T>) -> Self {
        Self(IRStmtImpl::Assert(value), Default::default())
    }
}
impl<T> From<PostCond<T>> for IRStmt<T> {
    fn from(value: PostCond<T>) -> Self {
        Self(IRStmtImpl::PostCond(value), Default::default())
    }
}
impl<T> From<CondBlock<T>> for IRStmt<T> {
    fn from(value: CondBlock<T>) -> Self {
        Self(IRStmtImpl::CondBlock(value), Default::default())
    }
}
impl<T> From<Seq<T>> for IRStmt<T> {
    fn from(value: Seq<T>) -> Self {
        Self(IRStmtImpl::Seq(value), Default::default())
    }
}

/// Error raised while lowering if the lowered statement was a conditionally emitted block what was
/// not resolved yet.
#[derive(Debug)]
pub struct UnresolvedCondBlockError;

impl std::fmt::Display for UnresolvedCondBlockError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "attempted to lower an unresolved conditionally emitted block"
        )
    }
}

impl std::error::Error for UnresolvedCondBlockError where Self: std::fmt::Debug {}

impl<T: LowerableExpr> LowerableStmt for IRStmt<T> {
    fn lower<L>(self, l: &L) -> haloumi_lowering::Result<()>
    where
        L: Lowering + ?Sized,
    {
        match self.0 {
            IRStmtImpl::ConstraintCall(call) => call.lower(l),
            IRStmtImpl::Constraint(constraint) => constraint.lower(l),
            IRStmtImpl::Comment(comment) => comment.lower(l),
            IRStmtImpl::AssumeDeterministic(ad) => ad.lower(l),
            IRStmtImpl::Assert(assert) => assert.lower(l),
            IRStmtImpl::PostCond(pc) => pc.lower(l),
            IRStmtImpl::CondBlock(_) => Err(lowering_err!(UnresolvedCondBlockError)),
            IRStmtImpl::Seq(seq) => seq.lower(l),
        }
    }
}

impl<T: Clone> Clone for IRStmt<T> {
    fn clone(&self) -> Self {
        match &self.0 {
            IRStmtImpl::ConstraintCall(call) => call.clone().into(),
            IRStmtImpl::Constraint(c) => c.clone().into(),
            IRStmtImpl::Comment(c) => c.clone().into(),
            IRStmtImpl::AssumeDeterministic(func_io) => func_io.clone().into(),
            IRStmtImpl::Assert(e) => e.clone().into(),
            IRStmtImpl::PostCond(e) => e.clone().into(),
            IRStmtImpl::CondBlock(e) => e.clone().into(),
            IRStmtImpl::Seq(stmts) => stmts.clone().into(),
        }
    }
}

impl<T: IRPrintable> IRPrintable for IRStmt<T> {
    fn fmt(&self, ctx: &mut crate::printer::IRPrinterCtx<'_, '_>) -> crate::printer::Result {
        match &self.0 {
            IRStmtImpl::ConstraintCall(call) => {
                ctx.fmt_call(call.callee(), call.inputs(), call.outputs(), None)
            }
            IRStmtImpl::Constraint(constraint) => {
                ctx.block(format!("assert/{}", constraint.op()).as_str(), |ctx| {
                    if constraint.lhs().depth() > 1 {
                        ctx.nl()?;
                    }
                    constraint.lhs().fmt(ctx)?;
                    if constraint.lhs().depth() > 1 || constraint.rhs().depth() > 1 {
                        ctx.nl()?;
                    }
                    constraint.rhs().fmt(ctx)
                })
            }
            IRStmtImpl::Comment(comment) => {
                ctx.nl()?;
                writeln!(ctx, "; {}", comment.value())
            }
            IRStmtImpl::AssumeDeterministic(assume_deterministic) => ctx
                .list_nl("assume-deterministic", |ctx| {
                    assume_deterministic.value().fmt(ctx)
                }),
            IRStmtImpl::Assert(assert) => ctx.block("assert", |ctx| assert.cond().fmt(ctx)),
            IRStmtImpl::Seq(seq) => {
                for stmt in seq.iter() {
                    stmt.fmt(ctx)?;
                }
                Ok(())
            }
            IRStmtImpl::CondBlock(cb) => ctx.block("emit-if", |ctx| {
                cb.cond().fmt(ctx)?;
                ctx.nl()?;
                cb.body().fmt(ctx)
            }),
            IRStmtImpl::PostCond(post_cond) => {
                ctx.block("post-cond", |ctx| post_cond.cond().fmt(ctx))
            }
        }
    }
}

/// Errors caused by failable map operations
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct TryMapError(#[from] Box<dyn std::error::Error>);

#[cfg(test)]
mod test;