Skip to main content

llama_cpp_bindings_build/
lib.rs

1#![cfg_attr(
2    not(test),
3    deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)
4)]
5mod android_ndk;
6mod apple_variant;
7mod bindgen_config;
8mod cmake_config;
9mod cpp_wrapper;
10mod library_linking;
11mod native_library;
12mod rebuild_tracking;
13mod target_os;
14
15use std::env;
16use std::path::{Path, PathBuf};
17
18use android_ndk::AndroidNdk;
19use target_os::TargetOs;
20
21#[derive(Debug, thiserror::Error)]
22pub enum BuildError {
23    #[error("environment variable {name} could not be read: {source}")]
24    Environment {
25        name: &'static str,
26        #[source]
27        source: env::VarError,
28    },
29    #[error("unsupported target operating system: {cargo_cfg_target_os}")]
30    UnsupportedTargetOs { cargo_cfg_target_os: String },
31    #[error(transparent)]
32    AndroidNdk(#[from] android_ndk::AndroidNdkDetectionError),
33    #[error("bindgen failed: {0}")]
34    Bindgen(#[source] bindgen::BindgenError),
35    #[error(
36        "bindgen never saw field {type_name}::{field_name}, so it can no longer be kept private"
37    )]
38    PrivatizedFieldMissing {
39        type_name: &'static str,
40        field_name: &'static str,
41    },
42    #[error("generated bindings could not be written: {0}")]
43    BindingsWrite(#[source] std::io::Error),
44    #[error("native wrapper compilation failed: {0}")]
45    NativeWrapper(#[source] cc::Error),
46    #[error("filesystem operation failed for {path}: {source}")]
47    Filesystem {
48        path: PathBuf,
49        #[source]
50        source: std::io::Error,
51    },
52    #[error("environment path {name} does not name a directory: {path}")]
53    EnvironmentDirectory { name: &'static str, path: PathBuf },
54}
55
56fn required_env(name: &'static str) -> Result<String, BuildError> {
57    env::var(name).map_err(|source| BuildError::Environment { name, source })
58}
59
60fn optional_env(name: &'static str) -> Result<Option<String>, BuildError> {
61    match env::var(name) {
62        Ok(value) => Ok(Some(value)),
63        Err(env::VarError::NotPresent) => Ok(None),
64        Err(source) => Err(BuildError::Environment { name, source }),
65    }
66}
67
68#[macro_export]
69macro_rules! debug_log {
70    ($($arg:tt)*) => {
71        if std::env::var("BUILD_DEBUG").is_ok() {
72            println!("cargo:warning=[DEBUG] {}", format!($($arg)*));
73        }
74    };
75}
76
77#[derive(Debug)]
78pub struct BuildContext {
79    pub out_dir: PathBuf,
80    pub cmake_dir: PathBuf,
81    pub llama_src: PathBuf,
82    pub target_os: TargetOs,
83    pub target_triple: String,
84    pub cargo_cfg_target_arch: String,
85    pub cargo_cfg_target_env: String,
86    pub build_shared_libs: bool,
87    pub profile: String,
88    pub android_ndk: Option<AndroidNdk>,
89}
90
91impl BuildContext {
92    fn detect() -> Result<Self, BuildError> {
93        let target_triple = required_env("TARGET")?;
94        let cargo_cfg_target_os = required_env("CARGO_CFG_TARGET_OS")?;
95        let cargo_cfg_target_env = optional_env("CARGO_CFG_TARGET_ENV")?.unwrap_or_default();
96        let target_os = TargetOs::from_cargo_cfg(&cargo_cfg_target_os).ok_or_else(|| {
97            BuildError::UnsupportedTargetOs {
98                cargo_cfg_target_os: cargo_cfg_target_os.clone(),
99            }
100        })?;
101        let out_dir = PathBuf::from(required_env("OUT_DIR")?);
102        let manifest_dir = required_env("CARGO_MANIFEST_DIR")?;
103        let llama_src = Path::new(&manifest_dir).join("llama.cpp");
104
105        let build_shared_libs = cfg!(feature = "dynamic-link");
106        let profile = native_profile(&required_env("PROFILE")?);
107
108        let cargo_cfg_target_arch = required_env("CARGO_CFG_TARGET_ARCH")?;
109        let android_ndk = if target_os.is_android() {
110            Some(AndroidNdk::detect(&target_triple, &cargo_cfg_target_arch)?)
111        } else {
112            None
113        };
114
115        let cmake_dir = out_dir.join("cmake");
116
117        debug_log!("TARGET: {}", target_triple);
118        debug_log!("CARGO_MANIFEST_DIR: {}", manifest_dir);
119        debug_log!("OUT_DIR: {}", out_dir.display());
120        debug_log!("CMAKE_DIR: {}", cmake_dir.display());
121        debug_log!("BUILD_SHARED: {}", build_shared_libs);
122
123        Ok(Self {
124            out_dir,
125            cmake_dir,
126            llama_src,
127            target_os,
128            target_triple,
129            cargo_cfg_target_arch,
130            cargo_cfg_target_env,
131            build_shared_libs,
132            profile,
133            android_ndk,
134        })
135    }
136}
137
138fn native_profile(cargo_profile: &str) -> String {
139    match cargo_profile {
140        "debug" | "release" => "Release".to_owned(),
141        other => other.to_owned(),
142    }
143}
144
145/// # Errors
146///
147/// Returns [`BuildError`] when the build environment cannot be read, the target is
148/// unsupported, or any of the native build steps fail.
149pub fn build() -> Result<(), BuildError> {
150    let context = BuildContext::detect()?;
151
152    rebuild_tracking::register_rebuild_triggers(&context.llama_src);
153
154    bindgen_config::generate_bindings(
155        &context.llama_src,
156        &context.out_dir,
157        context.target_os,
158        &context.target_triple,
159        context.android_ndk.as_ref(),
160    )?;
161
162    cpp_wrapper::compile_cpp_wrappers(context.target_os)?;
163
164    let build_dir = cmake_config::configure_and_build(&context)?;
165
166    library_linking::link_libraries(
167        &context.cmake_dir,
168        &build_dir,
169        context.target_os,
170        &context.cargo_cfg_target_env,
171        context.build_shared_libs,
172        &context.profile,
173    )?;
174
175    Ok(())
176}
177
178#[cfg(test)]
179mod build_context_value_tests {
180    use super::native_profile;
181
182    #[test]
183    fn cargo_debug_and_release_profiles_both_use_optimized_native_code() {
184        assert_eq!(native_profile("debug"), "Release");
185        assert_eq!(native_profile("release"), "Release");
186    }
187
188    #[test]
189    fn custom_cargo_profile_name_is_preserved_for_cmake() {
190        assert_eq!(native_profile("RelWithDebInfo"), "RelWithDebInfo");
191    }
192}