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.
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, consts, extra, entries] =
88            [0, 2, 3, 4].map(|i| field(i).and_then(|o| img.array(o)));
89        let imports: Vec<Import> = imports?
90            .into_iter()
91            .map(|i| {
92                Ok(Import {
93                    module: img.str_name(img.field(i, 0)?)?,
94                    all: img.scalar_u8(i, 0)? != 0,
95                    exported: img.scalar_u8(i, 1)? != 0,
96                    meta: img.scalar_u8(i, 2)? != 0,
97                })
98            })
99            .collect::<Result<_>>()?;
100        let consts: Vec<Decl> = consts?
101            .into_iter()
102            .map(|c| decl(&img, c))
103            .collect::<Result<_>>()?;
104        let extra: Vec<String> = extra?
105            .into_iter()
106            .map(|n| img.str_name(n))
107            .collect::<Result<_>>()?;
108
109        let mut seen = vec![false; img.slots()];
110        let mut section = |name: String, items: usize, roots: &[u64]| {
111            Ok::<_, crate::Error>(Section {
112                name,
113                items,
114                bytes: reach(&img, &mut seen, roots)?,
115            })
116        };
117        let mut sections = vec![
118            section("constants".into(), consts.len(), &[field(1)?, field(2)?])?,
119            section("extra names".into(), extra.len(), &[field(3)?])?,
120            section("imports".into(), imports.len(), &[field(0)?])?,
121        ];
122        for e in entries? {
123            let name = img.str_name(img.field(e, 0)?)?;
124            let items = img.array(img.field(e, 1)?)?.len();
125            sections.push(section(name, items, &[e])?);
126        }
127        Ok(Self {
128            header: img.header.clone(),
129            parts,
130            is_module,
131            imports,
132            consts,
133            extra,
134            sections,
135        })
136    }
137
138    /// Total size of every part on disk.
139    #[must_use]
140    pub fn bytes(&self) -> u64 {
141        self.parts.iter().map(|p| p.1).sum()
142    }
143}
144
145fn decl(img: &Image, info: u64) -> Result<Decl> {
146    let tag = img.tag(info)?;
147    let val = img.field(info, 0)?;
148    let safety = match img.safety(info)? {
149        Safety::Safe => "",
150        Safety::Unsafe => "unsafe",
151        Safety::Partial => "partial",
152    };
153    Ok(Decl {
154        name: img.str_name(img.field(img.field(val, 0)?, 0)?)?,
155        kind: KINDS.get(usize::from(tag)).copied().unwrap_or("?"),
156        safety,
157    })
158}
159
160/// Bytes of the objects reachable from `roots` that no earlier call reached.
161fn reach(img: &Image, seen: &mut [bool], roots: &[u64]) -> Result<u64> {
162    let mut stack: Vec<u64> = roots.iter().copied().filter(|&o| !is_scalar(o)).collect();
163    let mut bytes = 0;
164    while let Some(o) = stack.pop() {
165        let slot = img.slot(o)?;
166        if !mem::replace(&mut seen[slot], true) {
167            bytes += img.children(o, |c| stack.push(c))?;
168        }
169    }
170    Ok(bytes)
171}