1use bindgen::{2 RustEdition,3 callbacks::{ItemInfo, ParseCallbacks},4};5use std::path::PathBuf;67#[derive(Debug)]8struct StripPrefix;9impl ParseCallbacks for StripPrefix {10 fn item_name(&self, name: ItemInfo<'_>) -> Option<String> {11 name.name.strip_prefix("nix_").map(ToOwned::to_owned)12 }13}1415fn main() {16 17 for lib in &[18 "nix-util",19 "nix-util-c",20 "nix-store",21 "nix-store-c",22 "nix-expr",23 "nix-flake",24 "nix-fetchers",25 "bdw-gc",26 ] {27 if let Ok(library) = pkg_config::probe_library(lib) {28 for lib_path in library.libs {29 println!("cargo:rustc-link-lib={lib_path}");30 }31 for search_path in library.link_paths {32 println!("cargo:rustc-link-search=native={}", search_path.display());33 }34 }35 }3637 cxx_build::bridge("src/logging.rs")38 .file("src/logging.cc")39 .std("c++23")40 .shared_flag(true)41 .compile("nix-eval-logging");42 cxx_build::bridge("src/lib.rs")43 .file("src/lib.cc")44 .std("c++23")45 .shared_flag(true)46 .compile("nix-eval");4748 println!("cargo:rerun-if-changed=src/lib.cc");49 println!("cargo:rerun-if-changed=src/lib.hh");50 println!("cargo:rerun-if-changed=src/logging.cc");51 println!("cargo:rerun-if-changed=src/logging.hh");5253 54 let mut libnix = bindgen::builder()55 .rust_edition(RustEdition::Edition2024)56 .header_contents(57 "nix.h",58 "59 #define GC_THREADS60 #include <gc/gc.h>61 #include <nix_api_expr.h>62 #include <nix_api_store.h>63 #include <nix_api_flake.h>64 #include <nix_api_fetchers.h>65 #include <nix_api_util.h>66 #include <nix_api_value.h>67 ",68 )69 .parse_callbacks(Box::new(StripPrefix));7071 for header in pkg_config::probe_library("nix-expr-c")72 .expect("nix-expr-c")73 .include_paths74 .into_iter()75 .chain(76 pkg_config::probe_library("nix-store-c")77 .expect("nix-store-c")78 .include_paths79 .into_iter(),80 )81 .chain(82 pkg_config::probe_library("nix-flake-c")83 .expect("nix-flake-c")84 .include_paths85 .into_iter(),86 )87 .chain(88 pkg_config::probe_library("nix-fetchers-c")89 .expect("nix-fetchers-c")90 .include_paths91 .into_iter(),92 )93 .chain(94 pkg_config::probe_library("bdw-gc")95 .expect("bdw-gc")96 .include_paths97 .into_iter(),98 ) {99 libnix = libnix.clang_arg(format!("-I{}", header.to_str().expect("path is utf-8")));100 }101102 let mut out = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo"));103 out.push("bindings.rs");104 libnix105 .generate()106 .expect("generate bindings")107 .write_to_file(out)108 .expect("write bindings");109}