olean-export 0.6.0

Optimized library for reading Lean .olean files directly emitting lean4export-compatible NDJSON for external kernel checkers.
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
use crate::{
    env::{
        Binder, Builtins, Const, Ctor, Dep, Depth, Env, Expr, ExprId, Family, Inductive, Kind,
        Level, LevelId, Name, NameId, Rec, Reload, ANON, ZERO,
    },
    error::{corrupt, Error, Result},
    ndjson::Ndjson,
    record::{
        Binding, Counts, Decl, Head, IndCtor, IndRec, IndRule, IndType, Record, Safety, Sink,
    },
};
use rustc_hash::{FxHashMap, FxHashSet};
use std::io::Write;

const UNSEEN: u32 = u32::MAX;

/// Where an export stopped, so that a later one on the same [`Env`], reloaded or not,
/// continues its ids and writes only records the earlier one did not.
#[derive(Debug)]
pub struct Mark {
    lineage: u64,
    names: Vec<u32>,
    levels: Vec<u32>,
    exprs: Vec<u32>,
    scanned: Vec<bool>,
    visited: FxHashSet<NameId>,
    next: Counts,
}

impl Mark {
    fn fresh(env: &Env) -> Self {
        let mut names = vec![UNSEEN; env.names.bound()];
        let mut levels = vec![UNSEEN; env.levels.bound()];
        names[ANON.index()] = 0;
        levels[ZERO.index()] = 0;
        Self {
            lineage: env.lineage,
            names,
            levels,
            exprs: Vec::new(),
            scanned: Vec::new(),
            visited: FxHashSet::default(),
            next: Counts::default(),
        }
    }
}

/// Streams an [`Env`] in lean4export 3.1.0 order to a [`Sink`], NDJSON by default. Ids are
/// assigned on first use and every record only refers to records already written.
#[derive(Debug)]
pub struct Exporter<'a, S: Sink> {
    env: &'a Env,
    sink: S,
    names: Vec<u32>,
    levels: Vec<u32>,
    exprs: Vec<u32>,
    next: Counts,
    scanned: Vec<bool>,
    visited: FxHashSet<NameId>,
    builtins: Builtins,
    depth: Depth,
    scope: Option<Box<Scope>>,
}

/// Per-module export: which modules declare each constant, what each module imports
/// transitively, the module being written, and the entries its file took, to clear before
/// the next. Lean realizes some constants, such as equation lemmas, in every module that
/// needs them, and the environment keeps one copy, which may refer to private constants of
/// a module the writer does not import. So a file holds what its module declares and
/// whatever else it needs that no import provides.
#[derive(Debug, Default)]
struct Scope {
    owner: FxHashMap<NameId, u32>,
    more: FxHashMap<NameId, Vec<u32>>,
    closure: Vec<Vec<u64>>,
    module: u32,
    names: Vec<NameId>,
    levels: Vec<LevelId>,
    exprs: Vec<ExprId>,
    scanned: Vec<ExprId>,
    visited: Vec<NameId>,
}

impl Scope {
    fn new(env: &Env) -> Self {
        let mut s = Self::default();
        for m in 0..env.modules.len() {
            let m32 = u32::try_from(m).expect("module count");
            for &c in env.module_consts(m) {
                if let Some(&o) = s.owner.get(&c) {
                    if o != m32 {
                        s.more.entry(c).or_default().push(m32);
                    }
                } else {
                    s.owner.insert(c, m32);
                }
            }
        }
        let index: FxHashMap<&str, usize> = env
            .modules
            .iter()
            .enumerate()
            .map(|(i, m)| (m.as_str(), i))
            .collect();
        let words = env.modules.len().div_ceil(64);
        for imports in &env.imports {
            let mut bits = vec![0u64; words];
            for &j in imports.iter().filter_map(|i| index.get(i.as_str())) {
                if let Some(c) = s.closure.get(j) {
                    bits.iter_mut().zip(c).for_each(|(b, c)| *b |= c);
                    bits[j / 64] |= 1 << (j % 64);
                }
            }
            s.closure.push(bits);
        }
        s
    }

