Skip to main content

olean_export/
inspect.rs

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