Skip to content

Commit de9eb58

Browse files
committed
[Very WIP] Rewrite the core of the binding generator.
TL;DR: The binding generator is a mess as of right now. At first it was funny (in a "this is challenging" sense) to improve on it, but this is not sustainable. The truth is that the current architecture of the binding generator is a huge pile of hacks, so these few days I've been working on rewriting it with a few goals. 1) Have the hacks as contained and identified as possible. They're sometimes needed because how clang exposes the AST, but ideally those hacks are well identified and don't interact randomly with each others. As an example, in the current bindgen when scanning the parameters of a function that references a struct clones all the struct information, then if the struct name changes (because we mangle it), everything breaks. 2) Support extending the bindgen output without having to deal with clang. The way I'm aiming to do this is separating completely the parsing stage from the code generation one, and providing a single id for each item the binding generator provides. 3) No more random mutation of the internal representation from anywhere. That means no more Rc<RefCell<T>>, no more random circular references, no more borrow_state... nothing. 4) No more deduplication of declarations before code generation. Current bindgen has a stage, called `tag_dup_decl`[1], that takes care of deduplicating declarations. That's completely buggy, and for C++ it's a complete mess, since we YOLO modify the world. I've managed to take rid of this using the clang canonical declaration, and the definition, to avoid scanning any type/item twice. 5) Code generation should not modify any internal data structure. It can lookup things, traverse whatever it needs, but not modifying randomly. 6) Each item should have a canonical name, and a single source of mangling logic, and that should be computed from the inmutable state, at code generation. I've put a few canonical_name stuff in the code generation phase, but it's still not complete, and should change if I implement namespaces. Improvements pending until this can land: 1) Add support for missing core stuff, mainly generating functions (note that we parse the signatures for types correctly though), bitfields, generating C++ methods. 2) Add support for the necessary features that were added to work around some C++ pitfalls, like opaque types, etc... 3) Add support for the sugar that Manish added recently. 4) Optionally (and I guess this can land without it, because basically nobody uses it since it's so buggy), bring back namespace support. These are not completely trivial, but I think I can do them quite easily with the current architecture. I'm putting the current state of affairs here as a request for comments... Any thoughts? Note that there are still a few smells I want to eventually re-redesign, like the ParseError::Recurse thing, but until that happens I'm way happier with this kind of architecture. I'm keeping the old `parser.rs` and `gen.rs` in tree just for reference while I code, but they will go away. [1]: https://github.com/Yamakaky/rust-bindgen/blob/master/src/gen.rs#L448 Checkpoint to show a rust ICE. Union fields. Parse annotations. Multiple cleanups. Wip Whohoo
1 parent 89e2725 commit de9eb58

File tree

107 files changed

+6262
-3332
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

107 files changed

+6262
-3332
lines changed

Cargo.toml

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
[package]
2-
authors = ["Jyun-Yan You <[email protected]>"]
2+
authors = [
3+
"Jyun-Yan You <[email protected]>",
4+
"Emilio Cobos Álvarez <[email protected]>",
5+
"The Servo project developers",
6+
]
37
build = "build.rs"
48
description = "A binding generator for Rust"
5-
homepage = "https://github.com/crabtw/rust-bindgen"
9+
homepage = "https://github.com/servo/rust-bindgen"
610
keywords = ["bindings", "ffi", "code-generation"]
711
license = "BSD-3-Clause"
812
name = "bindgen"
@@ -22,6 +26,7 @@ clang-sys = "0.8.0"
2226
docopt = "0.6.82"
2327
libc = "0.2.*"
2428
log = "0.3.*"
29+
env_logger = "*"
2530
rustc-serialize = "0.3.19"
2631
syntex_syntax = "0.38"
2732

build.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ mod codegen {
55

66
pub fn main() {
77
let out_dir = env::var_os("OUT_DIR").unwrap();
8-
let src = Path::new("src/gen.rs");
9-
let dst = Path::new(&out_dir).join("gen.rs");
8+
let src = Path::new("src/codegen/mod.rs");
9+
let dst = Path::new(&out_dir).join("codegen.rs");
1010

1111
quasi_codegen::expand(&src, &dst).unwrap();
12-
println!("cargo:rerun-if-changed=src/gen.rs");
12+
println!("cargo:rerun-if-changed=src/codegen/mod.rs");
1313
}
1414
}
1515

src/bin/bindgen.rs

Lines changed: 24 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,20 @@
22
#![crate_type = "bin"]
33