    /// Whether the module being written writes `c`, rather than an import providing it.
    fn writes(&self, c: NameId) -> bool {
        let Some(&first) = self.owner.get(&c) else {
            return true;
        };
        let owners = std::iter::once(first).chain(self.more.get(&c).into_iter().flatten().copied());
        let mut provided = false;
        for o in owners {
            if o == self.module {
                return true;
            }
            let bits = &self.closure[self.module as usize];
            provided |= bits[o as usize / 64] >> (o % 64) & 1 == 1;
        }
        !provided
    }
}

/// One step of [`Exporter::constant`]'s depth-first walk over dependencies.
enum Task {
    Const(NameId),
    Scan(ExprId),
    Scanned(ExprId),
    Emit(NameId),
}

impl<'a, W: Write> Exporter<'a, Ndjson<W>> {
    pub fn new(env: &'a Env, out: W) -> Self {
        Self::with_sink(env, Ndjson::new(out))
    }
}

impl<'a, S: Sink> Exporter<'a, S> {
    pub fn with_sink(env: &'a Env, sink: S) -> Self {
        Self::from_mark(env, sink, Mark::fresh(env))
    }

    /// Continue the export `mark` was taken from, on the same environment.
    pub fn resume(env: &'a Env, sink: S, mark: Mark) -> Result<Self> {
        if mark.lineage != env.lineage {
            return Err(Error::Misuse("the mark is from another environment"));
        }
        Ok(Self::from_mark(env, sink, mark))
    }

    fn from_mark(env: &'a Env, sink: S, mut m: Mark) -> Self {
        m.names.resize(env.names.bound(), UNSEEN);
        m.levels.resize(env.levels.bound(), UNSEEN);
        m.exprs.resize(env.exprs.bound(), UNSEEN);
        m.scanned.resize(env.exprs.bound(), false);
        Self {
            env,
            sink,
            names: m.names,
            levels: m.levels,
            exprs: m.exprs,
            next: m.next,
            scanned: m.scanned,
            visited: m.visited,
            builtins: Builtins::find(env),
            depth: Depth::Full,
            scope: None,
        }
    }

    /// An exporter that writes one module at a time with [`Exporter::module`], each to its
    /// own sink after [`Exporter::split`]. A module's records refer to what its imports
    /// declare by name only.
    pub fn per_module(env: &'a Env, sink: S) -> Self {
        let mut ex = Self::with_sink(env, sink);
        ex.scope = Some(Box::new(Scope::new(env)));
        ex
    }

    /// Write every constant module `m` declares. Internal ones are included, since a later
    /// module may need them.
    pub fn module(&mut self, m: usize) -> Result<()> {
        let s = self
            .scope
            .as_mut()
            .ok_or(Error::Misuse("module needs a per-module exporter"))?;
        s.module = u32::try_from(m).expect("module count");
        let env = self.env;
        env.module_consts(m)
            .iter()
            .try_for_each(|&c| self.constant(c))
    }

    /// End the current file and start the next on `sink`, with ids from the start again.
    /// Returns the finished sink's output.
    pub fn split(&mut self, sink: S) -> Result<S::Output> {
        let s = self
            .scope
            .as_mut()
            .ok_or(Error::Misuse("split needs a per-module exporter"))?;
        for n in s.names.drain(..) {
            self.names[n.index()] = UNSEEN;
        }
        for l in s.levels.drain(..) {
            self.levels[l.index()] = UNSEEN;
        }
        for e in s.exprs.drain(..) {
            self.exprs[e.index()] = UNSEEN;
        }
        for e in s.scanned.drain(..) {
            self.scanned[e.index()] = false;
        }
        for c in s.visited.drain(..) {
            self.visited.remove(&c);
        }
        self.sink.record(None, &Record::End(self.next))?;
        self.next = Counts::default();
        std::mem::replace(&mut self.sink, sink).finish()
    }

