deduxit 0.5.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! A goal of a first-order session handed to the search: written as a
//! sequent of its own, proved, and its derivation carried back onto the
//! session's instances.
//!
//! The goal's members are instances whose frames hold the session's
//! eigenvariables and open witnesses. The search gets one formula:
//! - It joins the goal's formulas by `⅋`, the hypotheses first and the
//!   succedent last, so that the intuitionistic reading takes each `⅋` as
//!   an implication.
//! - A prefix binds the open witnesses by `∃`, and the eigenvariables made
//!   after the first of them by `∀`, in the order they were made. So the
//!   search's eigenvariable condition matches the session's levels.
//! - The older eigenvariables, and those that are constants, become
//!   constant symbols of their own.
//!
//! A proof of that formula opens the prefix and splits the `⅋` spine
//! before anything else. Those steps are left out when the derivation
//! comes back. The prefix's witnesses bind the open witnesses, and its
//! eigenvariables are the session's. Every other eigenvariable of the proof
//! becomes a fresh one of the session (a constant where no `∀` step
//! introduces it).

use super::{Closed, GoalId, Interactive};
use crate::Error;
use crate::hash::HashMap;
use crate::limits::{Limits, Progress};
use crate::linear::occurrences::instances::{Terms, binders, eigen_names};
use crate::linear::occurrences::{Forest, Member, OccId};
use crate::linear::proofs::derivation::{Derivation, InfId, Inference, ViewOptions};
use crate::linear::proofs::{CheckError, Named, Node, Proof, Rule};
use crate::linear::search::{self, Options, Verdict};
use crate::linear::sequents::fo::{FirstOrder, Interner};
use crate::linear::sequents::{Atom, Eigen, FoTerm, FoTermId, Sequent, Symbol, Term, TermId};

/// What a variable of the goal is in the sequent written for the search.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Bound {
    /// The `∃` or `∀` of the prefix at this position, outermost first.
    Prefix(u32),
    /// A constant, by its symbol.
    Constant(Symbol),
}

/// The goal written as a sequent for the search, with what its
/// occurrences stand for in the session.
struct Written {
    /// The sequent.
    sequent: Sequent,
    /// The prefix, outermost binder first: the open witness an `∃` binds
    /// (`Ok`), or the eigenvariable a `∀` binds (`Err`).
    prefix: Vec<Result<u32, Eigen>>,
    /// The constant symbols that stand for eigenvariables.
    constants: HashMap<Symbol, Eigen>,
}

/// Where an occurrence of the written sequent stands in the session.
#[derive(Clone, Copy, Debug)]
enum Place {
    /// A binder of the prefix, above every formula of the goal.
    Prefix,
    /// The `⅋` joining the goal's formulas from this one on.
    Spine(usize),
    /// An occurrence inside the goal's formula of this index, at this
    /// offset from its root.
    Inside(usize, u32),
}

