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