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