impl Interactive {
    /// Closes a goal of a first-order session by the search, as
    /// [`close`](Self::close) does.
    ///
    /// The outcome is the search's on the goal written as a sequent of its
    /// own. A proof is carried back and grafted as one step, which binds
    /// the open witnesses the proof filled.
    pub(super) fn close_framed(
        &mut self,
        goal: GoalId,
        options: &Options,
        view: &ViewOptions,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<Closed, Error> {
        let members = self.goal(goal)?.to_vec();
        let written = self.written(&members);
        let outcome =
            search::prove_within(&written.sequent, self.mode, options, limits, &mut stop)?;
        let mut grafted = Ok(());
        if let Verdict::Proved(proof) = &outcome.verdict {
            grafted = match self.carry_back(goal, &members, &written, proof, view, limits, stop) {
                Ok(()) => Ok(()),
                Err(Error::Refused(refusal)) => Err(refusal),
                Err(Error::Check(CheckError::Refused(refused))) => Err(refused.refusal),
                Err(error) => return Err(error),
            };
        }
        Ok(Closed { outcome, grafted })
    }

    /// Writes a goal of a first-order session as a sequent of its own.
    fn written(&self, members: &[Member]) -> Written {
        let q = self.fo.as_ref().expect("a first-order session");
        let forest = &self.forest;
        let fo = &forest.sequent().fo;
        // The goal's formulas, the hypotheses first in an intuitionistic
        // mode, and the variables their frames hold once bindings are
        // followed.
        let mut order: Vec<Member> = members.to_vec();
        if let Some(reading) = self.reading() {
            order.sort_by_key(|&m| {
                reading.position(self.occurrence(m)) == crate::linear::Side::Output
            });
        }
        let (mut eigens, mut metas) = (Vec::new(), Vec::new());
        for &m in &order {
            for t in q.frame_terms(q.instance(m).1) {
                let (e, k) = q.variables(forest, t);
                eigens.extend(e);
                metas.extend(k);
            }
        }
        eigens.sort_unstable();
        eigens.dedup();
        metas.sort_unstable_by_key(|&k| (q.metas[k as usize].level, k));
        metas.dedup();
        // The prefix, in the order the variables were made. An
        // eigenvariable at or past the first open witness's level is bound
        // by `∀` right before the first open witness of a higher level.
        // An older eigenvariable, or one that is a constant, becomes a
        // constant symbol.
        let first = metas.first().map(|&k| q.metas[k as usize].level);
        let mut prefix: Vec<Result<u32, Eigen>> = Vec::new();
        let mut placed: Vec<Eigen> = Vec::new();
        for &k in &metas {
            let level = q.metas[k as usize].level;
            for &a in &eigens {
                if a.get() < level
                    && first.is_some_and(|f| a.get() >= f)
                    && !q.constants.contains(&a)
                    && !placed.contains(&a)
                {
                    prefix.push(Err(a));
                    placed.push(a);
                }
            }
            prefix.push(Ok(k));
        }
        for &a in &eigens {
            if first.is_some_and(|f| a.get() >= f)
                && !q.constants.contains(&a)
                && !placed.contains(&a)
            {
                prefix.push(Err(a));
                placed.push(a);
            }
        }
        // The symbols: the sequent's, in their order and roles, then one
        // constant per eigenvariable that the prefix does not bind.
        let predicates: Vec<Symbol> = fo.atoms.iter().map(|&(p, _)| p).collect();
        let mut interner = Interner::new();
        for (i, (name, arity)) in fo.symbols.iter().enumerate() {
            let predicate = predicates.contains(&Symbol::new(i as u32));
            interner
                .symbol(name, *arity, predicate)
                .expect("the sequent's own symbols fit together");
        }
        let names = eigen_names(fo, &q.shown.eigenvariables());
        let mut bound: HashMap<Eigen, Bound> = HashMap::default();
        let mut constants: HashMap<Symbol, Eigen> = HashMap::default();
        for (j, p) in prefix.iter().enumerate() {
            if let &Err(a) = p {
                bound.insert(a, Bound::Prefix(j as u32));
            }
        }
        for &a in &eigens {
            if let std::collections::hash_map::Entry::Vacant(entry) = bound.entry(a) {
                let symbol = interner
                    .symbol(&names[&a], 0, false)
                    .expect("an eigenvariable's name is no symbol's");
                entry.insert(Bound::Constant(symbol));
                constants.insert(symbol, a);
            }
        }
        let metas_at: HashMap<u32, u32> = prefix
            .iter()
            .enumerate()
            .filter_map(|(j, p)| p.ok().map(|k| (k, j as u32)))
            .collect();
        let depth = prefix.len() as u32;
        let mut copy = Copy {
            forest,
            q,
            interner,
            terms: Vec::new(),
            atoms: Vec::new(),
            atom_of: HashMap::default(),
            fo_atoms: Vec::new(),
            binders: Vec::new(),
            bound,
            metas_at,
            depth,
            closed: HashMap::default(),
        };
        let mut formulas: Vec<TermId> = order.iter().map(|&m| copy.formula(m)).collect();
        // The spine: the hypotheses joined by `⅋`, the succedent last.
        // The empty goal of a classical mode has no formula, and so no
        // variable to bind.
        let root = formulas.pop().map(|last| {
            let mut root = last;
            while let Some(f) = formulas.pop() {
                root = copy.push(Term::Par(f, root));
            }
            for p in prefix.iter().rev() {
                root = copy.push(match p {
                    Ok(_) => Term::Exists(root),
                    Err(_) => Term::Forall(root),
                });
                let name = match p {
                    Ok(k) => format!("w_{k}"),
                    Err(a) => names[a].clone(),
                };
                copy.binders.push((root, name));
            }
            root
        });
        copy.binders.sort_unstable_by_key(|&(t, _)| t);
        let mut tables: FirstOrder = copy.interner.tables;
        tables.atoms = copy.fo_atoms;
        tables.binders = copy.binders;
        let sequent = Sequent {
            terms: copy.terms,
            roots: root.into_iter().collect(),
            atoms: copy.atoms,
            antecedents: Some(0),
            cuts: vec![],
            fo: tables,
        };
        #[cfg(any(test, feature = "parse", feature = "serialize"))]
        debug_assert!(sequent.check().is_ok(), "{:?}", sequent.check());
        Written {
            sequent,
            prefix,
            constants,
        }
    }

    /// Carries a proof of the written goal back onto the session.
    ///
    /// Its derivation, without the prefix's and the spine's steps and with
    /// every member made an instance of the session's, is grafted onto the
    /// goal as one step. The open witnesses that the prefix's `∃` steps
    /// filled are bound. A graft that fails leaves the session as it was.
    #[expect(clippy::too_many_arguments, reason = "close's own, and what it wrote")]
    fn carry_back(
        &mut self,
        goal: GoalId,
        members: &[Member],
        written: &Written,
        proof: &Proof,
        view: &ViewOptions,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<(), Error> {
        // The cast is exact: there are fewer steps than inferences, which
        // an `InfId` numbers.
        let step = self.history.len() as u32;
        let mark = self.fo.as_ref().expect("a first-order session").mark();
        let carried =
            self.carry_back_from(goal, members, written, proof, view, limits, &mut stop, step);
        let q = self.fo.as_mut().expect("a first-order session");
        match carried {
            Ok(()) => {
                q.made(step, mark);
                Ok(())
            }
            // A graft that fails leaves the session as it found it.
            Err(error) => {
                q.back_to(mark);
                self.show();
                Err(error)
            }
        }
    }

    /// Carries the proof back as [`carry_back`](Self::carry_back) does, but
    /// leaves what it made in place when it fails.
    #[expect(clippy::too_many_arguments, reason = "close's own, and what it wrote")]
    fn carry_back_from(
        &mut self,
        goal: GoalId,
        members: &[Member],
        written: &Written,
        proof: &Proof,
        view: &ViewOptions,
        limits: &Limits,
        stop: &mut dyn FnMut(Progress) -> bool,
        step: u32,
    ) -> Result<(), Error> {
        let bad = || Error::GoalMismatch;
        let found = proof.forest();
        // A goal written without a binder is proved without a table.
        let empty;
        let table = match proof.instances() {
            Some(table) => table,
            None => {
                empty = crate::linear::Instances::new(found);
                &empty
            }
        };
        let terms = Terms {
            fo: &found.sequent().fo,
            table,
        };
        // The goal's formulas in the order written.
        let mut order: Vec<Member> = members.to_vec();
        if let Some(reading) = self.reading() {
            order.sort_by_key(|&m| {
                reading.position(self.occurrence(m)) == crate::linear::Side::Output
            });
        }
        let places = places(found, written.prefix.len(), order.len());
        let depth = binders(found);
        // The proof's eigenvariables: the prefix's are the session's, and
        // the others become fresh ones (constants where no `∀` step
        // introduces them).
        let mut eigen_at: HashMap<Eigen, Eigen> = HashMap::default();
        let mut witnesses: Vec<(u32, FoTermId)> = Vec::new();
        let mut introduced: Vec<Eigen> = Vec::new();
        for node in proof.nodes() {
            if let Node::Forall(m, a, _) = *node {
                introduced.push(a);
                if let Place::Prefix = places[proof_occ(proof, m).index()] {
                    let j = depth[proof_occ(proof, m).index()] as usize;
                    if let Err(e) = written.prefix[j] {
                        eigen_at.insert(a, e);
                    }
                }
            } else if let Node::Exists(m, w, _) = *node
                && let Place::Prefix = places[proof_occ(proof, m).index()]
                && let Ok(k) = written.prefix[depth[proof_occ(proof, m).index()] as usize]
            {
                witnesses.push((k, w));
            }
        }
        // Unfolded as the propositional `close` unfolds its graft,
        // two-sided in an intuitionistic mode, so that its steps are the
        // ones `apply` and the reader take. A one-sided unfolding puts
        // structural steps where the reader refuses them.
        let roots: Vec<OccId> = found.roots().to_vec();
        let inferences = Derivation::of_goal(proof, &roots, self.mode, view, limits, stop)?;
        // The reading made from the fields directly, since the first-order
        // part is borrowed mutably below.
        let reading = self.reading.as_ref().map(|(position, goal)| {
            crate::linear::Reading::of_parts(&self.forest, position, *goal, self.mode.is_ordered())
        });
        let q = self.fo.as_mut().expect("a first-order session");
        let forest = &self.forest;
        let mut back = Back {
            q,
            terms,
            constants: &written.constants,
            eigen_at,
            introduced,
            done: HashMap::default(),
        };
        // Each of the proof's members as the session's: one instance, or,
        // for the prefix and the spine, the goal's formulas they join.
        let mut carried: Vec<Inference> = Vec::new();
        let mut at: Vec<Option<InfId>> = Vec::with_capacity(inferences.len());
        let mut members_of: HashMap<Member, Vec<Member>> = HashMap::default();
        for inference in &inferences {
            let mut map = |m: Member| -> Result<Vec<Member>, Error> {
                if let Some(ms) = members_of.get(&m) {
                    return Ok(ms.clone());
                }
                let o = proof_occ(proof, m);
                let ms = match places[o.index()] {
                    Place::Prefix => order.clone(),
                    Place::Spine(i) => order[i..].to_vec(),
                    Place::Inside(i, k) => {
                        let (base, frame) = back.q.instance(order[i]);
                        // A formula's root stands right under the prefix.
                        let inner = depth[o.index()] as usize - written.prefix.len();
                        let mut frame = frame;
                        if let Some((_, f)) = table.instance(m) {
                            let ts = table.frame_terms(f);
                            for &t in ts[..inner].iter().rev() {
                                let t = back.term(forest, t)?;
                                frame = Some(back.q.frame(frame, t));
                            }
                        }
                        vec![back.q.member(OccId::new(base.get() + k), frame)]
                    }
                };
                members_of.insert(m, ms.clone());
                Ok(ms)
            };
            let principal = inference.principal.map(|p| inference.sequent[p]);
            // The prefix's and the spine's steps are left out: the carried
            // inference of their premise stands for them.
            if let Some(p) = principal
                && !matches!(places[proof_occ(proof, p).index()], Place::Inside(..))
            {
                let rule = inference.rule.rule;
                if !matches!(rule, Rule::Forall | Rule::Exists | Rule::Par) {
                    return Err(bad());
                }
                at.push(at[inference.premises[0].index()]);
                continue;
            }
            let mut sequent: Vec<Member> = Vec::new();
            for &m in &inference.sequent {
                sequent.extend(map(m)?);
            }
            sequent.sort_unstable();
            let principal = match principal {
                Some(p) => {
                    let [m] = map(p)?[..] else {
                        return Err(bad());
                    };
                    Some(sequent.binary_search(&m).map_err(|_| bad())?)
                }
                None => None,
            };
            let rule = match principal {
                Some(p) => Named::applied(
                    inference.rule.rule,
                    reading.as_ref(),
                    back.q.instance(sequent[p]).0,
                ),
                None => inference.rule,
            };
            let premises = inference
                .premises
                .iter()
                .map(|p| at[p.index()].ok_or_else(bad))
                .collect::<Result<Vec<_>, _>>()?;
            at.push(Some(InfId::new(carried.len() as u32)));
            carried.push(Inference {
                sequent,
                rule,
                principal,
                premises,
                times: 1,
                cut: None,
                node: None,
            });
        }
        let mut goal_members = members.to_vec();
        goal_members.sort_unstable();
        if carried.last().map(|root| &root.sequent) != Some(&goal_members) {
            return Err(bad());
        }
        // The prefix's witnesses, as the session's terms.
        let mut bindings = Vec::new();
        for (k, w) in witnesses {
            bindings.push((k, back.term(forest, w)?));
        }
        let q = self.fo.as_mut().expect("a first-order session");
        for (k, t) in bindings {
            if q.bind(forest, k, t, step).is_err() {
                return Err(bad());
            }
        }
        self.show();
        let q = self.fo.as_ref().expect("a first-order session");
        if let Some(limit) = q.limit
            && q.too_large()
        {
            return Err(Error::Refused(crate::Refusal::Terms {
                terms: q.largest,
                limit,
            }));
        }
        self.graft(goal.inf(), carried);
        self.history.push(goal.inf());
        Ok(())
    }
}

/// Returns the occurrence a member of a proof stands for.
fn proof_occ(proof: &Proof, m: Member) -> OccId {
    proof
        .instances()
        .and_then(|t| t.instance(m))
        .map_or(m.occ(), |(o, _)| o)
}

/// Returns, per occurrence of the written sequent, where it stands: a
/// binder of the prefix, a `⅋` of the spine, or inside a formula of the
/// goal at an offset.
fn places(forest: &Forest, prefix: usize, formulas: usize) -> Vec<Place> {
    let mut places = vec![Place::Prefix; forest.len()];
    let mut at = OccId::new(prefix as u32);
    for i in 0..formulas {
        let start = if i + 1 < formulas {
            places[at.index()] = Place::Spine(i);
            let left = forest.left(at).expect("a ⅋ of the spine");
            let next = forest.right(at).expect("a ⅋ of the spine");
            let start = left;
            at = next;
            start
        } else {
            at
        };
        let size = forest.size(start);
        for k in 0..size {
            places[(start.get() + k) as usize] = Place::Inside(i, k);
        }
    }
    places
}

/// The copy of a goal's formulas into the written sequent's arenas.
struct Copy<'a> {
    /// The session's forest.
    forest: &'a Forest,
    /// The session's first-order part.
    q: &'a super::quantified::Quantified,
    /// The written sequent's first-order terms.
    interner: Interner,
    /// The written sequent's formula terms.
    terms: Vec<Term>,
    /// The written sequent's atom names.
    atoms: Vec<String>,
    /// Every atom by its name.
    atom_of: HashMap<String, Atom>,
    /// Per atom, its predicate and arguments.
    fo_atoms: Vec<(Symbol, crate::linear::sequents::Args)>,
    /// The binders' names.
    binders: Vec<(TermId, String)>,
    /// What each eigenvariable of the goal is.
    bound: HashMap<Eigen, Bound>,
    /// Each open witness's position in the prefix.
    metas_at: HashMap<u32, u32>,
    /// How many binders the prefix has.
    depth: u32,
    /// Every closed session term copied so far, by the term and the number
    /// of inner binders it was copied under.
    closed: HashMap<(FoTermId, u32), FoTermId>,
}

impl Copy<'_> {
    /// Appends a formula term.
    fn push(&mut self, term: Term) -> TermId {
        self.terms.push(term);
        TermId::new(self.terms.len() as u32 - 1)
    }

