bitloom 0.1.2

Bitloom CLI (crates.io: bitloom; cargo subcommand binary cargo-bitloom). Unrelated to samitbasu/rhdl.
//! Optional HLS front-end: emit host C and call pinned Bambu (AD-25 / FR35).
//! Never implements scheduling inside rhdl crates.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Pinned external HLS backend (AD-25).
pub const HLS_BACKEND: &str = "bambu";

#[derive(Debug)]
pub enum HlsError {
    Message(String),
}

impl std::fmt::Display for HlsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HlsError::Message(m) => write!(f, "{m}"),
        }
    }
}

impl std::error::Error for HlsError {}

pub fn hls_enabled() -> bool {
    matches!(
        std::env::var("RHDL_HLS_ENABLE").as_deref(),
        Ok("1") | Ok("true") | Ok("yes")
    )
}

/// Emit a trivial C stub the external tool accepts (no in-crate scheduling).
pub fn emit_c_stub(fn_name: &str, out_dir: &Path) -> Result<PathBuf, HlsError> {
    fs::create_dir_all(out_dir).map_err(|e| HlsError::Message(e.to_string()))?;
    let path = out_dir.join(format!("{fn_name}.c"));
    let body = format!(
        "/* generated by bitloom for {HLS_BACKEND}; no scheduling in bitloom */\n\
         unsigned {fn_name}(unsigned a, unsigned b) {{\n\
           return a + b;\n\
         }}\n"
    );
    fs::write(&path, body).map_err(|e| HlsError::Message(e.to_string()))?;
    Ok(path)
}

/// Run pinned Bambu when enabled; otherwise report unsupported.
pub fn run_hls(fn_name: &str, out_dir: &Path) -> Result<PathBuf, HlsError> {
    if !hls_enabled() {
        return Err(HlsError::Message(
            "HLS unsupported unless RHDL_HLS_ENABLE=1 (AD-25); pinned backend is bambu".into(),
        ));
    }
    let c = emit_c_stub(fn_name, out_dir)?;
    let bambu = std::env::var_os("RHDL_BAMBU_PATH")
        .map(PathBuf::from)
        .or_else(|| which("bambu"));
    let Some(bambu) = bambu else {
        return Err(HlsError::Message(
            "RHDL_HLS_ENABLE=1 but bambu not found; set RHDL_BAMBU_PATH or install bambu".into(),
        ));
    };
    let status = Command::new(&bambu)
        .arg(&c)
        .current_dir(out_dir)
        .status()
        .map_err(|e| HlsError::Message(format!("spawn bambu: {e}")))?;
    if !status.success() {
        return Err(HlsError::Message("bambu exited non-zero".into()));
    }
    Ok(c)
}

fn which(name: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path) {
        let cand = dir.join(name);
        if cand.is_file() {
            return Some(cand);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn disabled_is_unsupported() {
        if hls_enabled() {
            // Environment already enabled in this process; skip mutation race.
            return;
        }
        let err = run_hls("add", &std::env::temp_dir().join("rhdl_hls_off")).unwrap_err();
        assert!(err.to_string().contains("unsupported"));
    }

    #[test]
    fn emit_stub_without_scheduling() {
        let dir = std::env::temp_dir().join("rhdl_hls_stub");
        let p = emit_c_stub("add", &dir).unwrap();
        let text = std::fs::read_to_string(p).unwrap();
        assert!(text.contains("no scheduling in bitloom"));
        assert!(!text.contains("schedule"));
    }
}