cabal_foreign_library/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
//! A library for Cargo [build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html)
//! to build and link a Cabal [foreign library](https://cabal.readthedocs.io/en/3.4/cabal-package.html#foreign-libraries)
//! to Rust crates. The crate calls out to Cabal and GHC; all necesssary Haskell dependencies must
//! be installed and managed separately.
//!
//! Everything is a work-in-progress!
//!
//! # Example
//!
//! For a basic usage example, see [`examples/basic`](https://github.com/mirryi/cabal-foreign-library/tree/master/examples/basic).
mod error;
mod util;
use std::process::Command;
use std::{fs, str};
use camino::{Utf8Path, Utf8PathBuf};
use regex::Regex;
use util::{out_dir, package, CommandStdoutExt, DYLIB_EXT};
pub use error::*;
/// A builder for a Cabal library.
#[derive(Debug)]
pub struct Build {
cabal: Utf8PathBuf,
ghc_pkg: Utf8PathBuf,
rts_version: RTSVersion,
}
/// A handler for a library built by Cabal.
#[derive(Debug)]
pub struct Lib<'b> {
build: &'b Build,
path: Utf8PathBuf,
hs_deps: Vec<HSDep>,
}
#[derive(Debug, Clone, Copy)]
enum HSDep {
Ghc,
Base,
}
/// Generated Rust bindings for the Haskell library.
pub type Bindings = bindgen::Bindings;
/// Alias for Result.
pub type Result<T> = std::result::Result<T, Error>;
/// The version of the Haskell runtime library.
#[derive(Debug, Clone, Copy)]
pub enum RTSVersion {
NonThreaded,
NonThreadedL,
NonThreadedDebug,
Threaded,
ThreadedL,
ThreadedDebug,
}
impl RTSVersion {
fn default() -> Self {
Self::NonThreaded
}
}
impl Build {
/// Construct a new instance with a default configuration.
pub fn new() -> Result<Self> {
let cabal = util::which("cabal").map_err(Error::CabalError)?;
let ghc_pkg = util::which("ghc-pkg").map_err(Error::GHCPkgError)?;
Ok(Self {
cabal,
ghc_pkg,
rts_version: RTSVersion::default(),
})
}
/// Set the `cabal` binary.
///
/// By default, `PATH` is searched for the `cabal` binary.
pub fn use_cabal(&mut self, path: impl AsRef<Utf8Path>) -> &mut Self {
self.cabal = path.as_ref().to_path_buf();
self
}
/// Set the `ghc-pkg` binary.
///
/// By default, `PATH` is searched for the `ghc-pkg` binary.
pub fn use_ghc_pkg(&mut self, path: impl AsRef<Utf8Path>) -> &mut Self {
self.ghc_pkg = path.as_ref().to_path_buf();
self
}
/// Set the version of the GHC RTS.
///
/// By default, [`RTSVersion::NonThreaded`] is used.
pub fn use_rts(&mut self, rts_version: RTSVersion) -> &mut Self {
self.rts_version = rts_version;
self
}
/// Build the foreign library with cabal. The resulting [`Lib`] handler can be used to link and
/// generate bindings.
pub fn build(&mut self) -> Result<Lib> {
// build
let status = self
.cabal_cmd("build")
.status()
.map_err(|err| Error::BuildError(Some(err)))?;
if !status.success() {
return Err(Error::BuildError(None));
}
// find the dylib file
let path = self
.cabal_cmd("list-bin")
.arg(util::package())
.stdout_trim()
.map(Utf8PathBuf::from)
.map_err(|err| Error::BuildError(Some(err)))?;
Ok(Lib {
build: self,
path,
// TODO somehow pull necessary dependencies from cabal? or just link all system
// dependencies?
hs_deps: vec![HSDep::Ghc, HSDep::Base],
})
}
fn cabal_cmd(&self, cmd: &str) -> Command {
let mut cabal = Command::new(&self.cabal);
cabal.args([cmd, "--builddir", &out_dir()]);
cabal
}
fn ghc_pkg_cmd(&self, cmd: &str) -> Command {
let mut ghc_pkg = Command::new(&self.ghc_pkg);
ghc_pkg.args([cmd]);
ghc_pkg
}
}
impl<'b> Lib<'b> {
/// Link the crate to the dynamic library.
///
/// If `rpath` is true, the runpath of the resulting executable is modified to include the
/// directory of the compiled foreign library.
pub fn link(&self, rpath: bool) -> Result<()> {
let dir = self.path.parent().unwrap();
println!("cargo::rustc-link-search=native={}", dir);
println!("cargo::rustc-link-lib=dylib={}", &package());
if rpath {
println!("cargo::rustc-link-arg=-Wl,-rpath,{}", dir);
}
Ok(())
}
/// Generate Rust bindings for the dynamic library.
///
/// See [`bindgen::Bindings`].
pub fn bindings(&self) -> Result<Bindings> {
// find GHC RTS headers to be included
let rts_headers = self
.build
.ghc_pkg_cmd("field")
.args(["rts", "include-dirs", "--simple-output"])
.stdout_trim()
.map(Utf8PathBuf::from)
.map_err(BindingsError::IoError)?;
// find the stub file
let stub = self
.path
.parent()
.unwrap()
.join(format!("{}-tmp", package()))
.join("Lib_stub.h");
// invoke bindgen
let bindings = bindgen::Builder::default()
.clang_args(["-isystem", rts_headers.as_str()])
.header(stub)
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.generate()
.map_err(BindingsError::BindgenError)?;
Ok(bindings)
}
/// Link the crate to the Haskell system libraries, which are discovered via `ghc-pkg`.
///
/// If `rpath` is true, the runpath of the resulting executable is modified to include the
/// directory of the system libraries.
pub fn link_system(&self, rpath: bool) -> Result<()> {
// retrieve dynamic libraries directory.
let ghc_lib_dir = self
.build
.ghc_pkg_cmd("field")
.args(["rts", "dynamic-library-dirs", "--simple-output"])
.stdout_trim()
.map_err(InvocationError::IoError)
.map_err(Error::GHCPkgError)?;
let ghc_lib_dir = fs::canonicalize(ghc_lib_dir).unwrap();
// regexes to match the necessary system dependencies.
let version_regex = Regex::new(r"((\d+)\.)+?(\d+)").unwrap();
let non_rts_prefixes = self
.hs_deps
.iter()
.map(HSDep::prefix)
.collect::<Vec<_>>()
.join("|");
let non_rts_regex = Regex::new(&format!(
r"^lib({prefix})-({version})-ghc({version})\.{ext}$",
prefix = non_rts_prefixes,
version = version_regex,
ext = DYLIB_EXT
))
.unwrap();
let rts_suffix = self.build.rts_version.suffix();
let rts_regex = Regex::new(&format!(
r"^libHSrts-({version})({suffix})-ghc({version})\.{ext}$",
version = version_regex,
suffix = rts_suffix,
ext = DYLIB_EXT
))
.unwrap();
// link matching library files
println!("cargo:rustc-link-search=native={}", ghc_lib_dir.display());
for entry in fs::read_dir(&ghc_lib_dir).unwrap() {
let entry = entry.unwrap();
if let Some(i) = entry.file_name().to_str() {
if non_rts_regex.is_match(i) || rts_regex.is_match(i) {
// get rid of lib from the file name
let temp = i.split_at(3).1;
// get rid of the .so from the file name
let trimmed = temp.split_at(temp.len() - DYLIB_EXT.len() - 1).0;
println!("cargo:rustc-link-lib=dylib={}", trimmed);
}
}
}
if rpath {
println!("cargo::rustc-link-arg=-Wl,-rpath,{}", ghc_lib_dir.display());
}
// TODO error if failed to find some libraries
Ok(())
}
}
impl RTSVersion {
fn suffix(&self) -> &str {
match self {
RTSVersion::NonThreaded => "",
RTSVersion::NonThreadedL => "_l",
RTSVersion::NonThreadedDebug => "_debug",
RTSVersion::Threaded => "_thr",
RTSVersion::ThreadedL => "_thr_l",
RTSVersion::ThreadedDebug => "_thr_debug",
}
}
}
impl HSDep {
fn prefix(&self) -> &str {
match self {
HSDep::Ghc => "HSghc",
HSDep::Base => "HSbase",
}
}
}