    /// Copies the formula a member stands for, with its frame's terms in
    /// place of its loose variables.
    fn formula(&mut self, m: Member) -> TermId {
        let (o, frame) = self.q.instance(m);
        let frame = self.q.frame_terms(frame);
        let sequent = self.forest.sequent();
        let fo = &sequent.fo;
        // A walk with a stack of its own, since a formula may be deeper
        // than the call stack allows. Each entry is a formula term, how
        // many of the formula's binders stand above it, and whether its
        // children are copied.
        let mut stack = vec![(self.forest.term(o), 0u32, false)];
        let mut done: Vec<TermId> = Vec::new();
        while let Some((t, inner, expanded)) = stack.pop() {
            let term = sequent.term(t);
            let unary = |t: TermId| [Some(t), None];
            let children: [Option<TermId>; 2] = match term {
                Term::Tensor(a, b) | Term::Par(a, b) | Term::With(a, b) | Term::Plus(a, b) => {
                    [Some(a), Some(b)]
                }
                Term::Bang(a) | Term::Quest(a) | Term::Forall(a) | Term::Exists(a) => unary(a),
                Term::Atom(_)
                | Term::DualAtom(_)
                | Term::One
                | Term::Bot
                | Term::Top
                | Term::Zero => [None; 2],
            };
            if !expanded && children[0].is_some() {
                stack.push((t, inner, true));
                let below = inner + u32::from(matches!(term, Term::Forall(_) | Term::Exists(_)));
                for c in children.into_iter().flatten().rev() {
                    stack.push((c, below, false));
                }
                continue;
            }
            let made = match term {
                Term::Atom(a) | Term::DualAtom(a) => {
                    let atom = self.atom(a, inner, &frame);
                    self.push(if matches!(term, Term::Atom(_)) {
                        Term::Atom(atom)
                    } else {
                        Term::DualAtom(atom)
                    })
                }
                Term::One | Term::Bot | Term::Top | Term::Zero => self.push(term),
                Term::Tensor(..) | Term::Par(..) | Term::With(..) | Term::Plus(..) => {
                    let b = done.pop().expect("the right child");
                    let a = done.pop().expect("the left child");
                    let mut copies = [a, b].into_iter();
                    self.push(term.map_subterms(|_| copies.next().expect("two children")))
                }
                Term::Bang(_) | Term::Quest(_) | Term::Forall(_) | Term::Exists(_) => {
                    let a = done.pop().expect("the child");
                    let made = self.push(term.map_subterms(|_| a));
                    if let Some(name) = fo.binder_name(t) {
                        self.binders.push((made, name.to_owned()));
                    }
                    made
                }
            };
            done.push(made);
        }
        done.pop().expect("the formula")
    }