44
extern crate bindgen;
5+
extern crate env_logger;
56
#[macro_use]
67
extern crate docopt;
78
#[macro_use]
89
extern crate log;
910
extern crate clang_sys;
1011
extern crate rustc_serialize;
1112

12-
use bindgen::{Bindings, BindgenOptions, LinkType, Logger};
13+
use bindgen::{Bindings, BindgenOptions, LinkType};
1314
use std::io;
1415
use std::path;
1516
use std::env;
1617
use std::default::Default;
1718
use std::fs;
18-
use std::process::exit;
19-
20-
struct StdLogger;
21-
22-
impl Logger for StdLogger {
23-
fn error(&self, msg: &str) {
24-
println!("{}", msg);
25-
}
26-
27-
fn warn(&self, msg: &str) {
28-
println!("{}", msg);
29-
}
30-
}
3119

3220
const USAGE: &'static str = "
3321
Usage:
@@ -95,15 +83,15 @@ Options:
9583
ulonglong
9684
slonglong
9785
98-
--raw-line=<raw> TODO
99-
--dtor-attr=<attr> TODO
100-
--no-class-constants TODO
101-
--no-unstable-rust TODO
102-
--no-namespaced-constants TODO
103-
--no-bitfield-methods TODO
104-
--ignore-methods TODO
105-
--opaque-type=<type> TODO
106-
--blacklist-type=<type> TODO
86+
--raw-line=<raw> Add a raw line at the beginning of the output.
87+
--dtor-attr=<attr> Attributes to add to structures with destructor.
88+
--no-class-constants Avoid generating class constants.
89+
--no-unstable-rust Avoid generating unstable rust.
90+
--no-namespaced-constants Avoid generating constants right under namespaces.
91+
--no-bitfield-methods Avoid generating methods for bitfield access.
92+
--ignore-methods Avoid generating all kind of methods.
93+
--opaque-type=<type> Mark a type as opaque.
94+
--blacklist-type=<type> Mark a type as hidden.
10795
10896
<clang-args> Options other than stated above are passed
10997
directly through to clang.
@@ -182,7 +170,7 @@ impl Into<ParseResult<(BindgenOptions, Box<io::Write>)>> for Args {
182170
options.gen_bitfield_methods = !self.flag_no_bitfield_methods;
183171
options.ignore_methods = self.flag_ignore_methods;
184172
options.opaque_types.extend(self.flag_opaque_type.drain(..));
185-
options.blacklist_type.extend(self.flag_blacklist_type.drain(..));
173+
options.hidden_types.extend(self.flag_blacklist_type.drain(..));
186174
options.clang_args.extend(self.arg_clang_args.drain(..));
187175
options.clang_args.push(self.arg_input_header);
188176

@@ -191,6 +179,13 @@ impl Into<ParseResult<(BindgenOptions, Box<io::Write>)>> for Args {
191179
}
192180

193181
pub fn main() {
182+
log::set_logger(|max_log_level| {
183+
use env_logger::Logger;
184+
let env_logger = Logger::new();
185+
max_log_level.set(env_logger.filter());
186+
Box::new(env_logger)
187+
}).expect("Failed to set logger.");
188+
194189
let mut bind_args: Vec<_> = env::args().collect();
195190

196191
if let Some(clang) = clang_sys::support::Clang::find(None) {
@@ -212,24 +207,13 @@ pub fn main() {
212207
.and_then(|d| d.argv(bind_args.iter()).decode())
213208
.unwrap_or_else(|e| e.exit());
214209

215-
let logger = StdLogger;
216210
let result: ParseResult<_> = args.into();
217211
let (options, out) = result.unwrap_or_else(|msg| {
218-
logger.error(&msg);
219-
exit(-1);
212+
panic!("Failed to generate_bindings: {:?}", msg);
220213
});
221214

222-
match Bindings::generate(&options, Some(&logger as &Logger), None) {
223-
Ok(bindings) => match bindings.write(out) {
224-
Ok(()) => (),
225-
Err(e) => {
226-
logger.error(&format!("Unable to write bindings to file. {}", e));
227-
exit(-1);
228-
}
229-
},
230-
Err(()) => {
231-
logger.error("Failed to generate bindings".into());
232-
exit(-1);
233-
}
234-
}
215+
let bindings = Bindings::generate(options, None)
216+
.expect("Unable to generate bindings");
217+
bindings.write(out)
218+
.expect("Unable to write bindings to file.");
235219
}

0 commit comments

Comments
 (0)