Skip to content

Move CLI options to bindgen #2983

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ default-members = [

# Dependencies shared between crates
[workspace.dependencies]
clap = { version = "4", features = ["derive"] }
clap_complete = "4"
shlex = "1"
syn = "2.0"
proc-macro2 = { version = "1", default-features = false }
Expand Down
2 changes: 0 additions & 2 deletions bindgen-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ bindgen = { path = "../bindgen", version = "=0.70.1", default-features = false,
env_logger = { version = "0.10.0", optional = true }
log = { version = "0.4", optional = true }

clap.workspace = true
clap_complete.workspace = true
proc-macro2.workspace = true
shlex.workspace = true

Expand Down
3 changes: 1 addition & 2 deletions bindgen-cli/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::env;

mod options;
use crate::options::builder_from_flags;
use bindgen::builder_from_flags;

#[cfg(feature = "logging")]
fn clang_version_check() {
Expand Down
2 changes: 0 additions & 2 deletions bindgen-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ prettyplease = { version = "0.2.7", features = ["verbatim"] }
similar = { version = "2.2.1", features = ["inline"] }
tempfile = "3"

clap.workspace = true
clap_complete.workspace = true
proc-macro2.workspace = true
shlex.workspace = true
syn.workspace = true
Expand Down
8 changes: 2 additions & 6 deletions bindgen-tests/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ use std::fs;
use std::io::{BufRead, BufReader, Error, ErrorKind, Read, Write};
use std::path::{Path, PathBuf};

use crate::options::builder_from_flags;

#[path = "../../bindgen-cli/options.rs"]
mod options;
use bindgen::builder_from_flags;

mod parse_callbacks;

Expand Down Expand Up @@ -709,8 +706,7 @@ fn build_flags_output_helper(builder: &bindgen::Builder) {
println!("{}", flags_str);

let (builder, _output, _verbose) =
crate::options::builder_from_flags(command_line_flags.into_iter())
.unwrap();
builder_from_flags(command_line_flags.into_iter()).unwrap();
builder.generate().expect("failed to generate bindings");
}

Expand Down
4 changes: 3 additions & 1 deletion bindgen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ annotate-snippets = { version = "0.11.4", optional = true }
bitflags = "2.2.1"
cexpr = "0.6"
clang-sys = { version = "1", features = ["clang_11_0"] }
clap = { version = "4", features = ["derive"], optional = true }
clap_complete = { version = "4", optional = true}
itertools = { version = ">=0.10,<0.14", default-features = false }
log = { version = "0.4", optional = true }
prettyplease = { version = "0.2.7", optional = true, features = ["verbatim"] }
Expand All @@ -52,7 +54,7 @@ experimental = ["dep:annotate-snippets"]
## The following features are for internal use and they shouldn't be used if
## you're not hacking on bindgen
# Features used by `bindgen-cli`
__cli = []
__cli = ["dep:clap", "dep:clap_complete"]
# Features used for CI testing
__testing_only_extra_assertions = []
__testing_only_libclang_9 = []
Expand Down
5 changes: 2 additions & 3 deletions bindgen/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,11 @@ mod regex_set;
pub use codegen::{
AliasVariation, EnumVariation, MacroTypeVariation, NonCopyUnionStyle,
};
#[cfg(feature = "__cli")]
pub use features::RUST_TARGET_STRINGS;
pub use features::{RustTarget, LATEST_STABLE_RUST};
pub use ir::annotations::FieldVisibilityKind;
pub use ir::function::Abi;
pub use regex_set::RegexSet;
#[cfg(feature = "__cli")]
pub use options::cli::builder_from_flags;

use codegen::CodegenError;
use features::RustFeatures;
Expand Down
2 changes: 1 addition & 1 deletion bindgen/options/as_args.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::PathBuf;

use crate::RegexSet;
use crate::regex_set::RegexSet;

/// Trait used to turn [`crate::BindgenOptions`] fields into CLI args.
pub(super) trait AsArgs {
Expand Down
70 changes: 43 additions & 27 deletions bindgen-cli/options.rs → bindgen/options/cli.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
use bindgen::callbacks::TypeKind;
use bindgen::{
builder, Abi, AliasVariation, Builder, CodegenConfig, EnumVariation,
use crate::{
builder,
callbacks::{
AttributeInfo, DeriveInfo, ItemInfo, ParseCallbacks, TypeKind,
},
features::RUST_TARGET_STRINGS,
regex_set::RegexSet,
Abi, AliasVariation, Builder, CodegenConfig, EnumVariation,
FieldVisibilityKind, Formatter, MacroTypeVariation, NonCopyUnionStyle,
RegexSet, RustTarget, DEFAULT_ANON_FIELDS_PREFIX, RUST_TARGET_STRINGS,
RustTarget, DEFAULT_ANON_FIELDS_PREFIX,
};
use clap::{
error::{Error, ErrorKind},
CommandFactory, Parser,
};
use clap::error::{Error, ErrorKind};
use clap::{CommandFactory, Parser};
use proc_macro2::TokenStream;
use std::fs::File;
use std::io;
Expand Down Expand Up @@ -491,6 +498,7 @@ struct BindgenCommand {
#[arg(long, value_name = "VISIBILITY")]
default_visibility: Option<FieldVisibilityKind>,
/// Whether to emit diagnostics or not.
#[cfg(feature = "experimental")]
#[arg(long, requires = "experimental")]
emit_diagnostics: bool,
/// Generates completions for the specified SHELL, sends them to `stdout` and exits.
Expand Down Expand Up @@ -633,6 +641,7 @@ where
wrap_static_fns_path,
wrap_static_fns_suffix,
default_visibility,
#[cfg(feature = "experimental")]
emit_diagnostics,
generate_shell_completions,
experimental: _,
Expand All @@ -657,7 +666,7 @@ where
option_env!("CARGO_PKG_VERSION").unwrap_or("unknown")
);
if verbose {
println!("Clang: {}", bindgen::clang_version().full);
println!("Clang: {}", crate::clang_version().full);
}
std::process::exit(0);
}
Expand Down Expand Up @@ -1046,10 +1055,10 @@ where
prefix: String,
}

impl bindgen::callbacks::ParseCallbacks for PrefixLinkNameCallback {
impl ParseCallbacks for PrefixLinkNameCallback {
fn generated_link_name_override(
&self,
item_info: bindgen::callbacks::ItemInfo<'_>,
item_info: ItemInfo<'_>,
) -> Option<String> {
let mut prefix = self.prefix.clone();
prefix.push_str(item_info.name);
Expand Down Expand Up @@ -1114,10 +1123,10 @@ where
struct CustomDeriveCallback {
derives: Vec<String>,
kind: Option<TypeKind>,
regex_set: bindgen::RegexSet,
regex_set: RegexSet,
}

impl bindgen::callbacks::ParseCallbacks for CustomDeriveCallback {
impl ParseCallbacks for CustomDeriveCallback {
fn cli_args(&self) -> Vec<String> {
let mut args = vec![];

Expand All @@ -1140,10 +1149,7 @@ where
args
}

fn add_derives(
&self,
info: &bindgen::callbacks::DeriveInfo<'_>,
) -> Vec<String> {
fn add_derives(&self, info: &DeriveInfo<'_>) -> Vec<String> {
if self.kind.map(|kind| kind == info.kind).unwrap_or(true) &&
self.regex_set.matches(info.name)
{
Expand All @@ -1153,7 +1159,7 @@ where
}
}

for (custom_derives, kind, name) in [
for (custom_derives, kind, _name) in [
(with_derive_custom, None, "--with-derive-custom"),
(
with_derive_custom_struct,
Expand All @@ -1171,11 +1177,17 @@ where
"--with-derive-custom-union",
),
] {
let name = emit_diagnostics.then_some(name);
#[cfg(feature = "experimental")]
let name = emit_diagnostics.then_some(_name);

for (derives, regex) in custom_derives {
let mut regex_set = RegexSet::new();
let mut regex_set = RegexSet::default();
regex_set.insert(regex);

#[cfg(feature = "experimental")]
regex_set.build_with_diagnostics(false, name);
#[cfg(not(feature = "experimental"))]
regex_set.build(false);

builder = builder.parse_callbacks(Box::new(CustomDeriveCallback {
derives,
Expand All @@ -1189,10 +1201,10 @@ where
struct CustomAttributeCallback {
attributes: Vec<String>,
kind: Option<TypeKind>,
regex_set: bindgen::RegexSet,
regex_set: RegexSet,
}

impl bindgen::callbacks::ParseCallbacks for CustomAttributeCallback {
impl ParseCallbacks for CustomAttributeCallback {
fn cli_args(&self) -> Vec<String> {
let mut args = vec![];

Expand All @@ -1215,10 +1227,7 @@ where
args
}

fn add_attributes(
&self,
info: &bindgen::callbacks::AttributeInfo<'_>,
) -> Vec<String> {
fn add_attributes(&self, info: &AttributeInfo<'_>) -> Vec<String> {
if self.kind.map(|kind| kind == info.kind).unwrap_or(true) &&
self.regex_set.matches(info.name)
{
Expand All @@ -1228,7 +1237,7 @@ where
}
}

for (custom_attributes, kind, name) in [
for (custom_attributes, kind, _name) in [
(with_attribute_custom, None, "--with-attribute-custom"),
(
with_attribute_custom_struct,
Expand All @@ -1246,11 +1255,17 @@ where
"--with-attribute-custom-union",
),
] {
let name = emit_diagnostics.then_some(name);
#[cfg(feature = "experimental")]
let name = emit_diagnostics.then_some(_name);

for (attributes, regex) in custom_attributes {
let mut regex_set = RegexSet::new();
let mut regex_set = RegexSet::default();
regex_set.insert(regex);

#[cfg(feature = "experimental")]
regex_set.build_with_diagnostics(false, name);
#[cfg(not(feature = "experimental"))]
regex_set.build(false);

builder =
builder.parse_callbacks(Box::new(CustomAttributeCallback {
Expand All @@ -1277,6 +1292,7 @@ where
builder = builder.default_visibility(visibility);
}

#[cfg(feature = "experimental")]
if emit_diagnostics {
builder = builder.emit_diagnostics();
}
Expand Down
2 changes: 2 additions & 0 deletions bindgen/options/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#[macro_use]
mod helpers;
mod as_args;
#[cfg(feature = "__cli")]
pub(crate) mod cli;

use crate::callbacks::ParseCallbacks;
use crate::codegen::{
Expand Down
22 changes: 9 additions & 13 deletions bindgen/regex_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::cell::Cell;

/// A dynamic set of regular expressions.
#[derive(Clone, Debug, Default)]
pub struct RegexSet {
pub(crate) struct RegexSet {
items: Vec<Box<str>>,
/// Whether any of the items in the set was ever matched. The length of this
/// vector is exactly the length of `items`.
Expand All @@ -17,18 +17,13 @@ pub struct RegexSet {
}

impl RegexSet {
/// Create a new RegexSet
pub fn new() -> RegexSet {
RegexSet::default()
}

/// Is this set empty?
pub fn is_empty(&self) -> bool {
pub(crate) fn is_empty(&self) -> bool {
self.items.is_empty()
}

/// Insert a new regex into this set.
pub fn insert<S>(&mut self, string: S)
pub(crate) fn insert<S>(&mut self, string: S)
where
S: AsRef<str>,
{
Expand All @@ -38,13 +33,13 @@ impl RegexSet {
}

/// Returns slice of String from its field 'items'
pub fn get_items(&self) -> &[Box<str>] {
pub(crate) fn get_items(&self) -> &[Box<str>] {
&self.items
}

/// Returns an iterator over regexes in the set which didn't match any
/// strings yet.
pub fn unmatched_items(&self) -> impl Iterator<Item = &str> {
pub(crate) fn unmatched_items(&self) -> impl Iterator<Item = &str> {
self.items.iter().enumerate().filter_map(move |(i, item)| {
if !self.record_matches || self.matched[i].get() {
return None;
Expand All @@ -59,7 +54,8 @@ impl RegexSet {
/// Must be called before calling `matches()`, or it will always return
/// false.
#[inline]
pub fn build(&mut self, record_matches: bool) {
#[allow(unused)]
pub(crate) fn build(&mut self, record_matches: bool) {
self.build_inner(record_matches, None)
}

Expand All @@ -70,7 +66,7 @@ impl RegexSet {
/// Must be called before calling `matches()`, or it will always return
/// false.
#[inline]
pub fn build_with_diagnostics(
pub(crate) fn build_with_diagnostics(
&mut self,
record_matches: bool,
name: Option<&'static str>,
Expand Down Expand Up @@ -114,7 +110,7 @@ impl RegexSet {
}

/// Does the given `string` match any of the regexes in this set?
pub fn matches<S>(&self, string: S) -> bool
pub(crate) fn matches<S>(&self, string: S) -> bool
where
S: AsRef<str>,
{
Expand Down
Loading