1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
#![deny(missing_docs)]
#![deny(warnings)]
#![allow(deprecated)]
#![allow(non_upper_case_globals)]
#[macro_use]
extern crate cfg_if;
extern crate cexpr;
extern crate syntex_syntax as syntax;
extern crate aster;
extern crate quasi;
extern crate clang_sys;
extern crate libc;
extern crate regex;
#[macro_use]
extern crate lazy_static;
#[cfg(feature = "logging")]
#[macro_use]
extern crate log;
#[cfg(not(feature = "logging"))]
#[macro_use]
mod log_stubs;
macro_rules! doc_mod {
($m:ident, $doc_mod_name:ident) => {
cfg_if! {
if #[cfg(feature = "docs_")] {
pub mod $doc_mod_name {
pub use super::$m::*;
}
} else {
}
}
};
}
mod clangll;
mod clang;
mod ir;
mod parse;
mod regex_set;
mod uses;
pub mod chooser;
#[cfg(rustfmt)]
mod codegen;
doc_mod!(clang, clang_docs);
doc_mod!(ir, ir_docs);
doc_mod!(parse, parse_docs);
doc_mod!(regex_set, regex_set_docs);
doc_mod!(uses, uses_docs);
mod codegen {
include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
}
use ir::context::{BindgenContext, ItemId};
use ir::item::Item;
use parse::{ClangItemParser, ParseError};
use regex_set::RegexSet;
use std::borrow::Borrow;
use std::collections::HashSet;
use std::fs::OpenOptions;
use std::io::{self, Write};
use std::path::Path;
use syntax::ast;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::print::pp::eof;
use syntax::print::pprust;
use syntax::ptr::P;
#[derive(Debug, Clone)]
pub struct CodegenConfig {
pub functions: bool,
pub types: bool,
pub vars: bool,
pub methods: bool,
}
impl CodegenConfig {
pub fn all() -> Self {
CodegenConfig {
functions: true,
types: true,
vars: true,
methods: true,
}
}
pub fn nothing() -> Self {
CodegenConfig {
functions: false,
types: false,
vars: false,
methods: false,
}
}
}
impl Default for CodegenConfig {
fn default() -> Self {
CodegenConfig::all()
}
}
#[derive(Debug,Default)]
pub struct Builder {
options: BindgenOptions,
}
pub fn builder() -> Builder {
Default::default()
}
impl Builder {
pub fn header<T: Into<String>>(mut self, header: T) -> Builder {
let header = header.into();
self.options.input_header = Some(header.clone());
self.clang_arg(header)
}
pub fn dummy_uses<T: Into<String>>(mut self, dummy_uses: T) -> Builder {
self.options.dummy_uses = Some(dummy_uses.into());
self
}
pub fn hide_type<T: Into<String>>(mut self, arg: T) -> Builder {
self.options.hidden_types.insert(arg.into());
self
}
pub fn opaque_type<T: Into<String>>(mut self, arg: T) -> Builder {
self.options.opaque_types.insert(arg.into());
self
}
pub fn whitelisted_type<T: Borrow<str>>(mut self, arg: T) -> Builder {
self.options.whitelisted_types.insert(&arg);
self
}
pub fn whitelisted_function<T: Borrow<str>>(mut self, arg: T) -> Builder {
self.options.whitelisted_functions.insert(&arg);
self
}
pub fn whitelisted_var<T: Borrow<str>>(mut self, arg: T) -> Builder {
self.options.whitelisted_vars.insert(&arg);
self
}
pub fn bitfield_enum<T: Borrow<str>>(mut self, arg: T) -> Builder {
self.options.bitfield_enums.insert(&arg);
self
}
pub fn raw_line<T: Into<String>>(mut self, arg: T) -> Builder {
self.options.raw_lines.push(arg.into());
self
}
pub fn clang_arg<T: Into<String>>(mut self, arg: T) -> Builder {
self.options.clang_args.push(arg.into());
self
}
pub fn link<T: Into<String>>(mut self, library: T) -> Builder {
self.options.links.push((library.into(), LinkType::Default));
self
}
pub fn link_static<T: Into<String>>(mut self, library: T) -> Builder {
self.options.links.push((library.into(), LinkType::Static));
self
}
pub fn link_framework<T: Into<String>>(mut self, library: T) -> Builder {
self.options.links.push((library.into(), LinkType::Framework));
self
}
pub fn emit_builtins(mut self) -> Builder {
self.options.builtins = true;
self
}
pub fn no_convert_floats(mut self) -> Self {
self.options.convert_floats = false;
self
}
pub fn emit_clang_ast(mut self) -> Builder {
self.options.emit_ast = true;
self
}
pub fn emit_ir(mut self) -> Builder {
self.options.emit_ir = true;
self
}
pub fn enable_cxx_namespaces(mut self) -> Builder {
self.options.enable_cxx_namespaces = true;
self
}
pub fn disable_name_namespacing(mut self) -> Builder {
self.options.disable_name_namespacing = true;
self
}
pub fn ignore_functions(mut self) -> Builder {
self.options.codegen_config.functions = false;
self
}
pub fn ignore_methods(mut self) -> Builder {
self.options.codegen_config.methods = false;
self
}
pub fn no_unstable_rust(mut self) -> Builder {
self.options.unstable_rust = false;
self
}
pub fn use_core(mut self) -> Builder {
self.options.use_core = true;
self
}
pub fn ctypes_prefix<T: Into<String>>(mut self, prefix: T) -> Builder {
self.options.ctypes_prefix = Some(prefix.into());
self
}
pub fn type_chooser(mut self, cb: Box<chooser::TypeChooser>) -> Self {
self.options.type_chooser = Some(cb);
self
}
pub fn with_codegen_config(mut self, config: CodegenConfig) -> Self {
self.options.codegen_config = config;
self
}
pub fn generate<'ctx>(self) -> Result<Bindings<'ctx>, ()> {
Bindings::generate(self.options, None)
}
}
#[derive(Debug)]
#[deprecated]
pub struct BindgenOptions {
pub hidden_types: HashSet<String>,
pub opaque_types: HashSet<String>,
pub whitelisted_types: RegexSet,
pub whitelisted_functions: RegexSet,
pub whitelisted_vars: RegexSet,
pub bitfield_enums: RegexSet,
pub builtins: bool,
pub links: Vec<(String, LinkType)>,
pub emit_ast: bool,
pub emit_ir: bool,
pub enable_cxx_namespaces: bool,
pub disable_name_namespacing: bool,
pub derive_debug: bool,
pub unstable_rust: bool,
pub use_core: bool,
pub ctypes_prefix: Option<String>,
pub namespaced_constants: bool,
pub msvc_mangling: bool,
pub convert_floats: bool,
pub raw_lines: Vec<String>,
pub clang_args: Vec<String>,
pub input_header: Option<String>,
pub dummy_uses: Option<String>,
pub type_chooser: Option<Box<chooser::TypeChooser>>,
pub codegen_config: CodegenConfig,
}
impl Default for BindgenOptions {
fn default() -> BindgenOptions {
BindgenOptions {
hidden_types: Default::default(),
opaque_types: Default::default(),
whitelisted_types: Default::default(),
whitelisted_functions: Default::default(),
whitelisted_vars: Default::default(),
bitfield_enums: Default::default(),
builtins: false,
links: vec![],
emit_ast: false,
emit_ir: false,
derive_debug: true,
enable_cxx_namespaces: false,
disable_name_namespacing: false,
unstable_rust: true,
use_core: false,
ctypes_prefix: None,
namespaced_constants: true,
msvc_mangling: false,
convert_floats: true,
raw_lines: vec![],
clang_args: vec![],
input_header: None,
dummy_uses: None,
type_chooser: None,
codegen_config: CodegenConfig::all(),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum LinkType {
Default,
Static,
Framework,
}
#[derive(Debug)]
pub struct Bindings<'ctx> {
context: BindgenContext<'ctx>,
module: ast::Mod,
}
impl<'ctx> Bindings<'ctx> {
#[deprecated]
pub fn generate(options: BindgenOptions,
span: Option<Span>)
-> Result<Bindings<'ctx>, ()> {
let span = span.unwrap_or(DUMMY_SP);
let mut context = BindgenContext::new(options);
parse(&mut context);
let module = ast::Mod {
inner: span,
items: codegen::codegen(&mut context),
};
Ok(Bindings {
context: context,
module: module,
})
}
pub fn into_ast(self) -> Vec<P<ast::Item>> {
self.module.items
}
pub fn to_string(&self) -> String {
let mut mod_str = vec![];
{
let ref_writer = Box::new(mod_str.by_ref()) as Box<Write>;
self.write(ref_writer).expect("Could not write bindings to string");
}
String::from_utf8(mod_str).unwrap()
}
pub fn write_to_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
let file = try!(OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(path));
self.write(Box::new(file))
}
pub fn write<'a>(&self, mut writer: Box<Write + 'a>) -> io::Result<()> {
try!(writer.write("/* automatically generated by rust-bindgen */\n\n"
.as_bytes()));
for line in self.context.options().raw_lines.iter() {
try!(writer.write(line.as_bytes()));
try!(writer.write("\n".as_bytes()));
}
if !self.context.options().raw_lines.is_empty() {
try!(writer.write("\n".as_bytes()));
}
let mut ps = pprust::rust_printer(writer);
try!(ps.print_mod(&self.module, &[]));
try!(ps.print_remaining_comments());
try!(eof(&mut ps.s));
ps.s.out.flush()
}
pub fn write_dummy_uses(&mut self) -> io::Result<()> {
let file =
if let Some(ref dummy_path) = self.context.options().dummy_uses {
Some(try!(OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(dummy_path)))
} else {
None
};
if let Some(file) = file {
try!(uses::generate_dummy_uses(&mut self.context, file));
}
Ok(())
}
}
fn filter_builtins(ctx: &BindgenContext, cursor: &clang::Cursor) -> bool {
let (file, _, _, _) = cursor.location().location();
match file.name() {
None => ctx.options().builtins,
Some(..) => true,
}
}
pub fn parse_one(ctx: &mut BindgenContext,
cursor: clang::Cursor,
parent: Option<ItemId>)
-> clangll::Enum_CXVisitorResult {
if !filter_builtins(ctx, &cursor) {
return CXChildVisit_Continue;
}
use clangll::CXChildVisit_Continue;
match Item::parse(cursor, parent, ctx) {
Ok(..) => {},
Err(ParseError::Continue) => {}
Err(ParseError::Recurse) => {
cursor.visit(|child| parse_one(ctx, child, parent));
}
}
CXChildVisit_Continue
}
fn parse(context: &mut BindgenContext) {
use clang::Diagnostic;
use clangll::*;
for d in context.translation_unit().diags().iter() {
let msg = d.format(Diagnostic::default_opts());
let is_err = d.severity() >= CXDiagnostic_Error;
println!("{}, err: {}", msg, is_err);
}
let cursor = context.translation_unit().cursor();
if context.options().emit_ast {
cursor.visit(|cur| clang::ast_dump(&cur, 0));
}
let root = context.root_module();
context.with_module(root, |context| {
cursor.visit(|cursor| parse_one(context, cursor, None))
});
assert!(context.current_module() == context.root_module(),
"How did this happen?");
}
#[derive(Debug)]
pub struct ClangVersion {
pub parsed: Option<(u32, u32)>,
pub full: String,
}
pub fn clang_version() -> ClangVersion {
let raw_v: String = clang::extract_clang_version();
let split_v: Option<Vec<&str>> = raw_v.split_whitespace()
.nth(2)
.map(|v| v.split('.').collect());
match split_v {
Some(v) => {
if v.len() >= 2 {
let maybe_major = v[0].parse::<u32>();
let maybe_minor = v[1].parse::<u32>();
match (maybe_major, maybe_minor) {
(Ok(major), Ok(minor)) => {
return ClangVersion {
parsed: Some((major, minor)),
full: raw_v.clone(),
}
}
_ => {}
}
}
}
None => {}
};
ClangVersion {
parsed: None,
full: raw_v.clone(),
}
}