Skip to main content

fic/foreign/
load.rs

1//! Loading imports: every file the programs import is read once, by its
2//! language's [`Reader`], into the [`ForeignModules`] store, which records
3//! the file each written path names. The AST is read, never written.
4//!
5//! A reader turns a file into its exported functions with their surface
6//! signatures and each function's contract as written: the FFI spec. Each
7//! language's reader lives in its directory (`c/clang.rs`, `pnk/pnk.rs`).
8
9use std::fs::{self, read_to_string};
10use std::path::{Path, PathBuf};
11
12use anyhow::{anyhow, Result};
13
14use super::{c, pnk, ForeignKind, ForeignLang, ForeignModule, ForeignModules};
15use crate::ast::RawAst;
16use crate::error::{format_errors, Diagnostic};
17
18/// One foreign language's reader.
19pub trait Reader {
20    /// The exported functions of `src`. `file` is where it is on disk, so a
21    /// C file's `#include "sibling.h"` resolves against its own directory;
22    /// `path` is the module's identity (see [`ForeignModules`]); the two
23    /// coincide in tests. `includes` join a C file's include path.
24    ///
25    /// # Errors
26    ///
27    /// A message for a diagnostic at the `import` naming the file.
28    fn read(
29        &self,
30        src: &str,
31        file: &Path,
32        path: PathBuf,
33        includes: &[PathBuf],
34    ) -> Result<ForeignModule, String>;
35}
36
37/// The reader for `lang`; `c` reads C.
38fn reader(lang: ForeignLang, c: &c::Libclang) -> &dyn Reader {
39    match lang {
40        ForeignLang::C => c,
41        ForeignLang::Pancake => &pnk::Pancake,
42    }
43}
44
45/// Read one imported file with its language's [`Reader`].
46///
47/// # Errors
48///
49/// The reader's: for C, libclang could not be loaded.
50pub fn parse(
51    src: &str,
52    file: &Path,
53    path: PathBuf,
54    lang: ForeignLang,
55    includes: &[PathBuf],
56) -> Result<ForeignModule, String> {
57    reader(lang, &c::Libclang::default()).read(src, file, path, includes)
58}
59
60/// Load every import of `rawast`'s programs, one libclang for all its C
61/// files, then record each program's files ([`ForeignModules::bind`]). A C
62/// file is read with the include path the image build compiles it with: the
63/// project directory `dir`, then `include`, then `extra`.
64///
65/// # Errors
66///
67/// A missing or unreadable file, or one its reader rejects, reported at the
68/// `import` that names it.
69pub fn load(
70    dir: &Path,
71    include: &Path,
72    extra: &[PathBuf],
73    rawast: &RawAst,
74) -> Result<ForeignModules> {
75    let mut includes = vec![dir.to_path_buf(), include.to_path_buf()];
76    includes.extend_from_slice(extra);
77    let c = c::Libclang::default();
78    let mut modules = ForeignModules::new();
79    let pds = rawast.system.protection_domains.iter();
80    for (pd, program) in pds.zip(&rawast.programs) {
81        let file = pd.fi.display().to_string();
82        for import in &program.imports {
83            let written = import.path.clone();
84            let span = import.span.clone();
85            let report = |msg: String| {
86                let mut diag = Diagnostic::at(msg, span.clone(), file.clone());
87                diag.resolve_source();
88                anyhow!("{}", format_errors(&[diag], &file))
89            };
90            let Some(kind) = ForeignKind::of(&written) else {
91                return Err(report(format!(
92                    "import \"{}\": not a C or Pancake file",
93                    written.display()
94                )));
95            };
96            let source = read_to_string(dir.join(&written)).map_err(|err| {
97                report(format!(
98                    "import \"{}\": cannot read the file: {err}",
99                    written.display()
100                ))
101            })?;
102            let (on_disk, path) = resolve(dir, &written).map_err(|err| {
103                report(format!(
104                    "import \"{}\": cannot resolve the path: {err}",
105                    written.display()
106                ))
107            })?;
108            let id = if let Some(id) = modules.module(&path) {
109                id
110            } else {
111                let module = reader(kind.lang(), &c)
112                    .read(&source, &on_disk, path.clone(), &includes)
113                    .map_err(|err| report(format!("import \"{}\": {err}", written.display())))?;
114                modules.insert(module)
115            };
116            modules.record(written, id);
117        }
118    }
119    modules.bind(rawast);
120    Ok(modules)
121}
122
123/// Where an import's file is, and its identity: the canonical path (`.`,
124/// `..`, symlinks and on-disk casing resolved), and that path relative to
125/// the canonical project directory — or absolute, for a file outside it.
126fn resolve(dir: &Path, written: &Path) -> std::io::Result<(PathBuf, PathBuf)> {
127    let file = fs::canonicalize(dir.join(written))?;
128    let root = fs::canonicalize(dir)?;
129    let identity = file
130        .strip_prefix(&root)
131        .map_or_else(|_| file.clone(), Path::to_path_buf);
132    Ok((file, identity))
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn pancake_is_read_without_a_toolchain() {
141        let m = parse(
142            "export fun 1 f(1 x) { return x; }",
143            Path::new("d.pnk"),
144            PathBuf::from("d.pnk"),
145            ForeignLang::Pancake,
146            &[],
147        )
148        .unwrap();
149        assert_eq!(m.exports.len(), 1);
150        assert_eq!(m.lang(), ForeignLang::Pancake);
151    }
152}