feat: generate Rust bindings during build process

It can be used as:
  > cargo build -p tree-sitter -F bindgen
This commit is contained in:
Andrew Hlynskyi 2023-08-20 16:00:33 +03:00
parent 62823fc333
commit 4278e03b11
5 changed files with 137 additions and 2 deletions

View file

@ -17,6 +17,9 @@ fn main() {
}
}
#[cfg(feature = "bindgen")]
generate_bindings();
let src_path = Path::new("src");
for entry in fs::read_dir(&src_path).unwrap() {
let entry = entry.unwrap();
@ -34,6 +37,44 @@ fn main() {
.compile("tree-sitter");
}
#[cfg(feature = "bindgen")]
fn generate_bindings() {
const HEADER_PATH: &str = "include/tree_sitter/api.h";
println!("cargo:rerun-if-changed={}", HEADER_PATH);
let no_copy = [
"TSInput",
"TSLanguage",
"TSLogger",
"TSLookaheadIterator",
"TSParser",
"TSTree",
"TSQuery",
"TSQueryCursor",
"TSQueryCapture",
"TSQueryMatch",
"TSQueryPredicateStep",
];
let bindings = bindgen::Builder::default()
.header(HEADER_PATH)
.layout_tests(false)
.allowlist_type("^TS.*")
.allowlist_function("^ts_.*")
.allowlist_var("^TREE_SITTER.*")
.no_copy(no_copy.join("|"))
.generate()
.expect("Failed to generate bindings");
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let bindings_rs = out_dir.join("bindings.rs");
bindings.write_to_file(&bindings_rs).expect(&*format!(
"Failed to write bindings into path: {bindings_rs:?}"
));
}
fn which(exe_name: impl AsRef<Path>) -> Option<PathBuf> {
env::var_os("PATH").and_then(|paths| {
env::split_paths(&paths).find_map(|dir| {

View file

@ -2,6 +2,10 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#[cfg(feature = "bindgen")]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
#[cfg(not(feature = "bindgen"))]
include!("./bindings.rs");
extern "C" {

View file

@ -27,12 +27,13 @@ use std::{
/// The Tree-sitter library is generally backwards-compatible with languages
/// generated using older CLI versions, but is not forwards-compatible.
#[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION;
pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;
/// The earliest ABI version that is supported by the current version of the
/// library.
#[doc(alias = "TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION")]
pub const MIN_COMPATIBLE_LANGUAGE_VERSION: usize = ffi::TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION;
pub const MIN_COMPATIBLE_LANGUAGE_VERSION: usize =
ffi::TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION as usize;
pub const PARSER_HEADER: &'static str = include_str!("../include/tree_sitter/parser.h");