Skip to main content

fic/foreign/
module.rs

1//! The shared types of `foreign/`: the loaded-modules store and what each
2//! imported file is read into — its exported functions with their surface
3//! signatures, and each function's contract as the reader found it.
4
5use std::collections::BTreeMap;
6use std::fmt;
7use std::ops::Range;
8use std::path::{Path, PathBuf};
9
10use serde::Serialize;
11
12use crate::ast::RawAst;
13use crate::base::{FfnId, IdVec, ModuleId, PdId};
14
15/// The foreign files a project has loaded, one [`ForeignModule`] per
16/// distinct file — the *loaded-modules store*, not part of the AST.
17///
18/// An `import` is an AST item of the program that writes it
19/// ([`Import`](crate::ast::Import)); what the imported file *contains* is
20/// shared by every program that imports it, so it lives here, beside the
21/// [`RawAst`] rather than inside it — the split
22/// every compiler that reads foreign declarations makes (rustc's `CStore`
23/// beside `ast::Crate`, Swift's `ASTContext` loaded modules beside the
24/// `SourceFile`s, GHC's `HscEnv`). Built by the driver after all programs
25/// are parsed, each file numbered by its `ModuleId`. `rast` resolves a
26/// call through an import's alias to a function of that file and records
27/// where each called function is, by its `FfnId` (`ffis`); the backends
28/// read the files, the called functions and each program's links here.
29///
30/// A file's identity is its **normalised** project-relative path — canonicalised
31/// (so `c/util.h`, `./c/util.h`, `c/../c/util.h` and, on a
32/// case-insensitive filesystem, `C/Util.h` are one file) and then made
33/// relative to the project directory again, so keys carry no machine-
34/// specific prefix; a file outside the project keeps its canonical absolute
35/// path.
36#[derive(Debug, Clone, Default, Serialize)]
37pub struct ForeignModules {
38    /// Each file, once, numbered in the order it was first read.
39    pub modules: IdVec<ModuleId, ForeignModule>,
40    /// Each program's imported files, by its protection domain, in import
41    /// order: what its image links.
42    pub links: IdVec<PdId, Vec<Link>>,
43    /// Where each function some program calls is, by the id `rast` gave
44    /// it.
45    pub ffis: IdVec<FfnId, ForeignFnRef>,
46    /// Each file's identity, and each path an `import` is written with, to
47    /// the file it names.
48    ids: BTreeMap<PathBuf, ModuleId>,
49}
50
51impl ForeignModules {
52    /// An empty store.
53    pub fn new() -> Self {
54        Self::default()
55    }
56
57    /// Add a loaded module under its (normalised) path, which also names it
58    /// as written; returns its id. A second module for the same path is
59    /// ignored, and the first one's id returned.
60    pub fn insert(&mut self, module: ForeignModule) -> ModuleId {
61        if let Some(&id) = self.ids.get(&module.path) {
62            return id;
63        }
64        let path = module.path.clone();
65        let id = self.modules.push(module);
66        self.ids.insert(path, id);
67        id
68    }
69
70    /// Record that an import written as `written` names the file `id`.
71    pub fn record(&mut self, written: PathBuf, id: ModuleId) {
72        self.ids.insert(written, id);
73    }
74
75    /// The file an import written as `written`, or a file's identity, names,
76    /// once it has been loaded.
77    pub fn module(&self, written: &Path) -> Option<ModuleId> {
78        self.ids.get(written).copied()
79    }
80
81    /// Record each program's imported files, by its position among
82    /// `rawast`'s programs (its protection domain's id once bound), each
83    /// as its first import of the file writes it; an import whose file was
84    /// not loaded is left out.
85    pub fn bind(&mut self, rawast: &RawAst) {
86        self.links = rawast
87            .programs
88            .iter()
89            .map(|p| {
90                let mut files: Vec<Link> = Vec::new();
91                for i in &p.imports {
92                    let (Some(module), Some(kind)) =
93                        (self.module(&i.path), ForeignKind::of(&i.path))
94                    else {
95                        continue;
96                    };
97                    if !files.iter().any(|l| l.module == module) {
98                        files.push(Link {
99                            module,
100                            path: i.path.clone(),
101                            kind,
102                        });
103                    }
104                }
105                files
106            })
107            .collect();
108    }
109
110    /// The called function `f`: its file, and its declaration there.
111    #[must_use]
112    pub fn function(&self, f: FfnId) -> (&ForeignModule, &ForeignFn) {
113        let ForeignFnRef { module, index } = self.ffis[f];
114        let module = &self.modules[module];
115        (module, &module.exports[index as usize])
116    }
117
118    /// The files program `pd` imports; none for a program the store did not
119    /// link.
120    #[must_use]
121    pub fn linked(&self, pd: PdId) -> &[Link] {
122        self.links.get(pd).map_or(&[], Vec::as_slice)
123    }
124
125    /// Number of loaded modules.
126    pub fn len(&self) -> usize {
127        self.modules.len()
128    }
129
130    /// Whether nothing has been loaded.
131    pub fn is_empty(&self) -> bool {
132        self.modules.is_empty()
133    }
134}
135
136/// Where a foreign function is: its file, and its position among that
137/// file's exports.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
139pub struct ForeignFnRef {
140    /// The file.
141    pub module: ModuleId,
142    /// Index into the file's [`exports`](ForeignModule::exports).
143    pub index: u32,
144}
145
146/// A file a program imports, as its first import of it writes it.
147#[derive(Debug, Clone, Serialize)]
148pub struct Link {
149    /// The file.
150    pub module: ModuleId,
151    /// Its path as written, relative to the project.
152    pub path: PathBuf,
153    /// What it is, from the written path's extension.
154    pub kind: ForeignKind,
155}
156
157/// The language an imported file is written in — decided by its extension.
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
159pub enum ForeignLang {
160    /// `.c` / `.h`
161    C,
162    /// `.pnk`
163    Pancake,
164}
165
166impl fmt::Display for ForeignLang {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        f.write_str(match self {
169            ForeignLang::C => "C",
170            ForeignLang::Pancake => "Pancake",
171        })
172    }
173}
174
175/// What an imported file is, decided from its extension in one place
176/// (the front end, as it binds a program's imports): its language, and for
177/// C whether it is a header (a separately compiled driver, its `.c` linked
178/// beside the unit) or a source (inlined into the unit).
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
180pub enum ForeignKind {
181    /// `.h`
182    CHeader,
183    /// `.c`
184    CSource,
185    /// `.pnk`
186    Pancake,
187}
188
189impl ForeignKind {
190    /// The kind of the file at `path`, by its extension; `None` for a file
191    /// fic cannot read.
192    #[must_use]
193    pub fn of(path: &Path) -> Option<Self> {
194        match path.extension().and_then(|e| e.to_str()) {
195            Some("h") => Some(Self::CHeader),
196            Some("c") => Some(Self::CSource),
197            Some("pnk") => Some(Self::Pancake),
198            _ => None,
199        }
200    }
201
202    /// The file's language.
203    #[must_use]
204    pub fn lang(self) -> ForeignLang {
205        match self {
206            Self::CHeader | Self::CSource => ForeignLang::C,
207            Self::Pancake => ForeignLang::Pancake,
208        }
209    }
210
211    /// Whether the file is a C header.
212    #[must_use]
213    pub fn header(self) -> bool {
214        self == Self::CHeader
215    }
216}
217
218/// One imported file and the functions it exports. Shared by every program
219/// that imports the same file: it is read and parsed once, into
220/// [`ForeignModules`], which keeps it.
221#[derive(Debug, Clone, Serialize)]
222pub struct ForeignModule {
223    /// The file's identity: its normalised project-relative path (see
224    /// [`ForeignModules`]), what an [`Import`](crate::ast::Import) resolves
225    /// to.
226    pub path: PathBuf,
227    /// Where the file was read from on disk.
228    pub file: PathBuf,
229    /// The include path it was read with; a verifier reads it the same way.
230    pub includes: Vec<PathBuf>,
231    /// What the file is, from its extension: its language, and for C
232    /// whether it is a header.
233    pub kind: ForeignKind,
234    /// Every function the file exports, in source order; the first
235    /// declaration of a name wins.
236    pub exports: Vec<ForeignFn>,
237    /// Each function's contract as written, by name.
238    pub contracts: BTreeMap<String, ForeignContract>,
239}
240
241impl ForeignModule {
242    /// The file's language.
243    #[must_use]
244    pub fn lang(&self) -> ForeignLang {
245        self.kind.lang()
246    }
247
248    /// The export named `name`, if the file has one.
249    #[must_use]
250    pub fn export(&self, name: &str) -> Option<&ForeignFn> {
251        self.exports.iter().find(|f| f.name == name)
252    }
253}
254
255/// A foreign function as the imported file declares it.
256#[derive(Debug, Clone, Serialize)]
257pub struct ForeignFn {
258    /// The symbol name — what a call site names after the alias.
259    pub name: String,
260    /// Parameters, in order.
261    pub params: Vec<ForeignParam>,
262    /// Return type ([`ForeignType::Void`] for a procedure).
263    pub ret: ForeignType,
264    /// Trailing `...` (C only).
265    pub variadic: bool,
266    /// Byte span of the declaration in the imported file (the module's
267    /// `path` is the diagnostic filename).
268    pub span: Range<usize>,
269}
270
271/// The verifier side of a [`ForeignFn`]: its contract as written, and why
272/// it is impure. Lifted into the neutral IR at extraction.
273#[derive(Debug, Clone, Serialize)]
274pub struct ForeignContract {
275    /// The contract's blocks in source order: Pancake's `/@ … @/`, C's
276    /// `/*@ … */` and `//@`.
277    pub contracts: Vec<Annotation>,
278    /// Why a call has a side effect, when the reader found one — an FFI
279    /// call, a store, a shared-memory access, `raise`, a global written,
280    /// directly or through a callee. `None` for a pure function, or a reader
281    /// that does not look (C).
282    pub impurity: Option<String>,
283}
284
285/// One verifier annotation of a foreign declaration, as written.
286#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
287pub struct Annotation {
288    /// The text inside the annotation delimiters, trimmed.
289    pub text: String,
290    /// Byte span of the whole annotation in the imported file.
291    pub span: Range<usize>,
292}
293
294/// One parameter of a [`ForeignFn`]. The name is informational — C
295/// prototypes may omit it (`int f(int)`).
296#[derive(Debug, Clone, Serialize)]
297pub struct ForeignParam {
298    /// Parameter name, if the declaration gives one.
299    pub name: Option<String>,
300    /// Parameter type.
301    pub ty: ForeignType,
302}
303
304/// A type at a C-ABI boundary, as spelled in the foreign language and
305/// reduced to what fic can reason about. Qualifiers (`const`, `volatile`)
306/// are dropped; they do not change the call.
307#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
308pub enum ForeignType {
309    /// `void` — no value (return position only).
310    Void,
311    /// A scalar as spelled: `"int"`, `"unsigned int"`, `"uint8_t"`,
312    /// `"bool"`, `"uintptr_t"`, Rust `"u32"`. Width and signedness are
313    /// resolved by the type system, which knows the target.
314    Scalar(String),
315    /// A pointer to the given type (`const uint8_t *` → `Pointer(Scalar("uint8_t"))`).
316    Pointer(Box<ForeignType>),
317    /// A struct by name, by value (`struct Slot`, Rust `#[repr(C)] Slot`).
318    Struct(String),
319    /// A Pancake machine word (the only argument/return shape an
320    /// `export fun` may use).
321    Word,
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use crate::base::Idx;
328
329    #[test]
330    fn lang_display() {
331        assert_eq!(ForeignLang::Pancake.to_string(), "Pancake");
332    }
333
334    #[test]
335    fn each_program_links_every_file_it_imports_once() {
336        use crate::foreign::parse;
337        use crate::rast::env::ast_of;
338
339        let rawast = ast_of(
340            "ProtectionDomain a(1);\nProtectionDomain b(2);",
341            &[
342                (
343                    "a",
344                    "import \"x.pnk\" as x;\nimport \"y.pnk\" as y;\nimport \"x.pnk\" as z;",
345                ),
346                ("b", "import \"y.pnk\" as y;\nimport \"gone.pnk\" as g;"),
347            ],
348        );
349        let mut foreign = ForeignModules::new();
350        for path in ["x.pnk", "y.pnk"] {
351            let src = "export fun 1 f() { return 0; }";
352            let m = parse(src, Path::new(path), path.into(), ForeignLang::Pancake, &[]);
353            foreign.insert(m.expect("reads"));
354        }
355        foreign.bind(&rawast);
356        let (x, y) = (ModuleId::new(0), ModuleId::new(1));
357        // Nothing is called: each import still links its file, once.
358        let modules = |pd| -> Vec<ModuleId> {
359            foreign
360                .linked(PdId::new(pd))
361                .iter()
362                .map(|l| l.module)
363                .collect()
364        };
365        assert_eq!(modules(0), [x, y]);
366        // A file never read is left out.
367        assert_eq!(modules(1), [y]);
368        assert!(foreign.linked(PdId::new(2)).is_empty());
369    }
370}