Skip to main content

olean_export/
inspect.rs

1use crate::{
2    error::{at, Result},
3    olean::{is_scalar, Header, Image},
4};
5use std::path::{Path, PathBuf};
6
7const KINDS: [&str; 8] = [
8    "axiom",
9    "def",
10    "theorem",
11    "opaque",
12    "quot",
13    "inductive",
14    "ctor",
15    "recursor",
16];
17
18/// One entry of a module's import list.
19#[derive(Debug, Clone)]
20pub struct Import {
21    pub module: String,
22    pub all: bool,
23    pub exported: bool,
24    pub meta: bool,
25}
26
27/// A constant as the olean lists it, without its terms.
28#[derive(Debug, Clone)]
29pub struct Decl {
30    pub name: String,
31    pub kind: &'static str,
32    /// `unsafe` or `partial`, or empty.
33    pub safety: &'static str,
34}
35
36/// A slice of the module's data and the bytes only it reaches. Shared objects count toward
37/// the first section that reaches them, in the order constants, extra names, imports, then
38/// environment extensions.
39#[derive(Debug, Clone)]
40pub struct Section {
41    pub name: String,
42    pub items: usize,
43    pub bytes: u64,
44}
45
46/// What one module's olean holds, read straight from its header and `ModuleData` without
47/// decoding any terms.
48#[derive(Debug, Clone)]
49pub struct Summary {
50    pub header: Header,
51    pub parts: Vec<(PathBuf, u64)>,
52    pub is_module: bool,
53    pub imports: Vec<Import>,
54    pub consts: Vec<Decl>,
55    pub extra: Vec<String>,
56    pub sections: Vec<Section>,
57}
58
59impl Summary {
60    pub fn open(path: &Path) -> Result<Self> {
61        Self::read(path).map_err(at(path))
62    }
63
64    fn read(path: &Path) -> Result<Self> {
65        let img = Image::open_module(path)?;
66        let root = img.root;
67        let is_module = img.parts.len() > 1;
68        let paths = if is_module {
69            vec![
70                path.to_owned(),
71                path.with_extension("olean.server"),
72                path.with_extension("olean.private"),
73            ]
74        } else {
75            vec![path.to_owned()]
76        };
77        let parts = paths
78            .into_iter()
79            .zip(&img.parts)
80            .map(|(p, part)| (p, part.bytes.len() as u64))
81            .collect();
82
83        let field = |i| img.field(root, i);
84        let [imports, consts, extra, entries] =
85            [0, 2, 3, 4].map(|i| field(i).and_then(|o| img.array(o)));
86        let imports: Vec<Import> = imports?
87            .into_iter()
88            .map(|i| {
89                Ok(Import {
90                    module: img.str_name(img.field(i, 0)?)?,
91                    all: img.scalar_u8(i, 0)? != 0,
92                    exported: img.scalar_u8(i, 1)? != 0,
93                    meta: img.scalar_u8(i, 2)? != 0,
94                })
95            })
96            .collect::<Result<_>>()?;
97        let consts: Vec<Decl> = consts?
98            .into_iter()
99            .map(|c| decl(&img, c))
100            .collect::<Result<_>>()?;
101        let extra: Vec<String> = extra?
102            .into_iter()
103            .map(|n| img.str_name(n))
104            .collect::<Result<_>>()?;
105
106        let mut seen = vec![false; img.slots()];
107        let mut section = |name: String, items: usize, roots: &[u64]| {
108            Ok::<_, crate::Error>(Section {
109                name,
110                items,
111                bytes: reach(&img, &mut seen, roots)?,
112            })
113        };
114        let mut sections = vec![
115            section("constants".into(), consts.len(), &[field(1)?, field(2)?])?,
116            section("extra names".into(), extra.len(), &[field(3)?])?,
117            section("imports".into(), imports.len(), &[field(0)?])?,
118        ];
119        for e in entries? {
120            let name = img.str_name(img.field(e, 0)?)?;
121            let items = img.array(img.field(e, 1)?)?.len();
122            sections.push(section(name, items, &[e])?);
123        }
124        Ok(Self {
125            header: img.header.clone(),
126            parts,
127            is_module,
128            imports,
129            consts,
130            extra,
131            sections,
132        })
133    }
134
135    /// Total size of every part on disk.
136    #[must_use]
137    pub fn bytes(&self) -> u64 {
138        self.parts.iter().map(|p| p.1).sum()
139    }
140}
141
142fn decl(img: &Image, info: u64) -> Result<Decl> {
143    let tag = img.tag(info)?;
144    let val = img.field(info, 0)?;
145    let flag = |k| Ok::<_, crate::Error>(img.scalar_u8(val, k)? != 0);
146    let safety = match tag {
147        1 => match img.scalar_u8(val, 0)? {
148            0 => "unsafe",
149            1 => "",
150            _ => "partial",
151        },
152        0 | 3 | 6 if flag(0)? => "unsafe",
153        5 | 7 if flag(1)? => "unsafe",
154        _ => "",
155    };
156    Ok(Decl {
157        name: img.str_name(img.field(img.field(val, 0)?, 0)?)?,
158        kind: KINDS.get(usize::from(tag)).copied().unwrap_or("?"),
159        safety,
160    })
161}
162
163/// Bytes of the objects reachable from `roots` that no earlier call reached.
164fn reach(img: &Image, seen: &mut [bool], roots: &[u64]) -> Result<u64> {
165    let mut stack: Vec<u64> = roots.iter().copied().filter(|&o| !is_scalar(o)).collect();
166    let mut bytes = 0;
167    while let Some(o) = stack.pop() {
168        let slot = img.slot(o)?;
169        if !std::mem::replace(&mut seen[slot], true) {
170            bytes += img.children(o, |c| stack.push(c))?;
171        }
172    }
173    Ok(bytes)
174}