    /// Write every theorem as an axiom over its type, so an environment from
    /// [`Env::load_statements`] exports its statements and what they rest on, with no
    /// proofs.
    #[must_use]
    pub const fn statements(mut self) -> Self {
        self.depth = Depth::Statements;
        self
    }

    pub fn meta(&mut self) -> Result<()> {
        self.meta_with(None)
    }

    /// The `meta` record, with `module` added under that key when given.
    pub fn meta_with(&mut self, module: Option<serde_json::Value>) -> Result<()> {
        let h = &self.env.header;
        let mut meta = serde_json::json!({
            "exporter": {"name": "olean-export", "version": env!("CARGO_PKG_VERSION")},
            "format": {"version": "3.1.0"},
            "lean": {"githash": h.githash, "version": h.version},
        });
        if let Some(m) = module {
            meta["module"] = m;
        }
        self.sink
            .record(None, &Record::Meta(meta.to_string().into()))
    }

    /// Export every non-internal constant in load order, like `lean4export` with no `--`.
    pub fn all(&mut self) -> Result<()> {
        self.env.roots().try_for_each(|c| self.constant(c))
    }

    #[must_use]
    pub const fn counts(&self) -> Counts {
        self.next
    }

    /// Write the end record and hand back the sink's output.
    pub fn finish(self) -> Result<S::Output> {
        self.suspend().map(|(out, _)| out)
    }

    /// Like [`Exporter::finish`], with a [`Mark`] to [`Exporter::resume`] from.
    pub fn suspend(mut self) -> Result<(S::Output, Mark)> {
        self.sink.record(None, &Record::End(self.next))?;
        let mark = Mark {
            lineage: self.env.lineage,
            names: self.names,
            levels: self.levels,
            exprs: self.exprs,
            scanned: self.scanned,
            visited: self.visited,
            next: self.next,
        };
        Ok((self.sink.finish()?, mark))
    }

    /// After [`Env::reload`], export the reloaded constants again as [`Exporter::all`] would.
    /// The end record counts every record since the first export.
    /// An internal constant is written again if it was written before, since terms
    /// already scanned will not lead back to it.
    pub fn update(&mut self, r: &Reload) -> Result<()> {
        for c in &r.removed {
            self.visited.remove(c);
        }
        let env = self.env;
        let again: Vec<NameId> = r
            .consts
            .iter()
            .copied()
            .filter(|c| self.visited.remove(c) | !env.is_internal(*c))
            .collect();
        again.into_iter().try_for_each(|c| self.constant(c))
    }

    fn name(&mut self, n: NameId) -> Result<u32> {
        if self.names[n.index()] != UNSEEN {
            return Ok(self.names[n.index()]);
        }
        let id = match &self.env.names[n] {
            Name::Anon => unreachable!(),
            Name::Str(p, s) => {
                let p = self.name(*p)?;
                self.emit(&Record::NameStr {
                    pre: p,
                    str: s.as_ref().into(),
                })?
            }
            Name::Num(p, i) => {
                let p = self.name(*p)?;
                self.emit(&Record::NameNum { pre: p, i: *i })?
            }
        };
        self.names[n.index()] = id;
        if let Some(s) = &mut self.scope {
            s.names.push(n);
        }
        Ok(id)
    }

    fn name_list(&mut self, ns: &[NameId]) -> Result<Vec<u32>> {
        ns.iter().map(|&n| self.name(n)).collect()
    }

    fn level_params(&mut self, ps: &[NameId]) -> Result<Vec<u32>> {
        let list = self.name_list(ps)?;
        for &p in ps {
            let l = self
                .env
                .levels
                .get(&Level::Param(p))
                .expect("level params are interned at load");
            self.level(l)?;
        }
        Ok(list)
    }

