use std::path::Path;
use std::path::PathBuf;
use bindgen::Builder;
use llama_cpp_wrapper_sources::constants::FAULT_INJECTION_DEFINE;
use crate::binding_callbacks::BindingCallbacks;
use crate::build_context::BuildContext;
use crate::build_environment::BuildEnvironment;
use crate::build_error::BuildError;
use crate::build_feature::BuildFeature;
use crate::cargo_directive::CargoDirective;
use crate::target_os::TargetOs;
const DEPRECATED_FUNCTIONS: &[&str] = &[
"mtmd_encode",
"mtmd_helper_model_can_chat",
"mtmd_helper_support_video",
"mtmd_image_tokens_get_nx",
"mtmd_image_tokens_get_ny",
];
const SUPERSEDED_ITEMS: &[&str] = &[
"LLAMA_TOKEN_TYPE_BYTE",
"LLAMA_TOKEN_TYPE_CONTROL",
"LLAMA_TOKEN_TYPE_NORMAL",
"LLAMA_TOKEN_TYPE_UNDEFINED",
"LLAMA_TOKEN_TYPE_UNKNOWN",
"LLAMA_TOKEN_TYPE_UNUSED",
"LLAMA_TOKEN_TYPE_USER_DEFINED",
"ggml_backend_offload_op",
"ggml_backend_supports_buft",
"ggml_backend_supports_op",
"llama_batch",
"llama_batch_free",
"llama_batch_get_one",
"llama_batch_init",
"llama_decode",
"llama_encode",
"llama_get_embeddings",
"llama_get_logits",
"llama_perf_context",
"llama_perf_context_data",
"llama_perf_context_print",
"llama_perf_context_reset",
"llama_perf_sampler",
"llama_perf_sampler_data",
"llama_perf_sampler_print",
"llama_perf_sampler_reset",
"llama_token_type",
"mtmd_image_tokens_get_id",
"mtmd_image_tokens_get_n_pos",
"mtmd_image_tokens_get_n_tokens",
];
fn configured_builder() -> Builder {
let builder = Builder::default()
.generate_comments(false)
.allowlist_function("ggml_.*")
.allowlist_type("ggml_.*")
.allowlist_var("GGML_MAX_DIMS")
.allowlist_function("gguf_.*")
.allowlist_type("gguf_.*")
.allowlist_function("llama_.*")
.allowlist_type("llama_.*")
.allowlist_var("LLAMA_TOKEN_NULL")
.allowlist_var("LLAMA_DRY_MAX_SEQ_BREAKERS")
.allowlist_var("LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY")
.allowlist_function("mtmd_.*")
.allowlist_type("mtmd_.*")
.blocklist_function("ggml_fopen")
.blocklist_function("llama_adapter_lora_init_from_file_ptr")
.blocklist_function("gguf_init_from_file_ptr")
.blocklist_function("gguf_write_to_file_ptr")
.blocklist_function("llama_model_load_from_file_ptr")
.blocklist_type("FILE")
.blocklist_type("_IO_.*")
.rustified_enum("llama_rs_.*_status")
.rustified_enum("llama_rs_chat_span_kind")
.rustified_enum("llama_rs_chat_grammar_trigger_type")
.rustified_enum("llama_rs_memory_kind")
.prepend_enum_name(false);
let builder = DEPRECATED_FUNCTIONS
.iter()
.fold(builder, Builder::blocklist_function);
SUPERSEDED_ITEMS
.iter()
.fold(builder, Builder::blocklist_item)
}
fn fault_injection_args(environment: &BuildEnvironment) -> Vec<String> {
if environment.has(BuildFeature::FaultInjection) {
vec![format!("-D{FAULT_INJECTION_DEFINE}")]
} else {
Vec::new()
}
}
fn target_args(
BuildContext {
target_os,
target_triple,
..
}: &BuildContext,
) -> Vec<String> {
match target_os {
TargetOs::Android(android_ndk) => android_ndk.clang_args(target_triple),
TargetOs::Apple | TargetOs::Linux => Vec::new(),
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BindingsGeneration {
pub header: PathBuf,
pub clang_args: Vec<String>,
pub output: PathBuf,
}
impl BindingsGeneration {
#[must_use]
pub fn of(
context: &BuildContext,
environment: &BuildEnvironment,
llama_cpp_dir: &Path,
) -> Self {
Self {
header: context.manifest_dir.join("wrapper.h"),
clang_args: [
vec![
format!("-I{}", llama_cpp_dir.display()),
format!("-I{}", llama_cpp_dir.join("include").display()),
format!("-I{}", llama_cpp_dir.join("ggml/include").display()),
],
fault_injection_args(environment),
target_args(context),
]
.concat(),
output: context.out_dir.join("bindings.rs"),
}
}
pub fn generate(&self) -> Result<Vec<CargoDirective>, BuildError> {
let callbacks = BindingCallbacks::default();
let bindings = configured_builder()
.header(self.header.display().to_string())
.clang_args(&self.clang_args)
.parse_callbacks(Box::new(callbacks.clone()))
.generate()
.map_err(BuildError::Bindgen)?;
callbacks.verify_every_privatized_field_was_found()?;
bindings
.write_to_file(&self.output)
.map_err(BuildError::BindingsWrite)?;
Ok([
callbacks.take_rebuild_triggers(),
vec![CargoDirective::Debug("Bindings Created".to_owned())],
]
.concat())
}
}
#[cfg(test)]
mod tests {
use std::env;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::process;
use llama_cpp_wrapper_sources::constants::FAULT_INJECTION_DEFINE;
use llama_cpp_error_chain::error_chain::error_chain;
use super::BindingsGeneration;
use crate::android_ndk::tests::FIXTURE_ANDROID_NDK;
use crate::build_context::BuildContext;
use crate::build_context::tests::android_overrides;
use crate::build_context::tests::cargo_environment;
use crate::build_environment::tests::EnvironmentVariable;
use crate::build_feature::BuildFeature;
const FIXTURE_BINDINGS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/fixtures/bindings");
fn planned(features: &[BuildFeature], overrides: &[EnvironmentVariable]) -> BindingsGeneration {
let environment = cargo_environment(features, overrides);
BindingsGeneration::of(
&BuildContext::of_linux_host(&environment),
&environment,
Path::new("/native/llama.cpp"),
)
}
fn llama_cpp_includes() -> Vec<String> {
vec![
"-I/native/llama.cpp".to_owned(),
"-I/native/llama.cpp/include".to_owned(),
"-I/native/llama.cpp/ggml/include".to_owned(),
]
}
fn generation_failure(header: &str, output: PathBuf) -> Option<String> {
BindingsGeneration {
header: PathBuf::from(FIXTURE_BINDINGS).join(header),
clang_args: Vec::new(),
output,
}
.generate()
.err()
.map(|error| error_chain(&error))
}
#[test]
fn the_wrapper_header_is_parsed_against_the_llama_cpp_headers() {
assert_eq!(
planned(&[], &[]),
BindingsGeneration {
header: PathBuf::from("/sys/wrapper.h"),
clang_args: llama_cpp_includes(),
output: PathBuf::from("/out/bindings.rs"),
}
);
}
#[test]
fn fault_injection_adds_its_define_to_the_clang_arguments() {
assert_eq!(
planned(&[BuildFeature::FaultInjection], &[]).clang_args,
[
llama_cpp_includes(),
vec![format!("-D{FAULT_INJECTION_DEFINE}")],
]
.concat()
);
}
#[test]
fn android_targets_add_the_ndk_clang_arguments() {
let toolchain = format!("{FIXTURE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64");
assert_eq!(
planned(&[], &android_overrides()).clang_args,
[
llama_cpp_includes(),
vec![
format!("--sysroot={toolchain}/sysroot"),
"-D__ANDROID_API__=28".to_owned(),
"-D__ANDROID__".to_owned(),
"-isystem".to_owned(),
format!("{toolchain}/lib/clang/20/include"),
"-isystem".to_owned(),
format!("{toolchain}/sysroot/usr/include/aarch64-linux-android"),
"-isystem".to_owned(),
format!("{toolchain}/sysroot/usr/include"),
"-include".to_owned(),
"stdbool.h".to_owned(),
"-include".to_owned(),
"stdint.h".to_owned(),
"--target=aarch64-linux-android".to_owned(),
],
]
.concat()
);
}
#[test]
fn a_missing_header_is_reported_by_bindgen() {
assert_eq!(
generation_failure("missing.h", PathBuf::from("/out/bindings.rs")),
Some(format!(
"bindgen failed: header '{FIXTURE_BINDINGS}/missing.h' does not exist."
))
);
}
#[test]
fn a_header_without_a_privatized_field_is_refused() {
assert_eq!(
generation_failure(
"missing_privatized_field.h",
PathBuf::from("/out/bindings.rs")
),
Some(
"bindgen never saw field mtmd_context_params::image_marker, so it can no longer \
be kept private"
.to_owned()
)
);
}
#[test]
fn generated_bindings_hide_superseded_enum_variants_and_keep_their_replacements() {
let output = env::temp_dir().join(format!(
"llama-cpp-bindings-build-bindings-{}.rs",
process::id()
));
BindingsGeneration {
header: PathBuf::from(FIXTURE_BINDINGS).join("wrapper.h"),
clang_args: Vec::new(),
output: output.clone(),
}
.generate()
.unwrap();
let bindings = fs::read_to_string(&output).unwrap();
fs::remove_file(&output).unwrap();
let declares = |constant: &str| {
bindings
.lines()
.any(|line| line.trim() == format!("pub const {constant}: ggml_prec = 0;"))
};
assert_eq!(
[
declares("GGML_PREC_DEFAULT"),
declares("GGML_PREC_UNDEFINED")
],
[false, true]
);
}
#[test]
fn bindings_that_cannot_be_written_are_reported() {
assert_eq!(
generation_failure(
"wrapper.h",
PathBuf::from(FIXTURE_BINDINGS).join("missing-directory/bindings.rs")
),
Some(
"generated bindings could not be written: No such file or directory (os error 2)"
.to_owned()
)
);
}
}