Skip to main content

olean_export/
record.rs

1//! One line of the export stream with every reference resolved to an output id. The
2//! traversal in [`crate::Exporter`] produces these and every output format consumes them.
3//!
4//! The derived serde layout is also the blean format (see [`crate::blean`]), so variant
5//! and field order are part of the format and must not change.
6
7use crate::{
8    env::{Binder, Hints, QuotKind},
9    error::Result,
10};
11use serde::{Deserialize, Serialize};
12use std::borrow::Cow;
13
14/// Ids are implicit: names and levels count from 1 (0 is the anonymous name and the zero
15/// level), expressions from 0, each in record order. Records only refer to earlier ones.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub enum Record<'a> {
18    /// The `meta` object as JSON. Always first.
19    Meta(#[serde(borrow)] Cow<'a, str>),
20    NameStr {
21        pre: u32,
22        #[serde(borrow)]
23        str: Cow<'a, str>,
24    },
25    NameNum {
26        pre: u32,
27        i: u64,
28    },
29    Succ(u32),
30    Max(u32, u32),
31    IMax(u32, u32),
32    Param(u32),
33    BVar(u64),
34    Sort(u32),
35    Const {
36        name: u32,
37        us: Vec<u32>,
38    },
39    App {
40        fun: u32,
41        arg: u32,
42    },
43    Lam(Binding),
44    Pi(Binding),
45    Let {
46        name: u32,
47        ty: u32,
48        value: u32,
49        body: u32,
50        nondep: bool,
51    },
52    /// Decimal digits.
53    Nat(#[serde(borrow)] Cow<'a, str>),
54    Str(#[serde(borrow)] Cow<'a, str>),
55    Proj {
56        type_name: u32,
57        idx: u64,
58        struct_: u32,
59    },
60    /// lean4export's metadata wrapper, which kernels read as the wrapped term.
61    MData(u32),
62    Decl(Decl),
63    /// Always last.
64    End(Counts),
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
68pub struct Binding {
69    pub info: Binder,
70    pub name: u32,
71    pub ty: u32,
72    pub body: u32,
73}
74
75/// Records written so far for each table, which is also the next id each hands out. Fixed
76/// width on the wire, so a blean file ends with these as three little-endian `u32`s.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78pub struct Counts {
79    #[serde(with = "postcard::fixint::le")]
80    pub names: u32,
81    #[serde(with = "postcard::fixint::le")]
82    pub levels: u32,
83    #[serde(with = "postcard::fixint::le")]
84    pub exprs: u32,
85}
86
87impl Default for Counts {
88    fn default() -> Self {
89        Self {
90            names: 1,
91            levels: 1,
92            exprs: 0,
93        }
94    }
95}
96
97impl Record<'_> {
98    /// Which table the record adds to, if any.
99    #[must_use]
100    pub const fn table(&self) -> Option<Table> {
101        match self {
102            Self::NameStr { .. } | Self::NameNum { .. } => Some(Table::Names),
103            Self::Succ(_) | Self::Max(..) | Self::IMax(..) | Self::Param(_) => Some(Table::Levels),
104            Self::Meta(_) | Self::Decl(_) | Self::End(_) => None,
105            _ => Some(Table::Exprs),
106        }
107    }
108}
109
110impl Record<'_> {
111    /// Rewrite every id the record refers to with `f`, given the table it points into.
112    pub fn map_ids(&mut self, f: &impl Fn(Table, u32) -> u32) {
113        let n = |x: &mut u32| *x = f(Table::Names, *x);
114        let l = |x: &mut u32| *x = f(Table::Levels, *x);
115        let e = |x: &mut u32| *x = f(Table::Exprs, *x);
116        let head = |h: &mut Head| {
117            n(&mut h.name);
118            h.level_params.iter_mut().for_each(n);
119            e(&mut h.ty);
120        };
121        match self {
122            Self::Meta(_) | Self::BVar(_) | Self::Nat(_) | Self::Str(_) | Self::End(_) => {}
123            Self::NameStr { pre, .. } | Self::NameNum { pre, .. } => n(pre),
124            Self::Succ(a) | Self::Sort(a) => l(a),
125            Self::Max(a, b) | Self::IMax(a, b) => {
126                l(a);
127                l(b);
128            }
129            Self::Param(p) => n(p),
130            Self::Const { name, us } => {
131                n(name);
132                us.iter_mut().for_each(l);
133            }
134            Self::App { fun, arg } => {
135                e(fun);
136                e(arg);
137            }
138            Self::Lam(b) | Self::Pi(b) => {
139                n(&mut b.name);
140                e(&mut b.ty);
141                e(&mut b.body);
142            }
143            Self::Let {
144                name,
145                ty,
146                value,
147                body,
148                ..
149            } => {
150                n(name);
151                e(ty);
152                e(value);
153                e(body);
154            }
155            Self::Proj {
156                type_name, struct_, ..
157            } => {
158                n(type_name);
159                e(struct_);
160            }
161            Self::MData(x) => e(x),
162            Self::Decl(d) => match d {
163                Decl::Axiom { head: h, all, .. } => {
164                    head(h);
165                    all.iter_mut().flatten().for_each(n);
166                }
167                Decl::Def {
168                    head: h,
169                    value,
170                    all,
171                    ..
172                }
173                | Decl::Thm {
174                    head: h,
175                    value,
176                    all,
177                } => {
178                    head(h);
179                    e(value);
180                    all.iter_mut().for_each(n);
181                }
182                Decl::Opaque {
183                    head: h,
184                    value,
185                    all,
186                    ..
187                } => {
188                    head(h);
189                    e(value);
190                    all.iter_mut().flatten().for_each(n);
191                }
192                Decl::Quot { head: h, .. } => head(h),
193                Decl::Inductive { types, ctors, recs } => {
194                    for t in types {
195                        head(&mut t.head);
196                        t.all.iter_mut().for_each(n);
197                        t.ctors.iter_mut().for_each(n);
198                    }
199                    for c in ctors {
200                        head(&mut c.head);
201                        n(&mut c.induct);
202                    }
203                    for r in recs {
204                        head(&mut r.head);
205                        r.all.iter_mut().for_each(n);
206                        for rule in &mut r.rules {
207                            n(&mut rule.ctor);
208                            e(&mut rule.rhs);
209                        }
210                    }
211                }
212            },
213        }
214    }
215}
216
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Table {
219    Names,
220    Levels,
221    Exprs,
222}
223
224impl Counts {
225    /// Take the id of `r` if it defines a name, level or expression.
226    pub fn assign(&mut self, r: &Record<'_>) -> Option<u32> {
227        let next = match r.table()? {
228            Table::Names => &mut self.names,
229            Table::Levels => &mut self.levels,
230            Table::Exprs => &mut self.exprs,
231        };
232        *next += 1;
233        Some(*next - 1)
234    }
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
238pub enum Safety {
239    Safe,
240    Unsafe,
241    Partial,
242}
243
244/// The fields every declaration starts with.
245#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
246pub struct Head {
247    pub name: u32,
248    pub level_params: Vec<u32>,
249    pub ty: u32,
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253pub enum Decl {
254    /// `all` is never written by olean-export, but some lean4export versions write it.
255    Axiom {
256        head: Head,
257        is_unsafe: bool,
258        all: Option<Vec<u32>>,
259    },
260    Def {
261        head: Head,
262        value: u32,
263        hints: Hints,
264        safety: Safety,
265        all: Vec<u32>,
266    },
267    Thm {
268        head: Head,
269        value: u32,
270        all: Vec<u32>,
271    },
272    Opaque {
273        head: Head,
274        value: u32,
275        is_unsafe: bool,
276        all: Option<Vec<u32>>,
277    },
278    Quot {
279        head: Head,
280        kind: QuotKind,
281    },
282    Inductive {
283        types: Vec<IndType>,
284        ctors: Vec<IndCtor>,
285        recs: Vec<IndRec>,
286    },
287}
288
289impl Decl {
290    /// The declared name, the first type's for an inductive block.
291    #[must_use]
292    pub fn name(&self) -> Option<u32> {
293        match self {
294            Self::Axiom { head, .. }
295            | Self::Def { head, .. }
296            | Self::Thm { head, .. }
297            | Self::Opaque { head, .. }
298            | Self::Quot { head, .. } => Some(head.name),
299            Self::Inductive { types, .. } => types.first().map(|t| t.head.name),
300        }
301    }
302}
303
304#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
305pub struct IndType {
306    pub head: Head,
307    pub is_unsafe: bool,
308    pub num_params: u64,
309    pub num_indices: u64,
310    pub all: Vec<u32>,
311    pub ctors: Vec<u32>,
312    pub num_nested: u64,
313    pub is_rec: bool,
314    pub is_reflexive: bool,
315}
316
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
318pub struct IndCtor {
319    pub head: Head,
320    pub is_unsafe: bool,
321    pub induct: u32,
322    pub cidx: u64,
323    pub num_params: u64,
324    pub num_fields: u64,
325}
326
327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
328pub struct IndRec {
329    pub head: Head,
330    pub is_unsafe: bool,
331    pub all: Vec<u32>,
332    pub num_params: u64,
333    pub num_indices: u64,
334    pub num_motives: u64,
335    pub num_minors: u64,
336    pub rules: Vec<IndRule>,
337    pub k: bool,
338}
339
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
341pub struct IndRule {
342    pub ctor: u32,
343    pub nfields: u64,
344    pub rhs: u32,
345}
346
347/// A destination for records. `id` is the id `r` defines, if it defines a name, level or
348/// expression; ids count from where the stream started, also across a resumed export.
349pub trait Sink {
350    type Output;
351    fn record(&mut self, id: Option<u32>, r: &Record<'_>) -> Result<()>;
352    fn finish(self) -> Result<Self::Output>;
353}