    /// Returns the written sequent's atom for the session's atom `a` under
    /// `inner` binders of its formula and the member's frame.
    fn atom(&mut self, a: Atom, inner: u32, frame: &[FoTermId]) -> Atom {
        let fo = &self.forest.sequent().fo;
        let key = match fo.atoms.get(a.index()) {
            Some(&(p, args)) => {
                let items: Vec<FoTermId> = fo
                    .list(args)
                    .to_vec()
                    .into_iter()
                    .map(|t| self.open(t, inner, frame))
                    .collect();
                let list = self.interner.list(&items);
                Some((p, list))
            }
            None => None,
        };
        let name = match key {
            Some((p, list)) => self.interner.tables.atom_key(p, list),
            None => self.forest.sequent().atom_name(a).to_owned(),
        };
        if let Some(&atom) = self.atom_of.get(&name) {
            return atom;
        }
        let atom = Atom::new(self.atoms.len() as u32);
        self.atoms.push(name.clone());
        self.atom_of.insert(name, atom);
        if let Some(key) = key {
            self.fo_atoms.push(key);
        }
        atom
    }

    /// Copies a term of the sequent's arena under `inner` binders of its
    /// formula. Its variables bound past those binders become the frame's
    /// terms.
    fn open(&mut self, t: FoTermId, inner: u32, frame: &[FoTermId]) -> FoTermId {
        let fo = &self.forest.sequent().fo;
        // A walk with a stack of its own, arguments first: an input's
        // terms are as deep as its text, which a recursion may not fit.
        let mut done: HashMap<FoTermId, FoTermId> = HashMap::default();
        let mut stack = vec![(t, false)];
        while let Some((u, expanded)) = stack.pop() {
            if done.contains_key(&u) {
                continue;
            }
            let made = match fo.terms[u.index()] {
                FoTerm::Bound(i) if i < inner => self.interner.term(FoTerm::Bound(i)),
                FoTerm::Bound(i) => self.closed(frame[(i - inner) as usize], inner),
                FoTerm::App(f, args) if expanded => {
                    let items: Vec<FoTermId> = fo.list(args).iter().map(|c| done[c]).collect();
                    let list = self.interner.list(&items);
                    self.interner.term(FoTerm::App(f, list))
                }
                FoTerm::App(_, args) => {
                    stack.push((u, true));
                    stack.extend(fo.list(args).iter().map(|&c| (c, false)));
                    continue;
                }
                FoTerm::Eigen(_) | FoTerm::Meta(_) => {
                    unreachable!("a sequent's arena holds no eigenvariable or metavariable")
                }
            };
            done.insert(u, made);
        }
        done[&t]
    }

