Skip to main content

fic/foreign/
export.rs

1//! Exporting the data layer: the `.fis` structs and folded constants,
2//! written for each foreign language as a header under
3//! `<project>/include/gen/`, before any import is read, from the `.fis`
4//! typed on its own (its programs set aside). Every tool gets
5//! `<project>/include` on its include path; the rest of `include/` is the
6//! user's.
7//!
8//! The other direction of the FFI boundary from `load` and `extract`. Each
9//! language's [`Header`] supplies its spelling (`c/header.rs` → `types.h`,
10//! `pnk/header.rs` → `types.pnk`); this module owns the file's skeleton, the
11//! folded constants, and the writing.
12//!
13//! A project that imports C also gets `gen/mem.h` ([`c::MEM_H`]): the
14//! contracts of the memory routines fic links into every PD, for its C to
15//! include. That one is the same for every project.
16
17use std::fmt::Write as _;
18use std::fs;
19use std::path::{Path, PathBuf};
20use std::process;
21use std::sync::atomic::{AtomicUsize, Ordering};
22
23use anyhow::{bail, Context, Result};
24
25use super::{c, pnk, ForeignKind};
26use crate::ast::RawAst;
27use crate::tast::{Const, Struct, TyEnv};
28
29/// The include directory, relative to the project.
30pub const DIR: &str = "include";
31
32/// The first line of every file fic writes.
33pub const MARKER: &str = "/* Generated by fic";
34
35/// One foreign language's data-layer header.
36pub trait Header {
37    /// Its file name under `include/gen/`.
38    fn file(&self) -> &'static str;
39
40    /// Whether `rawast` needs it.
41    fn needed(&self, rawast: &RawAst) -> bool;
42
43    /// The include-guard macro.
44    fn guard(&self) -> &'static str;
45
46    /// Text after the guard, before the declarations.
47    fn preamble(&self, _out: &mut String) {}
48
49    /// One struct, laid out.
50    fn structure(&self, _out: &mut String, _tenv: &TyEnv, _s: &Struct) {}
51
52    /// The constants, folded, in declaration order.
53    fn constants(&self, out: &mut String, tenv: &TyEnv, consts: &[&Const]);
54}
55
56/// Every language's header.
57const HEADERS: [&dyn Header; 2] = [&c::C, &pnk::Pancake];
58
59/// Write each header `rawast` needs, from its data layer `tenv` (typed by
60/// `tast::build_data`). Returns `<project>/include`.
61///
62/// # Errors
63///
64/// An I/O failure, or a file there that fic did not write ([`MARKER`]).
65pub fn export(project: &Path, rawast: &RawAst, tenv: &TyEnv) -> Result<PathBuf> {
66    let include = project.join(DIR);
67    let needed: Vec<&dyn Header> = HEADERS.into_iter().filter(|h| h.needed(rawast)).collect();
68    let imports_c = rawast.programs.iter().flat_map(|p| &p.imports).any(|i| {
69        matches!(
70            ForeignKind::of(&i.path),
71            Some(ForeignKind::CHeader | ForeignKind::CSource)
72        )
73    });
74    if !needed.is_empty() || imports_c {
75        let gen = include.join("gen");
76        fs::create_dir_all(&gen).with_context(|| format!("failed to create {}", gen.display()))?;
77        for header in needed {
78            write_generated(&gen.join(header.file()), &render(header, tenv))?;
79        }
80        if imports_c {
81            write_generated(&gen.join(MEM_FILE), &mem_h())?;
82        }
83    }
84    Ok(include)
85}
86
87/// The memory routines' header, under `include/gen/`.
88pub const MEM_FILE: &str = "mem.h";
89
90/// [`c::MEM_H`] as fic writes it: one [`MARKER`] line, then the file as it
91/// is. `fire verify` holds a project's copy to exactly that, since the
92/// contracts are proved of fic's routines and of no edited text.
93fn mem_h() -> String {
94    format!(
95        "{MARKER}: the memory routines of a PD's runtime. Do not edit. */\n{}",
96        c::MEM_H
97    )
98}
99
100/// `header`'s file for the typed `.fis`.
101pub(crate) fn render(header: &dyn Header, tenv: &TyEnv) -> String {
102    skeleton(
103        header,
104        header.guard(),
105        "from the .fis on every build",
106        |out| {
107            for s in tenv.structs.iter() {
108                header.structure(out, tenv, s);
109            }
110            let consts: Vec<&Const> = tenv.consts.iter().collect();
111            header.constants(out, tenv, &consts);
112        },
113    )
114}
115
116/// A header file in `header`'s language: [`MARKER`] naming its `origin`,
117/// then inside `guard` the preamble and `body`.
118pub(crate) fn skeleton(
119    header: &dyn Header,
120    guard: &str,
121    origin: &str,
122    body: impl FnOnce(&mut String),
123) -> String {
124    let mut out = format!("{MARKER} {origin}. Do not edit. */\n");
125    let _ = writeln!(out, "#ifndef {guard}\n#define {guard}\n");
126    header.preamble(&mut out);
127    body(&mut out);
128    let _ = writeln!(out, "\n#endif /* {guard} */");
129    out
130}
131
132/// Distinguishes this process's temporary files.
133static TMP_SEQ: AtomicUsize = AtomicUsize::new(0);
134
135/// Write `content`, unless `path` is a file fic did not write. Written
136/// beside and renamed into place, so a concurrent run never reads it partial.
137fn write_generated(path: &Path, content: &str) -> Result<()> {
138    if let Ok(existing) = fs::read_to_string(path) {
139        if !existing.starts_with(MARKER) {
140            bail!(
141                "{} exists and was not generated by fic; it is where fic writes the \
142                 `.fis` data layer — move or rename it",
143                path.display()
144            );
145        }
146    }
147    let tmp = path.with_extension(format!(
148        "tmp.{}.{}",
149        process::id(),
150        TMP_SEQ.fetch_add(1, Ordering::Relaxed)
151    ));
152    fs::write(&tmp, content).with_context(|| format!("failed to write {}", tmp.display()))?;
153    fs::rename(&tmp, path).with_context(|| format!("failed to write {}", path.display()))
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use crate::parser::{parse_program, parse_system};
160    use crate::{rast, tast};
161
162    /// [`export`] of the `.fis` `fis` into `dir`, from its data layer.
163    fn exported(dir: &Path, fis: &str) -> Result<PathBuf> {
164        let rawast = RawAst {
165            system: parse_system(fis).unwrap(),
166            programs: Vec::new(),
167        };
168        let (env, _) = rast::build_data(&rawast).unwrap();
169        let (tenv, _) = tast::build_data(&env).unwrap();
170        export(dir, &rawast, &tenv)
171    }
172
173    fn temp_project(name: &str) -> PathBuf {
174        let dir = std::env::temp_dir().join(format!("fic-export-{name}-{}", process::id()));
175        let _ = fs::remove_dir_all(&dir);
176        fs::create_dir_all(&dir).unwrap();
177        dir
178    }
179
180    #[test]
181    fn writes_types_h_for_a_data_layer() {
182        let dir = temp_project("data");
183        let include = exported(&dir, "const N: int = 3;\nProtectionDomain a(1);").unwrap();
184        assert_eq!(include, dir.join("include"));
185        let h = fs::read_to_string(dir.join("include/gen/types.h")).unwrap();
186        assert!(h.starts_with(MARKER));
187        assert!(h.contains("#define N 3"));
188        assert!(
189            !dir.join("include/gen/types.pnk").exists(),
190            "no Pancake import"
191        );
192    }
193
194    #[test]
195    fn writes_mem_h_for_a_project_that_imports_c() {
196        let dir = temp_project("mem");
197        let rawast = RawAst {
198            system: parse_system("ProtectionDomain a(1);").unwrap(),
199            programs: vec![parse_program("import \"include/eth.h\" as eth;").unwrap()],
200        };
201        let (env, _) = rast::build_data(&rawast).unwrap();
202        let (tenv, _) = tast::build_data(&env).unwrap();
203        export(&dir, &rawast, &tenv).unwrap();
204        let h = fs::read_to_string(dir.join("include/gen/mem.h")).unwrap();
205        assert!(h.starts_with(MARKER));
206        assert!(h.contains("void *memcpy(") && h.contains("void fi_memcpy_u8("));
207        assert!(!dir.join("include/gen/types.h").exists(), "no data layer");
208    }
209
210    #[test]
211    fn writes_nothing_without_a_data_layer() {
212        let dir = temp_project("empty");
213        exported(&dir, "ProtectionDomain a(1);").unwrap();
214        assert!(!dir.join("include").exists());
215    }
216
217    #[test]
218    fn refuses_to_replace_a_users_file() {
219        let dir = temp_project("user");
220        fs::create_dir_all(dir.join("include/gen")).unwrap();
221        fs::write(dir.join("include/gen/types.h"), "/* mine */\n").unwrap();
222        let err = exported(&dir, "const N: int = 3;\nProtectionDomain a(1);").unwrap_err();
223        assert!(err.to_string().contains("not generated by fic"), "{err}");
224        assert_eq!(
225            fs::read_to_string(dir.join("include/gen/types.h")).unwrap(),
226            "/* mine */\n"
227        );
228    }
229
230    #[test]
231    fn replaces_its_own_file() {
232        let dir = temp_project("own");
233        let fis = "const N: int = 3;\nProtectionDomain a(1);";
234        exported(&dir, fis).unwrap();
235        exported(&dir, &fis.replace('3', "4")).unwrap();
236        let h = fs::read_to_string(dir.join("include/gen/types.h")).unwrap();
237        assert!(h.contains("#define N 4"));
238    }
239}