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
// Copyright 2016 Kyle Mayes
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A Rust bindings generator.

#![feature(rustc_private)]

#![warn(missing_copy_implementations, missing_debug_implementations, missing_docs)]

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", warn(clippy))]

extern crate clang;
extern crate clang_sys;
extern crate libc;
extern crate syntax;

use std::collections::{HashMap};
use std::io::{Write};
use std::path::{PathBuf};

use clang::{Clang, Index, TranslationUnit};
use clang::sonar::{self, Declaration};

use syntax::print::pprust;
use syntax::abi::{Abi};
use syntax::ast::*;
use syntax::codemap::{Span, DUMMY_SP};
use syntax::ptr::{P};

mod ast;
use self::ast::*;

//================================================
// Macros
//================================================

// str_vec! ______________________________________

macro_rules! str_vec {
    ($($string:expr), *) => (vec![$($string.into()), *]);
}

// try_io! _______________________________________

macro_rules! try_io {
    ($result:expr) => {
        match $result {
            Ok(ok) => ok,
            Err(err) => return Err(format!("{:?}", err)),
        }
    }
}

//================================================
// Enums
//================================================

// Filter ________________________________________

/// Indicates which kinds of declarations will be filtered out of generated bindings.
#[derive(Copy, Clone, Debug)]
pub enum Filter {
    /// No declarations will be filtered out.
    None,
    /// Declarations in system headers will be filtered out.
    System,
    /// Declarations not in main headers will be filtered out.
    NonMain,
}

impl Filter {
    //- Accessors --------------------------------

    fn filter(self, declaration: &Declaration) -> bool {
        match self {
            Filter::None => true,
            Filter::System => !declaration.entity.is_in_system_header(),
            Filter::NonMain => declaration.entity.is_in_main_file(),
        }
    }
}

//================================================
// Structs
//================================================

// Generator _____________________________________

/// Generates Rust bindings.
#[derive(Debug, Default)]
pub struct Generator {
    headers: Vec<(PathBuf, Vec<String>)>,
    options: GeneratorOptions,
}

impl Generator {
    //- Constructors -----------------------------

    /// Constructs a new `Generator`.
    pub fn new() -> Generator {
        Generator::default()
    }

    //- Mutators ---------------------------------

    /// Adds a header to be parsed along with the arguments to pass to `libclang`.
    pub fn header<H: Into<PathBuf>, S: AsRef<str>>(
        &mut self, header: H, arguments: &[S]
    ) -> &mut Generator {
        self.headers.push((header.into(), arguments.iter().map(|a| a.as_ref().into()).collect()));
        self
    }

    /// Sets whether unsupported types will be ignored and treated as `void`.
    ///
    /// Default: `false`
    pub fn allow_unsupported_types(&mut self, allow_unsupported_types: bool) -> &mut Generator {
        self.options.allow_unsupported_types = allow_unsupported_types;
        self
    }

    /// Sets the traits that will be derived by generated enums.
    ///
    /// Default: `&["Copy", "Clone", "Debug", "PartialEq", "Eq", "PartialOrd", "Ord", "Hash"]`
    pub fn derive_enum<S: AsRef<str>>(&mut self, derive_enum: &[S]) -> &mut Generator {
        self.options.derive_enum = derive_enum.iter().map(|f| f.as_ref().into()).collect();
        self
    }

    /// Sets the traits that will be derived by generated structs.
    ///
    /// Default: `&["Copy", "Clone", "Debug"]`
    pub fn derive_struct<S: AsRef<str>>(&mut self, derive_struct: &[S]) -> &mut Generator {
        self.options.derive_struct = derive_struct.iter().map(|f| f.as_ref().into()).collect();
        self
    }

    /// Sets whether `clang` diagnostics will be printed to `stdout`.
    ///
    /// Default: `false`
    pub fn display_diagnostics(&mut self, display_diagnostics: bool) -> &mut Generator {
        self.options.display_diagnostics = display_diagnostics;
        self
    }

    /// Sets which kinds of declarations will be filtered out.
    ///
    /// Default: `Filter::None`
    pub fn filter(&mut self, filter: Filter) -> &mut Generator {
        self.options.filter = filter;
        self
    }