    /// Copies a closed term of the session under `inner` binders of its
    /// formula, below the prefix. An eigenvariable or open witness the
    /// prefix binds becomes its bound variable; any other eigenvariable
    /// becomes its constant.
    fn closed(&mut self, t: FoTermId, inner: u32) -> FoTermId {
        // A walk with a stack of its own, arguments first: a witness is as
        // deep as its bindings go, which a recursion may not fit.
        let mut stack = vec![(t, false)];
        while let Some((u, expanded)) = stack.pop() {
            let u = self.q.resolve(self.forest, u);
            if self.closed.contains_key(&(u, inner)) {
                continue;
            }
            let made = match self.q.terms(self.forest).term(u) {
                FoTerm::App(f, args) if expanded => {
                    let items: Vec<FoTermId> = self
                        .q
                        .terms(self.forest)
                        .list(args)
                        .iter()
                        .map(|&c| self.closed[&(self.q.resolve(self.forest, c), inner)])
                        .collect();
                    let list = self.interner.list(&items);
                    self.interner.term(FoTerm::App(f, list))
                }
                FoTerm::App(_, args) => {
                    stack.push((u, true));
                    let children = self.q.terms(self.forest).list(args).to_vec();
                    stack.extend(children.into_iter().map(|c| (c, false)));
                    continue;
                }
                FoTerm::Eigen(a) => match self.bound[&a] {
                    Bound::Constant(symbol) => {
                        let list = self.interner.list(&[]);
                        self.interner.term(FoTerm::App(symbol, list))
                    }
                    Bound::Prefix(j) => self.prefixed(j, inner),
                },
                FoTerm::Meta(k) => {
                    let j = self.metas_at[&k];
                    self.prefixed(j, inner)
                }
                FoTerm::Bound(_) => unreachable!("a closed term has no bound variable"),
            };
            self.closed.insert((u, inner), made);
        }
        self.closed[&(self.q.resolve(self.forest, t), inner)]
    }