    fn level(&mut self, l: LevelId) -> Result<u32> {
        if self.levels[l.index()] != UNSEEN {
            return Ok(self.levels[l.index()]);
        }
        let r = match self.env.levels[l] {
            Level::Zero => unreachable!(),
            Level::Succ(a) => Record::Succ(self.level(a)?),
            Level::Max(a, b) => Record::Max(self.level(a)?, self.level(b)?),
            Level::IMax(a, b) => Record::IMax(self.level(a)?, self.level(b)?),
            Level::Param(n) => Record::Param(self.name(n)?),
        };
        let id = self.emit(&r)?;
        self.levels[l.index()] = id;
        if let Some(s) = &mut self.scope {
            s.levels.push(l);
        }
        Ok(id)
    }

    /// Export `root` after its subterms. The worklist visits each term twice: first to
    /// export the names and levels it mentions and queue its subterms, then to write it.
    fn expr(&mut self, root: ExprId) -> Result<u32> {
        let env = self.env;
        let mut work = vec![(root, false)];
        while let Some((e, ready)) = work.pop() {
            if self.exprs[e.index()] != UNSEEN {
                continue;
            }
            let x = &env.exprs[e];
            if !ready {
                work.push((e, true));
                match x {
                    Expr::BVar(_) => {}
                    Expr::Sort(l) => {
                        self.level(*l)?;
                    }
                    Expr::Const(n, us) => {
                        self.name(*n)?;
                        us.iter().try_for_each(|&u| self.level(u).map(drop))?;
                    }
                    Expr::App(f, a) => work.extend([(*a, false), (*f, false)]),
                    Expr::Lam(n, t, b, _) | Expr::Pi(n, t, b, _) => {
                        self.name(*n)?;
                        work.extend([(*b, false), (*t, false)]);
                    }
                    Expr::Let(n, t, v, b) => {
                        self.name(*n)?;
                        work.extend([(*b, false), (*v, false), (*t, false)]);
                    }
                    Expr::Nat(_) | Expr::Str(_) => {
                        let mut lits = Vec::new();
                        self.env.children(e, &self.builtins, |d| lits.push(d));
                        for d in lits {
                            if let Dep::Literal(c) = d {
                                self.constant(c)?;
                            }
                        }
                    }
                    Expr::Proj(n, _, x) => {
                        self.name(*n)?;
                        work.push((*x, false));
                    }
                }
                continue;
            }
            let (names, levels, exprs) = (&self.names, &self.levels, &self.exprs);
            let name = |n: &NameId| names[n.index()];
            let level = |l: &LevelId| levels[l.index()];
            let expr = |e: &ExprId| exprs[e.index()];
            let bind = |n: &NameId, t: &ExprId, b: &ExprId, bi: &Binder| Binding {
                info: *bi,
                name: name(n),
                ty: expr(t),
                body: expr(b),
            };
            let r = match x {
                Expr::BVar(i) => Record::BVar(*i),
                Expr::Sort(l) => Record::Sort(level(l)),
                Expr::Const(n, us) => Record::Const {
                    name: name(n),
                    us: us.iter().map(level).collect(),
                },
                Expr::App(f, a) => Record::App {
                    fun: expr(f),
                    arg: expr(a),
                },
                Expr::Lam(n, t, b, bi) => Record::Lam(bind(n, t, b, bi)),
                Expr::Pi(n, t, b, bi) => Record::Pi(bind(n, t, b, bi)),
                // Lean marks most `let`s nondep, but lean4export writes false for all of
                // them so that terms differing only in the flag share one index.
                Expr::Let(n, t, v, b) => Record::Let {
                    name: name(n),
                    ty: expr(t),
                    value: expr(v),
                    body: expr(b),
                    nondep: false,
                },
                Expr::Nat(v) => Record::Nat(v.as_ref().into()),
                Expr::Str(v) => Record::Str(v.as_ref().into()),
                Expr::Proj(n, i, x) => Record::Proj {
                    type_name: name(n),
                    idx: *i,
                    struct_: expr(x),
                },
            };
            let id = self.emit(&r)?;
            self.exprs[e.index()] = id;
            if let Some(s) = &mut self.scope {
                s.exprs.push(e);
            }
        }
        Ok(self.exprs[root.index()])
    }

