Skip to main content

fic/emit/
c.rs

1//! `--emit=c`: the C backend's sources, written to `<project>/build/gen/`
2//! (or `-o`) and not compiled.
3
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use anyhow::{Context, Result};
8
9use crate::c_backend::generate;
10use crate::ccfg::System;
11use crate::foreign::ForeignModules;
12use crate::tast::Tast;
13
14/// Write the generated C sources to `<dir>/build/gen/`, or `out_dir`, and
15/// return the directory written to. Every PD with a program must bind
16/// `microkit.init` and `microkit.notified`; [`generate`] reports a missing
17/// one.
18pub fn write(
19    dir: &Path,
20    tast: &Tast,
21    ccfg: &System,
22    foreign: &ForeignModules,
23    out_dir: Option<&PathBuf>,
24) -> Result<PathBuf> {
25    let gen_dir = out_dir.cloned().unwrap_or_else(|| dir.join("build/gen"));
26    fs::create_dir_all(&gen_dir)
27        .with_context(|| format!("failed to create {}", gen_dir.display()))?;
28    let files = generate(tast, ccfg, foreign)?;
29    for f in &files {
30        f.write(&gen_dir)?;
31    }
32    eprintln!(
33        "  \u{2713} Generated {} C file(s) in {}",
34        files.len(),
35        gen_dir.display()
36    );
37    Ok(gen_dir)
38}