Skip to main content

olean_export/
ndjson.rs

1//! The lean4export 3.1.0 NDJSON format.
2
3use crate::{
4    env::{Binder, Hints, QuotKind},
5    error::{corrupt, Result},
6    record::{
7        Binding, Counts, Decl, Head, IndCtor, IndRec, IndRule, IndType, Record, Safety, Sink,
8    },
9};
10use rayon::prelude::*;
11use serde::Deserialize;
12use serde_json::value::RawValue;
13use std::io::{self, BufRead, Write};
14
15/// Writes records as NDJSON lines, byte for byte as lean4export does.
16#[derive(Debug)]
17pub struct Ndjson<W: Write> {
18    out: W,
19    buf: Vec<u8>,
20}
21
22impl<W: Write> Ndjson<W> {
23    pub const fn new(out: W) -> Self {
24        Self {
25            out,
26            buf: Vec::new(),
27        }
28    }
29
30    fn start(&mut self) -> &mut Self {
31        self.buf.clear();
32        self
33    }
34
35    fn emit(&mut self) -> Result<()> {
36        self.buf.push(b'\n');
37        self.out.write_all(&self.buf)?;
38        Ok(())
39    }
40
41    fn s(&mut self, s: &str) -> &mut Self {
42        self.buf.extend_from_slice(s.as_bytes());
43        self
44    }
45
46    fn n(&mut self, n: impl itoa::Integer) -> &mut Self {
47        self.s(itoa::Buffer::new().format(n))
48    }
49
50    fn b(&mut self, b: bool) -> &mut Self {
51        self.s(if b { "true" } else { "false" })
52    }
53
54    fn list(&mut self, ids: &[u32]) -> &mut Self {
55        self.s("[");
56        for (i, &id) in ids.iter().enumerate() {
57            if i > 0 {
58                self.s(",");
59            }
60            self.n(id);
61        }
62        self.s("]")
63    }
64
65    fn q(&mut self, s: &str) -> &mut Self {
66        self.s("\"");
67        for c in s.chars() {
68            match c {
69                '"' => self.s("\\\""),
70                '\\' => self.s("\\\\"),
71                '\n' => self.s("\\n"),
72                '\r' => self.s("\\r"),
73                c if (c as u32) < 0x20 => self.s("\\u00").s(&format!("{:02x}", c as u32)),
74                c => self.s(c.encode_utf8(&mut [0; 4])),
75            };
76        }
77        self.s("\"")
78    }
79
80    /// `"levelParams":[..],"name":N` and, for `ty`, `"type":T`.
81    fn lp_name(&mut self, h: &Head) -> &mut Self {
82        self.s(r#""levelParams":"#)
83            .list(&h.level_params)
84            .s(r#","name":"#)
85            .n(h.name)
86    }
87
88    fn unsafe_(&mut self, u: bool) -> &mut Self {
89        self.s(r#""isUnsafe":"#).b(u)
90    }
91
92    fn ctor(&mut self, c: &IndCtor) {
93        self.s(r#"{"cidx":"#)
94            .n(c.cidx)
95            .s(r#","induct":"#)
96            .n(c.induct)
97            .s(",")
98            .unsafe_(c.is_unsafe)
99            .s(",")
100            .lp_name(&c.head)
101            .s(r#","numFields":"#)
102            .n(c.num_fields)
103            .s(r#","numParams":"#)
104            .n(c.num_params)
105            .s(r#","type":"#)
106            .n(c.head.ty)
107            .s("}");
108    }
109
110    fn rec(&mut self, r: &IndRec) {
111        self.s(r#"{"all":"#)
112            .list(&r.all)
113            .s(",")
114            .unsafe_(r.is_unsafe)
115            .s(r#","k":"#)
116            .b(r.k)
117            .s(",")
118            .lp_name(&r.head)
119            .s(r#","numIndices":"#)
120            .n(r.num_indices)
121            .s(r#","numMinors":"#)
122            .n(r.num_minors)
123            .s(r#","numMotives":"#)
124            .n(r.num_motives)
125            .s(r#","numParams":"#)
126            .n(r.num_params)
127            .s(r#","rules":["#);
128        for (i, rule) in r.rules.iter().enumerate() {
129            if i > 0 {
130                self.s(",");
131            }
132            self.s(r#"{"ctor":"#)
133                .n(rule.ctor)
134                .s(r#","nfields":"#)
135                .n(rule.nfields)
136                .s(r#","rhs":"#)
137                .n(rule.rhs)
138                .s("}");
139        }
140        self.s(r#"],"type":"#).n(r.head.ty).s("}");
141    }
142
143    fn ty(&mut self, t: &IndType) {
144        self.s(r#"{"all":"#)
145            .list(&t.all)
146            .s(r#","ctors":"#)
147            .list(&t.ctors)
148            .s(r#","isRec":"#)
149            .b(t.is_rec)
150            .s(r#","isReflexive":"#)
151            .b(t.is_reflexive)
152            .s(",")
153            .unsafe_(t.is_unsafe)
154            .s(",")
155            .lp_name(&t.head)
156            .s(r#","numIndices":"#)
157            .n(t.num_indices)
158            .s(r#","numNested":"#)
159            .n(t.num_nested)
160            .s(r#","numParams":"#)
161            .n(t.num_params)
162            .s(r#","type":"#)
163            .n(t.head.ty)
164            .s("}");
165    }
166
167    fn all_opt(&mut self, all: Option<&Vec<u32>>) -> &mut Self {
168        if let Some(all) = all {
169            self.s(r#""all":"#).list(all).s(",");
170        }
171        self
172    }
173}
174
175const fn binder(b: Binder) -> &'static str {
176    match b {
177        Binder::Default => "default",
178        Binder::Implicit => "implicit",
179        Binder::StrictImplicit => "strictImplicit",
180        Binder::InstImplicit => "instImplicit",
181    }
182}
183
184impl<W: Write> Sink for Ndjson<W> {
185    type Output = W;
186
187    fn record(&mut self, id: Option<u32>, r: &Record<'_>) -> Result<()> {
188        let Some(id) = id else {
189            self.start();
190            match r {
191                Record::Meta(json) => {
192                    self.start().s(r#"{"meta":"#).s(json).s("}");
193                }
194                Record::Decl(d) => self.decl(d),
195                _ => return Ok(()),
196            }
197            return self.emit();
198        };
199        self.start();
200        let level = |this: &mut Self, key: &str| {
201            this.s(r#"{"il":"#).n(id).s(r#",""#).s(key).s(r#"":"#);
202        };
203        let binding = |this: &mut Self, b: &Binding| {
204            this.s(r#"{"binderInfo":""#)
205                .s(binder(b.info))
206                .s(r#"","body":"#)
207                .n(b.body)
208                .s(r#","name":"#)
209                .n(b.name)
210                .s(r#","type":"#)
211                .n(b.ty)
212                .s("}");
213        };
214        match r {
215            Record::NameStr { pre, str } => {
216                self.s(r#"{"in":"#)
217                    .n(id)
218                    .s(r#","str":{"pre":"#)
219                    .n(*pre)
220                    .s(r#","str":"#)
221                    .q(str)
222                    .s("}}");
223            }
224            Record::NameNum { pre, i } => {
225                self.s(r#"{"in":"#)
226                    .n(id)
227                    .s(r#","num":{"i":"#)
228                    .n(*i)
229                    .s(r#","pre":"#)
230                    .n(*pre)
231                    .s("}}");
232            }
233            Record::Succ(a) => {
234                level(self, "succ");
235                self.n(*a).s("}");
236            }
237            Record::Param(a) => {
238                level(self, "param");
239                self.n(*a).s("}");
240            }
241            Record::Max(a, b) | Record::IMax(a, b) => {
242                level(
243                    self,
244                    if matches!(r, Record::Max(..)) {
245                        "max"
246                    } else {
247                        "imax"
248                    },
249                );
250                self.s("[").n(*a).s(",").n(*b).s("]}");
251            }
252            Record::BVar(i) => {
253                self.s(r#"{"bvar":"#).n(*i).s(r#","ie":"#).n(id).s("}");
254            }
255            Record::Sort(l) => {
256                self.s(r#"{"ie":"#).n(id).s(r#","sort":"#).n(*l).s("}");
257            }
258            Record::Const { name, us } => {
259                self.s(r#"{"const":{"name":"#)
260                    .n(*name)
261                    .s(r#","us":"#)
262                    .list(us)
263                    .s(r#"},"ie":"#)
264                    .n(id)
265                    .s("}");
266            }
267            Record::App { fun, arg } => {
268                self.s(r#"{"app":{"arg":"#)
269                    .n(*arg)
270                    .s(r#","fn":"#)
271                    .n(*fun)
272                    .s(r#"},"ie":"#)
273                    .n(id)
274                    .s("}");
275            }
276            Record::Lam(b) => {
277                self.s(r#"{"ie":"#).n(id).s(r#","lam":"#);
278                binding(self, b);
279                self.s("}");
280            }
281            Record::Pi(b) => {
282                self.s(r#"{"forallE":"#);
283                binding(self, b);
284                self.s(r#","ie":"#).n(id).s("}");
285            }
286            Record::Let {
287                name,
288                ty,
289                value,
290                body,
291                nondep,
292            } => {
293                self.s(r#"{"ie":"#)
294                    .n(id)
295                    .s(r#","letE":{"body":"#)
296                    .n(*body)
297                    .s(r#","name":"#)
298                    .n(*name)
299                    .s(r#","nondep":"#)
300                    .b(*nondep)
301                    .s(r#","type":"#)
302                    .n(*ty)
303                    .s(r#","value":"#)
304                    .n(*value)
305                    .s("}}");
306            }
307            Record::Nat(v) => {
308                self.s(r#"{"ie":"#)
309                    .n(id)
310                    .s(r#","natVal":""#)
311                    .s(v)
312                    .s(r#""}"#);
313            }
314            Record::Str(v) => {
315                self.s(r#"{"ie":"#).n(id).s(r#","strVal":"#).q(v).s("}");
316            }
317            Record::Proj {
318                type_name,
319                idx,
320                struct_,
321            } => {
322                self.s(r#"{"ie":"#)
323                    .n(id)
324                    .s(r#","proj":{"idx":"#)
325                    .n(*idx)
326                    .s(r#","struct":"#)
327                    .n(*struct_)
328                    .s(r#","typeName":"#)
329                    .n(*type_name)
330                    .s("}}");
331            }
332            Record::MData(x) => {
333                self.s(r#"{"ie":"#)
334                    .n(id)
335                    .s(r#","mdata":{"expr":"#)
336                    .n(*x)
337                    .s("}}");
338            }
339            Record::Meta(_) | Record::Decl(_) | Record::End(_) => unreachable!(),
340        }
341        self.emit()
342    }
343
344    fn finish(mut self) -> Result<W> {
345        self.out.flush()?;
346        Ok(self.out)
347    }
348}
349
350impl<W: Write> Ndjson<W> {
351    fn decl(&mut self, d: &Decl) {
352        match d {
353            Decl::Axiom {
354                head,
355                is_unsafe,
356                all,
357            } => {
358                self.s(r#"{"axiom":{"#)
359                    .all_opt(all.as_ref())
360                    .unsafe_(*is_unsafe)
361                    .s(",")
362                    .lp_name(head)
363                    .s(r#","type":"#)
364                    .n(head.ty)
365                    .s("}}");
366            }
367            Decl::Def {
368                head,
369                value,
370                hints,
371                safety,
372                all,
373            } => {
374                self.s(r#"{"def":{"all":"#).list(all).s(r#","hints":"#);
375                match hints {
376                    Hints::Opaque => self.s(r#""opaque""#),
377                    Hints::Abbrev => self.s(r#""abbrev""#),
378                    Hints::Regular(h) => self.s(r#"{"regular":"#).n(*h).s("}"),
379                };
380                let safety = match safety {
381                    Safety::Safe => "safe",
382                    Safety::Unsafe => "unsafe",
383                    Safety::Partial => "partial",
384                };
385                self.s(",")
386                    .lp_name(head)
387                    .s(r#","safety":""#)
388                    .s(safety)
389                    .s(r#"","type":"#)
390                    .n(head.ty)
391                    .s(r#","value":"#)
392                    .n(*value)
393                    .s("}}");
394            }
395            Decl::Thm { head, value, all } => {
396                self.s(r#"{"thm":{"all":"#)
397                    .list(all)
398                    .s(",")
399                    .lp_name(head)
400                    .s(r#","type":"#)
401                    .n(head.ty)
402                    .s(r#","value":"#)
403                    .n(*value)
404                    .s("}}");
405            }
406            Decl::Opaque {
407                head,
408                value,
409                is_unsafe,
410                all,
411            } => {
412                self.s(r#"{"opaque":{"#)
413                    .all_opt(all.as_ref())
414                    .unsafe_(*is_unsafe)
415                    .s(",")
416                    .lp_name(head)
417                    .s(r#","type":"#)
418                    .n(head.ty)
419                    .s(r#","value":"#)
420                    .n(*value)
421                    .s("}}");
422            }
423            Decl::Quot { head, kind } => {
424                let kind = match kind {
425                    QuotKind::Type => "type",
426                    QuotKind::Ctor => "ctor",
427                    QuotKind::Lift => "lift",
428                    QuotKind::Ind => "ind",
429                };
430                self.s(r#"{"quot":{"kind":""#)
431                    .s(kind)
432                    .s(r#"","#)
433                    .lp_name(head)
434                    .s(r#","type":"#)
435                    .n(head.ty)
436                    .s("}}");
437            }
438            Decl::Inductive { types, ctors, recs } => {
439                self.s(r#"{"inductive":{"ctors":["#);
440                for (i, c) in ctors.iter().enumerate() {
441                    self.sep(i).ctor(c);
442                }
443                self.s(r#"],"recs":["#);
444                for (i, r) in recs.iter().enumerate() {
445                    self.sep(i).rec(r);
446                }
447                self.s(r#"],"types":["#);
448                for (i, t) in types.iter().enumerate() {
449                    self.sep(i).ty(t);
450                }
451                self.s("]}}");
452            }
453        }
454    }
455
456    fn sep(&mut self, i: usize) -> &mut Self {
457        if i > 0 {
458            self.s(",");
459        }
460        self
461    }
462}
463
464/// Replay lean4export NDJSON into `sink`. Ids must be consecutive, as lean4export writes them.
465///
466/// Lines parse in parallel batches, each while `sink` takes the batch before it.
467pub fn read<S: Sink>(mut input: impl BufRead, mut sink: S) -> Result<S::Output> {
468    const BATCH: usize = 1 << 15;
469    let mut next = Counts::default();
470    let mut base = 0;
471    let mut parsed = parse(&batch(&mut input, BATCH)?, base);
472    while let Some(records) = parsed? {
473        let lines = batch(&mut input, BATCH)?;
474        let mut ahead = Ok(None);
475        let mut fed = Ok(());
476        rayon::in_place_scope(|s| {
477            s.spawn(|_| ahead = parse(&lines, base + BATCH));
478            fed = records.iter().try_for_each(|(n, id, r)| {
479                let want = next.assign(r);
480                if let (Some(id), Some(want)) = (id, want) {
481                    if *id != want {
482                        return Err(corrupt(format!("line {n}: id {id}, expected {want}")));
483                    }
484                }
485                sink.record(want, r)
486            });
487        });
488        fed?;
489        parsed = ahead;
490        base += BATCH;
491    }
492    sink.record(None, &Record::End(next))?;
493    sink.finish()
494}
495
496fn batch(input: &mut impl BufRead, n: usize) -> Result<Vec<String>> {
497    input
498        .lines()
499        .take(n)
500        .collect::<io::Result<_>>()
501        .map_err(Into::into)
502}
503
504type Parsed = Vec<(usize, Option<u32>, Record<'static>)>;
505
506fn parse(lines: &[String], base: usize) -> Result<Option<Parsed>> {
507    if lines.is_empty() {
508        return Ok(None);
509    }
510    lines
511        .par_iter()
512        .enumerate()
513        .filter(|(_, l)| !l.is_empty())
514        .map(|(i, line)| {
515            let n = base + i + 1;
516            let at = |e: serde_json::Error| corrupt(format!("line {n}: {e}"));
517            let (id, r) = if line.starts_with(r#"{"meta":"#) {
518                let m: Meta<'_> = serde_json::from_str(line).map_err(at)?;
519                (None, Record::Meta(m.meta.get().to_owned().into()))
520            } else {
521                serde_json::from_str::<Line>(line).map_err(at)?.record()
522            };
523            Ok((n, id, r))
524        })
525        .collect::<Result<_>>()
526        .map(Some)
527}
528
529#[derive(Deserialize)]
530struct Meta<'a> {
531    #[serde(borrow)]
532    meta: &'a RawValue,
533}
534
535#[derive(Deserialize)]
536#[serde(untagged)]
537enum Line {
538    Name {
539        #[serde(rename = "in")]
540        id: u32,
541        #[serde(flatten)]
542        name: JName,
543    },
544    Level {
545        il: u32,
546        #[serde(flatten)]
547        level: JLevel,
548    },
549    Expr {
550        ie: u32,
551        #[serde(flatten)]
552        expr: JExpr,
553    },
554    Decl(JDecl),
555}
556
557#[derive(Deserialize)]
558#[serde(rename_all = "lowercase")]
559enum JName {
560    Str { pre: u32, str: String },
561    Num { pre: u32, i: u64 },
562}
563
564#[derive(Deserialize)]
565#[serde(rename_all = "lowercase")]
566enum JLevel {
567    Succ(u32),
568    Max(u32, u32),
569    IMax(u32, u32),
570    Param(u32),
571}
572
573#[derive(Deserialize)]
574#[serde(rename_all = "camelCase")]
575struct JBinding {
576    binder_info: Binder,
577    name: u32,
578    #[serde(rename = "type")]
579    ty: u32,
580    body: u32,
581}
582
583#[derive(Deserialize)]
584#[serde(rename_all = "camelCase")]
585enum JExpr {
586    Bvar(u64),
587    Sort(u32),
588    Const {
589        name: u32,
590        us: Vec<u32>,
591    },
592    App {
593        #[serde(rename = "fn")]
594        fun: u32,
595        arg: u32,
596    },
597    Lam(JBinding),
598    ForallE(JBinding),
599    LetE {
600        name: u32,
601        #[serde(rename = "type")]
602        ty: u32,
603        value: u32,
604        body: u32,
605        #[serde(default)]
606        nondep: bool,
607    },
608    NatVal(String),
609    StrVal(String),
610    #[serde(rename_all = "camelCase")]
611    Proj {
612        type_name: u32,
613        idx: u64,
614        #[serde(rename = "struct")]
615        struct_: u32,
616    },
617    Mdata {
618        expr: u32,
619    },
620}
621
622#[derive(Deserialize)]
623#[serde(rename_all = "camelCase")]
624struct JHead {
625    name: u32,
626    level_params: Vec<u32>,
627    #[serde(rename = "type")]
628    ty: u32,
629}
630
631impl From<JHead> for Head {
632    fn from(h: JHead) -> Self {
633        Self {
634            name: h.name,
635            level_params: h.level_params,
636            ty: h.ty,
637        }
638    }
639}
640
641#[derive(Deserialize)]
642#[serde(rename_all = "lowercase")]
643enum JSafety {
644    Safe,
645    Unsafe,
646    Partial,
647}
648
649#[derive(Deserialize)]
650#[serde(rename_all = "camelCase")]
651struct JUnsafe {
652    #[serde(flatten)]
653    head: JHead,
654    #[serde(default)]
655    is_unsafe: bool,
656}
657
658#[derive(Deserialize)]
659#[serde(rename_all = "lowercase")]
660enum JDecl {
661    Axiom {
662        #[serde(flatten)]
663        head: JUnsafe,
664        all: Option<Vec<u32>>,
665    },
666    Def {
667        #[serde(flatten)]
668        head: JHead,
669        value: u32,
670        hints: Hints,
671        safety: JSafety,
672        all: Vec<u32>,
673    },
674    Thm {
675        #[serde(flatten)]
676        head: JHead,
677        value: u32,
678        all: Vec<u32>,
679    },
680    Opaque {
681        #[serde(flatten)]
682        head: JUnsafe,
683        value: u32,
684        all: Option<Vec<u32>>,
685    },
686    Quot {
687        #[serde(flatten)]
688        head: JHead,
689        kind: QuotKind,
690    },
691    Inductive {
692        types: Vec<JType>,
693        ctors: Vec<JCtor>,
694        recs: Vec<JRec>,
695    },
696}
697
698#[derive(Deserialize)]
699#[serde(rename_all = "camelCase")]
700struct JType {
701    #[serde(flatten)]
702    head: JUnsafe,
703    num_params: u64,
704    num_indices: u64,
705    all: Vec<u32>,
706    ctors: Vec<u32>,
707    num_nested: u64,
708    is_rec: bool,
709    is_reflexive: bool,
710}
711
712#[derive(Deserialize)]
713#[serde(rename_all = "camelCase")]
714struct JCtor {
715    #[serde(flatten)]
716    head: JUnsafe,
717    induct: u32,
718    cidx: u64,
719    num_params: u64,
720    num_fields: u64,
721}
722
723#[derive(Deserialize)]
724#[serde(rename_all = "camelCase")]
725struct JRec {
726    #[serde(flatten)]
727    head: JUnsafe,
728    all: Vec<u32>,
729    num_params: u64,
730    num_indices: u64,
731    num_motives: u64,
732    num_minors: u64,
733    rules: Vec<IndRule>,
734    k: bool,
735}
736
737impl Line {
738    fn record(self) -> (Option<u32>, Record<'static>) {
739        match self {
740            Self::Name { id, name } => (
741                Some(id),
742                match name {
743                    JName::Str { pre, str } => Record::NameStr {
744                        pre,
745                        str: str.into(),
746                    },
747                    JName::Num { pre, i } => Record::NameNum { pre, i },
748                },
749            ),
750            Self::Level { il, level } => (
751                Some(il),
752                match level {
753                    JLevel::Succ(a) => Record::Succ(a),
754                    JLevel::Max(a, b) => Record::Max(a, b),
755                    JLevel::IMax(a, b) => Record::IMax(a, b),
756                    JLevel::Param(n) => Record::Param(n),
757                },
758            ),
759            Self::Expr { ie, expr } => (Some(ie), expr.into()),
760            Self::Decl(d) => (None, Record::Decl(d.into())),
761        }
762    }
763}
764
765impl From<JBinding> for Binding {
766    fn from(b: JBinding) -> Self {
767        Self {
768            info: b.binder_info,
769            name: b.name,
770            ty: b.ty,
771            body: b.body,
772        }
773    }
774}
775
776impl From<JExpr> for Record<'_> {
777    fn from(e: JExpr) -> Self {
778        match e {
779            JExpr::Bvar(i) => Self::BVar(i),
780            JExpr::Sort(l) => Self::Sort(l),
781            JExpr::Const { name, us } => Self::Const { name, us },
782            JExpr::App { fun, arg } => Self::App { fun, arg },
783            JExpr::Lam(b) => Self::Lam(b.into()),
784            JExpr::ForallE(b) => Self::Pi(b.into()),
785            JExpr::LetE {
786                name,
787                ty,
788                value,
789                body,
790                nondep,
791            } => Self::Let {
792                name,
793                ty,
794                value,
795                body,
796                nondep,
797            },
798            JExpr::NatVal(v) => Self::Nat(v.into()),
799            JExpr::StrVal(v) => Self::Str(v.into()),
800            JExpr::Proj {
801                type_name,
802                idx,
803                struct_,
804            } => Self::Proj {
805                type_name,
806                idx,
807                struct_,
808            },
809            JExpr::Mdata { expr } => Self::MData(expr),
810        }
811    }
812}
813
814impl From<JDecl> for Decl {
815    fn from(d: JDecl) -> Self {
816        match d {
817            JDecl::Axiom { head, all } => Self::Axiom {
818                head: head.head.into(),
819                is_unsafe: head.is_unsafe,
820                all,
821            },
822            JDecl::Def {
823                head,
824                value,
825                hints,
826                safety,
827                all,
828            } => Self::Def {
829                head: head.into(),
830                value,
831                hints,
832                safety: match safety {
833                    JSafety::Safe => Safety::Safe,
834                    JSafety::Unsafe => Safety::Unsafe,
835                    JSafety::Partial => Safety::Partial,
836                },
837                all,
838            },
839            JDecl::Thm { head, value, all } => Self::Thm {
840                head: head.into(),
841                value,
842                all,
843            },
844            JDecl::Opaque { head, value, all } => Self::Opaque {
845                head: head.head.into(),
846                value,
847                is_unsafe: head.is_unsafe,
848                all,
849            },
850            JDecl::Quot { head, kind } => Self::Quot {
851                head: head.into(),
852                kind,
853            },
854            JDecl::Inductive { types, ctors, recs } => Self::Inductive {
855                types: types
856                    .into_iter()
857                    .map(|t| IndType {
858                        head: t.head.head.into(),
859                        is_unsafe: t.head.is_unsafe,
860                        num_params: t.num_params,
861                        num_indices: t.num_indices,
862                        all: t.all,
863                        ctors: t.ctors,
864                        num_nested: t.num_nested,
865                        is_rec: t.is_rec,
866                        is_reflexive: t.is_reflexive,
867                    })
868                    .collect(),
869                ctors: ctors
870                    .into_iter()
871                    .map(|c| IndCtor {
872                        head: c.head.head.into(),
873                        is_unsafe: c.head.is_unsafe,
874                        induct: c.induct,
875                        cidx: c.cidx,
876                        num_params: c.num_params,
877                        num_fields: c.num_fields,
878                    })
879                    .collect(),
880                recs: recs
881                    .into_iter()
882                    .map(|r| IndRec {
883                        head: r.head.head.into(),
884                        is_unsafe: r.head.is_unsafe,
885                        all: r.all,
886                        num_params: r.num_params,
887                        num_indices: r.num_indices,
888                        num_motives: r.num_motives,
889                        num_minors: r.num_minors,
890                        rules: r.rules,
891                        k: r.k,
892                    })
893                    .collect(),
894            },
895        }
896    }
897}