    /// Write a name, level or expression record and return its id.
    fn emit(&mut self, r: &Record<'_>) -> Result<u32> {
        let id = self.next.assign(r);
        self.sink.record(id, r)?;
        Ok(id.expect("emit takes only id-bearing records"))
    }

    fn decl(&mut self, d: Decl) -> Result<()> {
        self.sink.record(None, &Record::Decl(d))
    }

    /// Export a constant and, first, everything it mentions. Dependencies are walked
    /// depth-first on an explicit stack, so no term depth or dependency chain can overflow
    /// the thread's stack.
    pub fn constant(&mut self, c: NameId) -> Result<()> {
        let env = self.env;
        let mut work = vec![Task::Const(c)];
        let mut members = Vec::new();
        while let Some(task) = work.pop() {
            match task {
                Task::Scan(e) => {
                    if !self.scanned[e.index()] {
                        work.push(Task::Scanned(e));
                        let at = work.len();
                        env.children(e, &self.builtins, |d| match d {
                            Dep::Expr(x) => work.push(Task::Scan(x)),
                            Dep::Const(c) => work.push(Task::Const(c)),
                            Dep::Member(_) | Dep::Literal(_) | Dep::Unloaded(_) => {}
                        });
                        work[at..].reverse();
                    }
                }
                Task::Scanned(e) => {
                    self.scanned[e.index()] = true;
                    if let Some(s) = &mut self.scope {
                        s.scanned.push(e);
                    }
                }
                Task::Const(c) => {
                    if self.scope.as_ref().is_some_and(|s| !s.writes(c)) {
                        continue;
                    }
                    if !self.visit(c) {
                        continue;
                    }
                    let Some(k) = env.consts.get(&c) else {
                        continue;
                    };
                    if !matches!(k.kind, Kind::Ctor(_) | Kind::Rec(_)) {
                        work.push(Task::Emit(c));
                    }
                    let at = work.len();
                    let mut unloaded = None;
                    env.mentions(k, self.depth, &self.builtins, |d| match d {
                        Dep::Expr(e) => work.push(Task::Scan(e)),
                        Dep::Const(c) => work.push(Task::Const(c)),
                        Dep::Member(c) => members.push(c),
                        Dep::Literal(_) => {}
                        Dep::Unloaded(c) => unloaded = Some(c),
                    })?;
                    if let Some(c) = unloaded {
                        return Err(corrupt(format!(
                            "the value of {} was not loaded",
                            env.display(c)
                        )));
                    }
                    work[at..].reverse();
                    for c in std::mem::take(&mut members) {
                        self.visit(c);
                    }
                }
                Task::Emit(c) => self.write(c)?,
            }
        }
        Ok(())
    }

    fn visit(&mut self, c: NameId) -> bool {
        let new = self.visited.insert(c);
        if let Some(s) = self.scope.as_mut().filter(|_| new) {
            s.visited.push(c);
        }
        new
    }