    /// Returns the bound variable of the prefix's binder `j`, seen from
    /// under `inner` binders of a formula.
    fn prefixed(&mut self, j: u32, inner: u32) -> FoTermId {
        self.interner
            .term(FoTerm::Bound(self.depth - 1 - j + inner))
    }
}

/// What carries a proof's terms back into the session's.
struct Back<'a> {
    /// The session's first-order part.
    q: &'a mut super::quantified::Quantified,
    /// The proof's terms.
    terms: Terms<'a>,
    /// The written sequent's constants that stand for eigenvariables.
    constants: &'a HashMap<Symbol, Eigen>,
    /// The proof's eigenvariables as the session's.
    eigen_at: HashMap<Eigen, Eigen>,
    /// The proof's eigenvariables that a `∀` step introduces.
    introduced: Vec<Eigen>,
    /// Every term carried back.
    done: HashMap<FoTermId, FoTermId>,
}

impl Back<'_> {
    /// Returns the proof's closed term `t` as the session's.
    fn term(&mut self, forest: &Forest, t: FoTermId) -> Result<FoTermId, Error> {
        // A walk with a stack of its own, arguments first, since a term
        // may be deeper than the call stack allows.
        let mut stack = vec![(t, false)];
        while let Some((u, expanded)) = stack.pop() {
            if self.done.contains_key(&u) {
                continue;
            }
            let made = match self.terms.term(u) {
                FoTerm::App(f, _) if self.constants.contains_key(&f) => {
                    self.q.eigen_term(self.constants[&f])
                }
                FoTerm::App(f, args) if expanded => {
                    let items: Vec<FoTermId> =
                        self.terms.list(args).iter().map(|c| self.done[c]).collect();
                    self.q.apply(f, &items)
                }
                FoTerm::App(_, args) => {
                    stack.push((u, true));
                    stack.extend(self.terms.list(args).iter().map(|&c| (c, false)));
                    continue;
                }
                FoTerm::Eigen(a) => {
                    let e = match self.eigen_at.get(&a) {
                        Some(&e) => e,
                        None => {
                            let Some((e, _)) = self.q.fresh_eigen() else {
                                return Err(Error::Refused(crate::Refusal::Index {
                                    what: crate::limits::Space::Term,
                                    count: u64::from(u32::MAX) + 1,
                                    most: u64::from(u32::MAX),
                                }));
                            };
                            if !self.introduced.contains(&a) {
                                self.q.constants.push(e);
                            }
                            self.eigen_at.insert(a, e);
                            e
                        }
                    };
                    self.q.eigen_term(e)
                }
                FoTerm::Bound(_) | FoTerm::Meta(_) => return Err(Error::GoalMismatch),
            };
            self.done.insert(u, made);
        }
        let _ = forest;
        Ok(self.done[&t])
    }
}