use std::env;
use std::path::PathBuf;
fn main() {
if !cfg!(target_os = "macos") {
panic!("mlxcore-sys currently only supports macOS on Apple Silicon");
}
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mlx_c_dir = manifest_dir
.join("third_party/mlx-c")
.canonicalize()
.expect(
"third_party/mlx-c submodule not found — run `git submodule update --init --recursive`",
);
let mut cfg = cmake::Config::new(&mlx_c_dir);
cfg.define("BUILD_SHARED_LIBS", "OFF")
.define("MLX_C_BUILD_EXAMPLES", "OFF")
.define("CMAKE_BUILD_TYPE", "Release");
if cfg!(feature = "metal") {
cfg.define("MLX_BUILD_METAL", "ON");
} else {
cfg.define("MLX_BUILD_METAL", "OFF");
}
if cfg!(feature = "accelerate") {
cfg.define("MLX_BUILD_ACCELERATE", "ON");
}
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let profile_dir = out_dir
.ancestors()
.nth(3)
.expect("unexpected OUT_DIR layout");
cfg.out_dir(profile_dir.join("mlx-c-build"));
let dst = cfg.build();
println!("cargo:rustc-link-search=native={}/lib", dst.display());
println!("cargo:rustc-link-lib=static=mlxc");
println!("cargo:rustc-link-lib=static=mlx");
println!("cargo:rustc-link-lib=dylib=c++");
for framework in ["Foundation", "Metal", "QuartzCore", "Accelerate"] {
println!("cargo:rustc-link-lib=framework={framework}");
}
let header = mlx_c_dir.join("mlx/c/mlx.h");
println!("cargo:rerun-if-changed={}", header.display());
let bindings = bindgen::Builder::default()
.header(header.to_string_lossy())
.clang_arg(format!("-I{}", mlx_c_dir.display()))
.allowlist_function("mlx_.*")
.allowlist_type("mlx_.*")
.allowlist_var("MLX_.*")
.prepend_enum_name(false)
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.generate()
.expect("failed to generate mlx-c bindings");
bindings
.write_to_file(out_dir.join("bindings.rs"))
.expect("failed to write bindings.rs");
}