    /// Write the declaration of `c`, whose dependencies are already out.
    fn write(&mut self, c: NameId) -> Result<()> {
        let k = &self.env.consts[&c];
        match &k.kind {
            Kind::Thm(_) if self.depth == Depth::Statements => {
                let head = self.header(k)?;
                self.decl(Decl::Axiom {
                    head,
                    is_unsafe: false,
                    all: None,
                })
            }
            Kind::Axiom => {
                let head = self.header(k)?;
                self.decl(Decl::Axiom {
                    head,
                    is_unsafe: false,
                    all: None,
                })
            }
            Kind::Defn(d) => {
                let head = self.header(k)?;
                let value = self.expr(d.value)?;
                let all = self.name_list(&d.all)?;
                self.decl(Decl::Def {
                    head,
                    value,
                    hints: d.hints,
                    all,
                    safety: Safety::Safe,
                })
            }
            Kind::Thm(t) => {
                let head = self.header(k)?;
                let value = self.expr(t.value.expect("scanned"))?;
                let all = self.name_list(&t.all)?;
                self.decl(Decl::Thm { head, value, all })
            }
            Kind::Opaque(b) => {
                let head = self.header(k)?;
                let value = self.expr(b.value)?;
                let all = self.name_list(&b.all)?;
                self.decl(Decl::Opaque {
                    head,
                    value,
                    is_unsafe: false,
                    all: Some(all),
                })
            }
            Kind::Quot(_) => self.quot(),
            Kind::Induct(ind) => self.inductive(k, ind),
            Kind::Ctor(_) | Kind::Rec(_) => unreachable!("exported through their inductive"),
        }
    }

    fn header(&mut self, k: &Const) -> Result<Head> {
        Ok(Head {
            name: self.name(k.name)?,
            level_params: self.level_params(&k.level_params)?,
            ty: self.expr(k.ty)?,
        })
    }

    fn quot(&mut self) -> Result<()> {
        let env = self.env;
        let [_, rest @ ..] = self.builtins.quot;
        for c in rest.into_iter().flatten() {
            let (k, &kind) = env.lookup(c, "quotient", |k| match k {
                Kind::Quot(q) => Some(q),
                _ => None,
            })?;
            let head = self.header(k)?;
            self.decl(Decl::Quot { head, kind })?;
        }
        Ok(())
    }

    fn inductive(&mut self, base: &Const, ind: &Inductive) -> Result<()> {
        let Family { types, ctors, recs } = self.env.family(base, ind)?;
        let mut out_ctors = Vec::with_capacity(ctors.len());
        for &(c, ctor) in &ctors {
            let Ctor {
                induct,
                cidx,
                num_params,
                num_fields,
            } = *ctor;
            let head = self.header(c)?;
            out_ctors.push(IndCtor {
                head,
                is_unsafe: false,
                induct: self.name(induct)?,
                cidx,
                num_params,
                num_fields,
            });
        }
        let mut out_recs = Vec::with_capacity(recs.len());
        for &(r, rec) in &recs {
            let Rec {
                all,
                num_params,
                num_indices,
                num_motives,
                num_minors,
                rules,
                k,
            } = rec;
            let head = self.header(r)?;
            let all = self.name_list(all)?;
            let rules = rules
                .iter()
                .map(|rule| {
                    Ok(IndRule {
                        ctor: self.name(rule.ctor)?,
                        nfields: rule.nfields,
                        rhs: self.expr(rule.rhs)?,
                    })
                })
                .collect::<Result<Vec<_>>>()?;
            out_recs.push(IndRec {
                head,
                is_unsafe: false,
                all,
                num_params: *num_params,
                num_indices: *num_indices,
                num_motives: *num_motives,
                num_minors: *num_minors,
                rules,
                k: *k,
            });
        }
        let mut out_types = Vec::with_capacity(types.len());
        for &(ty, ind) in &types {
            let Inductive {
                num_params,
                num_indices,
                all,
                ctors,
                num_nested,
                is_rec,
                is_reflexive,
            } = ind;
            let head = self.header(ty)?;
            let (all, ctors) = (self.name_list(all)?, self.name_list(ctors)?);
            out_types.push(IndType {
                head,
                is_unsafe: false,
                num_params: *num_params,
                num_indices: *num_indices,
                all,
                ctors,
                num_nested: *num_nested,
                is_rec: *is_rec,
                is_reflexive: *is_reflexive,
            });
        }
        self.decl(Decl::Inductive {
            types: out_types,
            ctors: out_ctors,
            recs: out_recs,
        })
    }
}