    /// Sets the enum variants to ignore.
    ///
    /// Default: `&[]`
    pub fn ignore_enum_variants<N: AsRef<str>, V: AsRef<str>, VS: AsRef<[V]>>(
        &mut self, ignore_enum_variants: &[(N, VS)]
    ) -> &mut Generator {
        self.options.ignore_enum_variants = ignore_enum_variants.iter().map(|&(ref e, ref vs)| {
            (e.as_ref().into(), vs.as_ref().iter().map(|v| v.as_ref().into()).collect())
        }).collect();
        self
    }

    /// Sets the name of the `mod` that will contain nested enums, structs, and unions.
    ///
    /// Default: `"nested"`
    pub fn nested_mod<S: Into<String>>(&mut self, nested_mod: S) -> &mut Generator {
        self.options.nested_mod = nested_mod.into();
        self
    }

    /// Sets the prefix for primitive types.
    ///
    /// Primitive types are the aliases for built-in C types (e.g., `c_int` or `c_void`). The prefix
    /// is the global path where these types can be found (e.g., `&["std", "os", "raw"]` becomes
    /// the prefix `"::std::os::raw"`).
    ///
    /// Default: `&["libc"]`
    pub fn primitive<S: AsRef<str>>(&mut self, primitive: &[S]) -> &mut Generator {
        self.options.primitive = primitive.iter().map(|f| f.as_ref().into()).collect();
        self
    }

    /// Sets the span for the generated bindings.
    ///
    /// Default: `syntax::codemap::DUMMY_SP`
    pub fn span(&mut self, span: Span) -> &mut Generator {
        self.options.span = span;
        self
    }

    /// Returns the generated bindings.
    ///
    /// # Failures
    ///
    /// * called from multiple threads simultaneously
    /// * unable to open and parse the headers
    pub fn generate(&mut self) -> Result<Mod, String> {
        let search = if let Some(clang) = clang_sys::support::Clang::find(None) {
            clang.c_search_paths.iter().map(|p| format!("-I{}", p.to_string_lossy())).collect()
        } else {
            vec![]
        };

        let clang = try!(Clang::new().map_err(|_| "called from multiple threads simultaneously"));
        let index = Index::new(&clang, false, self.options.display_diagnostics);
        let mut tus = vec![];
        for &(ref header, ref arguments) in &self.headers {
            let arguments = search.iter().chain(arguments.iter()).collect::<Vec<_>>();
            tus.push(try!(index.parser(header).arguments(&arguments[..]).parse()));
        }

        let mut nested = vec![];
        let mut items = generate_typedefs(&self.options, &tus[..]);
        items.extend(generate_enums(&self.options, &tus[..]).into_iter());
        items.extend(generate_records(&self.options, &tus[..], &mut nested).into_iter());
        items.extend(generate_functions(&self.options, &tus[..]).into_iter());

        // Generate nested items.
        nested.sort_by_key(|t| t.ident.name.as_str());
        if !nested.is_empty() {
            items.insert(0, ast::to_item_mod(self.options.span, &self.options.nested_mod, nested));
        }

        // Generate opaque type aliases.
        let mut opaque = c::get_opaque_record_typedefs().into_iter().map(|t| {
            t.into_rust(&self.options)
        }).collect::<Vec<_>>();
        opaque.sort_by_key(|t| t.ident.name.as_str());

        opaque.extend(items.into_iter());
        Ok(Mod { inner: self.options.span, items: opaque })
    }

    /// Writes the generated bindings to the supplied writer.
    ///
    /// # Failures
    ///
    /// * called from multiple threads simultaneously
    /// * unable to open and parse the headers
    /// * unable to write the generated bindings
    pub fn write<W: Write>(&mut self, writer: &mut W) -> Result<(), String> {
        try_io!(write!(writer, "#![allow(dead_code, non_camel_case_types, non_snake_case)]\n"));
        let mut items = try_io!(self.generate()).items.into_iter().peekable();
        while let Some(item) = items.next() {
            let string = pprust::item_to_string(&item);
            if items.peek().map_or(false, |i| is_ty(i)) {
                try_io!(write!(writer, "\n{}", string));
            } else {
                try_io!(write!(writer, "\n{}\n", string));
            }
        }
        try_io!(writer.flush());
        Ok(())
    }
}

// GeneratorOptions ______________________________

#[doc(hidden)]
#[derive(Debug)]
pub struct GeneratorOptions {
    pub allow_unsupported_types: bool,
    pub derive_enum: Vec<String>,
    pub derive_struct: Vec<String>,
    pub display_diagnostics: bool,
    pub filter: Filter,
    pub ignore_enum_variants: HashMap<String, Vec<String>>,
    pub nested_mod: String,
    pub primitive: Vec<String>,
    pub span: Span,
}

impl Default for GeneratorOptions {
    fn default() -> GeneratorOptions {
        GeneratorOptions {
            allow_unsupported_types: false,
            derive_enum: str_vec![
                "Copy", "Clone", "Debug", "PartialEq", "Eq", "PartialOrd", "Ord", "Hash"
            ],
            derive_struct: str_vec!["Copy", "Clone", "Debug"],
            display_diagnostics: false,
            filter: Filter::None,
            ignore_enum_variants: HashMap::new(),
            nested_mod: "nested".into(),
            primitive: str_vec!["libc"],
            span: DUMMY_SP,
        }
    }
}

//================================================
// Functions
//================================================

fn generate_typedefs(options: &GeneratorOptions, tus: &[TranslationUnit]) -> Vec<P<Item>> {
    let mut typedefs = HashMap::new();
    for tu in tus {
        let children = tu.get_entity().get_children();
        for typedef in sonar::find_typedefs(children).filter(|t| options.filter.filter(t)) {
            typedefs.entry(typedef.name.clone()).or_insert_with(|| c::Typedef::new(typedef));
        }
    }
    let mut typedefs = typedefs.into_iter().map(|(_, t)| t.into_rust(options)).collect::<Vec<_>>();
    typedefs.sort_by_key(|t| t.ident.name.as_str());
    typedefs
}

fn generate_enums(options: &GeneratorOptions, tus: &[TranslationUnit]) -> Vec<P<Item>> {
    let mut enums = HashMap::new();
    for tu in tus {
        let children = tu.get_entity().get_children();
        for enum_ in sonar::find_enums(children).filter(|e| options.filter.filter(e)) {
            enums.entry(enum_.name.clone()).or_insert_with(|| c::Enum::new(enum_));
        }
    }
    let mut enums = enums.into_iter().map(|(_, e)| e.into_rust(options)).collect::<Vec<_>>();
    enums.sort_by_key(|es| es[0].ident.name.as_str());
    enums.into_iter().flat_map(|es| es.into_iter()).collect()
}

fn generate_records(
    options: &GeneratorOptions, tus: &[TranslationUnit], nested: &mut Vec<P<Item>>
) -> Vec<P<Item>> {
    let mut records = HashMap::new();
    for tu in tus {
        let children = tu.get_entity().get_children();
        for struct_ in sonar::find_structs(&children[..]).filter(|s| options.filter.filter(s)) {
            records.entry(struct_.name.clone()).or_insert_with(|| c::Record::new(struct_));
        }
        for union in sonar::find_unions(children).filter(|u| options.filter.filter(u)) {
            records.entry(union.name.clone()).or_insert_with(|| c::Record::new(union));
        }
    }
    let mut records = records.into_iter().map(|(_, r)| {
        let (subnested, items) = r.into_rust(options);
        nested.extend(subnested.into_iter());
        items
    }).collect::<Vec<_>>();
    records.sort_by_key(|rs| rs[0].ident.name.as_str());
    records.into_iter().flat_map(|rs| rs.into_iter()).collect()
}

fn generate_functions(options: &GeneratorOptions, tus: &[TranslationUnit]) -> Option<P<Item>> {
    let mut functions = HashMap::new();
    for tu in tus {
        let children = tu.get_entity().get_children();
        for function in sonar::find_functions(children).filter(|f| options.filter.filter(f)) {
            functions.entry(function.name.clone()).or_insert_with(|| {
                c::Function::new(Some(function.entity), function.entity.get_type().unwrap())
            });
        }
    }
    if functions.is_empty() {
        None
    } else {
        let mut functions = functions.into_iter().map(|(_, f)| {
            f.into_rust(options)
        }).collect::<Vec<ForeignItem>>();
        functions.sort_by_key(|f| f.ident.name.as_str());
        let functions = ItemKind::ForeignMod(ForeignMod { abi: Abi::C, items: functions });
        Some(to_item(options.span, "", functions, vec![]))
    }
}

fn is_ty(item: &Item) -> bool {
    if let ItemKind::Ty(_, _) = item.node {
        true
    } else {
        false
    }
}