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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use std::io::Write;
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::cmp::Ordering;
use std::fs::File;
use std::path;

use syn;

use bindgen::cargo::Cargo;
use bindgen::config::{self, Config, Language};
use bindgen::annotation::*;
use bindgen::items::*;
use bindgen::rust_lib;
use bindgen::utilities::*;
use bindgen::writer::{Source, SourceWriter};

/// A path ref is used to reference a path value
pub type PathRef = String;

/// A path value is any type of rust item besides a function
#[derive(Debug, Clone)]
pub enum PathValue {
    Enum(Enum),
    Struct(Struct),
    OpaqueStruct(OpaqueStruct),
    Typedef(Typedef),
    Specialization(Specialization),
}

impl PathValue {
    pub fn name(&self) -> &String {
        match self {
            &PathValue::Enum(ref x) => { &x.name },
            &PathValue::Struct(ref x) => { &x.name },
            &PathValue::OpaqueStruct(ref x) => { &x.name },
            &PathValue::Typedef(ref x) => { &x.name },
            &PathValue::Specialization(ref x) => { &x.name },
        }
    }

    pub fn add_deps(&self, library: &Library, out: &mut DependencyGraph) {
        match self {
            &PathValue::Enum(_) => { },
            &PathValue::Struct(ref x) => { x.add_deps(library, out); },
            &PathValue::OpaqueStruct(_) => { },
            &PathValue::Typedef(ref x) => { x.add_deps(library, out); },
            &PathValue::Specialization(ref x) => { x.add_deps(library, out); },
        }
    }

    pub fn apply_renaming(&mut self, config: &Config) {
        match self {
            &mut PathValue::Enum(ref mut x) => { x.apply_renaming(config); },
            &mut PathValue::Struct(ref mut x) => { x.apply_renaming(config); },
            _ => { },
        }
    }
}

/// A dependency graph is used for gathering what order to output the types.
pub struct DependencyGraph {
    order: Vec<PathValue>,
    items: HashSet<PathRef>,
}

impl DependencyGraph {
    fn new() -> DependencyGraph {
        DependencyGraph {
            order: Vec::new(),
            items: HashSet::new(),
        }
    }
}

/// A library contains all of the information needed to generate bindings for a rust library.
#[derive(Debug, Clone)]
pub struct Library {
    bindings_crate_name: String,
    config: Config,

    enums: BTreeMap<String, Enum>,
    structs: BTreeMap<String, Struct>,
    opaque_structs: BTreeMap<String, OpaqueStruct>,
    typedefs: BTreeMap<String, Typedef>,
    specializations: BTreeMap<String, Specialization>,
    functions: BTreeMap<String, Function>,
}

impl Library {
    fn blank(bindings_crate_name: &str, config: &Config) -> Library {
        Library {
            bindings_crate_name: String::from(bindings_crate_name),
            config: config.clone(),

            enums: BTreeMap::new(),
            structs: BTreeMap::new(),
            opaque_structs: BTreeMap::new(),
            typedefs: BTreeMap::new(),
            specializations: BTreeMap::new(),
            functions: BTreeMap::new(),
        }
    }

    /// Parse the specified crate or source file and load #[repr(C)] types for binding generation.
    pub fn load_src(src: &path::Path,
                    config: &Config) -> Result<Library, String>
    {
        let mut library = Library::blank("", config);

        rust_lib::parse_src(src, &mut |crate_name, items| {
            library.load_from_crate_mod(&crate_name, items);
        })?;

        Ok(library)
    }

    /// Parse the specified crate or source file and load #[repr(C)] types for binding generation.
    pub fn load_crate(lib: Cargo,
                      config: &Config) -> Result<Library, String>
    {
        let mut library = Library::blank(lib.binding_crate_name(),
                                         config);

        rust_lib::parse_lib(lib,
                            config.parse.parse_deps,
                            &config.parse.include,
                            &config.parse.exclude,
                            &config.parse.expand,
                            &mut |crate_name, items| {
            library.load_from_crate_mod(&crate_name, items);
        })?;

        Ok(library)
    }

    fn load_from_crate_mod(&mut self, crate_name: &str, items: &Vec<syn::Item>) {
        for item in items {
            match item.node {
                syn::ItemKind::ForeignMod(ref block) => {
                    if !block.abi.is_c() {
                        info!("skip {}::{} - (extern block must be extern C)", crate_name, &item.ident);
                        continue;
                    }

                    for foreign_item in &block.items {
                        match foreign_item.node {
                            syn::ForeignItemKind::Fn(ref decl,
                                                     ref _generic) => {
                                if crate_name != self.bindings_crate_name {
                                    info!("skip {}::{} - (fn's outside of the binding crate are not used)", crate_name, &foreign_item.ident);
                                    continue;
                                }

                                let annotations = match AnnotationSet::parse(foreign_item.get_doc_attr()) {
                                    Ok(x) => x,
                                    Err(msg) => {
                                        warn!("{}", msg);
                                        AnnotationSet::new()
                                    }
                                };

                                match Function::load(foreign_item.ident.to_string(), annotations, decl, true) {
                                    Ok(func) => {
                                        info!("take {}::{}", crate_name, &foreign_item.ident);

                                        self.functions.insert(func.name.clone(), func);
                                    }
                                    Err(msg) => {
                                        info!("skip {}::{} - ({})", crate_name, &foreign_item.ident, msg);
                                    },
                                }
                            }
                            _ => {}
                        }
                    }
                }
                syn::ItemKind::Fn(ref decl,
                                  ref _unsafe,
                                  ref _const,
                                  ref abi,
                                  ref _generic,
                                  ref _block) => {
                    if crate_name != self.bindings_crate_name {
                        info!("skip {}::{} - (fn's outside of the binding crate are not used)", crate_name, &item.ident);
                        continue;
                    }

                    if item.is_no_mangle() && abi.is_c() {
                        let annotations = match AnnotationSet::parse(item.get_doc_attr()) {
                            Ok(x) => x,
                            Err(msg) => {
                                warn!("{}", msg);
                                AnnotationSet::new()
                            }
                        };

                        match Function::load(item.ident.to_string(), annotations, decl, false) {
                            Ok(func) => {
                                info!("take {}::{}", crate_name, &item.ident);

                                self.functions.insert(func.name.clone(), func);
                            }
                            Err(msg) => {
                                info!("skip {}::{} - ({})", crate_name, &item.ident, msg);
                            },
                        }
                    } else {
                        if item.is_no_mangle() != abi.is_c() {
                            warn!("skip {}::{} - (not both `no_mangle` and `extern \"C\"`)", crate_name, &item.ident);
                        }
                    }
                }
                syn::ItemKind::Struct(ref variant,
                                      ref generics) => {
                    let struct_name = item.ident.to_string();
                    let annotations = match AnnotationSet::parse(item.get_doc_attr()) {
                        Ok(x) => x,
                        Err(msg) => {
                            warn!("{}", msg);
                            AnnotationSet::new()
                        }
                    };

                    if item.is_repr_c() {
                        match Struct::load(struct_name.clone(), annotations.clone(), variant, generics) {
                            Ok(st) => {
                                info!("take {}::{}", crate_name, &item.ident);
                                self.structs.insert(struct_name,
                                                    st);
                            }
                            Err(msg) => {
                                info!("take {}::{} - opaque ({})", crate_name, &item.ident, msg);
                                self.opaque_structs.insert(struct_name.clone(),
                                                           OpaqueStruct::new(struct_name, annotations));
                            }
                        }
                    } else {
                        info!("take {}::{} - opaque (not marked as repr(C))", crate_name, &item.ident);
                        self.opaque_structs.insert(struct_name.clone(),
                                                   OpaqueStruct::new(struct_name, annotations));
                    }
                }
                syn::ItemKind::Enum(ref variants, ref generics) => {
                    if !generics.lifetimes.is_empty() ||
                       !generics.ty_params.is_empty() ||
                       !generics.where_clause.predicates.is_empty() {
                        info!("skip {}::{} - (has generics or lifetimes or where bounds)", crate_name, &item.ident);
                        continue;
                    }

                    let enum_name = item.ident.to_string();
                    let annotations = match AnnotationSet::parse(item.get_doc_attr()) {
                        Ok(x) => x,
                        Err(msg) => {
                            warn!("{}", msg);
                            AnnotationSet::new()
                        }
                    };

                    match Enum::load(enum_name.clone(), item.get_repr(), annotations.clone(), variants) {
                        Ok(en) => {
                            info!("take {}::{}", crate_name, &item.ident);
                            self.enums.insert(enum_name, en);
                        }
                        Err(msg) => {
                            info!("take {}::{} - opaque ({})", crate_name, &item.ident, msg);
                            self.opaque_structs.insert(enum_name.clone(),
                                                       OpaqueStruct::new(enum_name, annotations));
                        }
                    }
                }
                syn::ItemKind::Ty(ref ty, ref generics) => {
                    let alias_name = item.ident.to_string();
                    let annotations = match AnnotationSet::parse(item.get_doc_attr()) {
                        Ok(x) => x,
                        Err(msg) => {
                            warn!("{}", msg);
                            AnnotationSet::new()
                        }
                    };

                    let fail1 = match Specialization::load(alias_name.clone(),
                                                           annotations.clone(),
                                                           generics,
                                                           ty) {
                        Ok(spec) => {
                            info!("take {}::{}", crate_name, &item.ident);
                            self.specializations.insert(alias_name, spec);
                            continue;
                        }
                        Err(msg) => msg,
                    };

                    if !generics.lifetimes.is_empty() ||
                       !generics.ty_params.is_empty() {
                        info!("skip {}::{} - (typedefs cannot have generics or lifetimes)", crate_name, &item.ident);
                        continue;
                    }

                    let fail2 = match Typedef::load(alias_name.clone(), annotations, ty) {
                        Ok(typedef) => {
                            info!("take {}::{}", crate_name, &item.ident);
                            self.typedefs.insert(alias_name, typedef);
                            continue;
                        }
                        Err(msg) => msg,
                    };
                    info!("skip {}::{} - ({} and {})", crate_name, &item.ident, fail1, fail2);
                }
                _ => {}
            }
        }
    }

    pub fn resolve_path(&self, p: &PathRef) -> Option<PathValue> {
        if let Some(x) = self.enums.get(p) {
            return Some(PathValue::Enum(x.clone()));
        }
        if let Some(x) = self.structs.get(p) {
            return Some(PathValue::Struct(x.clone()));
        }
        if let Some(x) = self.opaque_structs.get(p) {
            return Some(PathValue::OpaqueStruct(x.clone()));
        }
        if let Some(x) = self.typedefs.get(p) {
            return Some(PathValue::Typedef(x.clone()));
        }
        if let Some(x) = self.specializations.get(p) {
            return Some(PathValue::Specialization(x.clone()));
        }

        None
    }

    pub fn add_deps_for_path(&self, p: &PathRef, out: &mut DependencyGraph) {
        if let Some(value) = self.resolve_path(p) {
            if !out.items.contains(p) {
                out.items.insert(p.clone());

                value.add_deps(self, out);

                out.order.push(value);
            }
        } else {
            warn!("can't find {}", p);
        }
    }

    /// Build a bindings file from this rust library.
    pub fn generate(self) -> Result<GeneratedBindings, String> {
        let mut result = GeneratedBindings::blank(&self.config);

        // Gather only the items that we need for this
        // `extern "c"` interface
        let mut deps = DependencyGraph::new();
        for (_, function) in &self.functions {
            function.add_deps(&self, &mut deps);
        }

        // Copy the binding items in dependencies order
        // into the GeneratedBindings, specializing any type
        // aliases we encounter
        for dep in deps.order {
            match &dep {
                &PathValue::Struct(ref s) => {
                    if !s.generic_params.is_empty() {
                        continue;
                    }
                }
                &PathValue::Specialization(ref s) => {
                    match s.specialize(&self) {
                        Ok(Some(value)) => {
                            result.items.push(value);
                        }
                        Ok(None) => {},
                        Err(msg) => {
                            warn!("specializing {} failed - ({})", dep.name(), msg);
                        }
                    }
                    continue;
                }
                _ => { }
            }
            result.items.push(dep);
        }

        // Sort enums and opaque structs into their own layers because they don't
        // depend on each other or anything else.
        let ordering = |a: &PathValue, b: &PathValue| {
            match (a, b) {
                (&PathValue::Enum(ref e1), &PathValue::Enum(ref e2)) => e1.name.cmp(&e2.name),
                (&PathValue::Enum(_), _) => Ordering::Less,
                (_, &PathValue::Enum(_)) => Ordering::Greater,

                (&PathValue::OpaqueStruct(ref o1), &PathValue::OpaqueStruct(ref o2)) => o1.name.cmp(&o2.name),
                (&PathValue::OpaqueStruct(_), _) => Ordering::Less,
                (_, &PathValue::OpaqueStruct(_)) => Ordering::Greater,

                _ => Ordering::Equal,
            }
        };
        result.items.sort_by(ordering);

        result.functions = self.functions.iter()
                                         .map(|(_, function)| function.clone())
                                         .collect::<Vec<_>>();

        // Do one last pass to do renaming for all the items
        for item in &mut result.items {
            item.apply_renaming(&self.config);
        }
        for func in &mut result.functions {
            func.apply_renaming(&self.config);
        }

        Ok(result)
    }
}

/// A GeneratedBindings is a completed bindings file ready to be written.
#[derive(Debug, Clone)]
pub struct GeneratedBindings {
    config: Config,

    items: Vec<PathValue>,
    functions: Vec<Function>,
}

impl GeneratedBindings {
    fn blank(config: &Config) -> GeneratedBindings {
        GeneratedBindings {
            config: config.clone(),
            items: Vec::new(),
            functions: Vec::new(),
        }
    }

    pub fn write_to_file(&self, path: &str) {
        self.write(File::create(path).unwrap());
    }

    pub fn write<F: Write>(&self, file: F) {
        let mut out = SourceWriter::new(file, &self.config);

        if let Some(ref f) = self.config.header {
            out.new_line_if_not_start();
            out.write(&f);
            out.new_line();
        }
        if let Some(ref f) = self.config.include_guard {
            out.new_line_if_not_start();
            out.write(&format!("#ifndef {}", f));
            out.new_line();
            out.write(&format!("#define {}", f));
            out.new_line();
        }
        if self.config.include_version {
            out.new_line_if_not_start();
            out.write(&format!("/* Generated with cbindgen:{} */", config::VERSION));
            out.new_line();
        }
        if let Some(ref f) = self.config.autogen_warning {
            out.new_line_if_not_start();
            out.write(&f);
            out.new_line();
        }

        out.new_line_if_not_start();
        if self.config.language == Language::C {
            out.write("#include <stdint.h>");
            out.new_line();
            out.write("#include <stdlib.h>");
            out.new_line();
            out.write("#include <stdbool.h>");
        } else {
            out.write("#include <cstdint>");
            out.new_line();
            out.write("#include <cstdlib>");
        }
        out.new_line();

        if self.config.language == Language::Cxx {
            out.new_line_if_not_start();
            out.write("extern \"C\" {");
            out.new_line();

            let mut wrote_namespace: bool = false;
            if let Some(ref namespace) = self.config.namespace {
                wrote_namespace = true;

                out.new_line();
                out.write("namespace ");
                out.write(namespace);
                out.write(" {");
            }
            if let Some(ref namespaces) = self.config.namespaces {
                wrote_namespace = true;
                for namespace in namespaces {
                    out.new_line();
                    out.write("namespace ");
                    out.write(namespace);
                    out.write(" {");
                }
            }
            if wrote_namespace {
                out.new_line();
            }
        }

        for item in &self.items {
            out.new_line_if_not_start();
            match item {
                &PathValue::Enum(ref x) => x.write(&self.config, &mut out),
                &PathValue::Struct(ref x) => x.write(&self.config, &mut out),
                &PathValue::OpaqueStruct(ref x) => x.write(&self.config, &mut out),
                &PathValue::Typedef(ref x) => x.write(&self.config, &mut out),
                &PathValue::Specialization(_) => {
                    panic!("should not encounter a specialization in a built library")
                }
            }
            out.new_line();
        }

        if let Some(ref f) = self.config.autogen_warning {
            out.new_line_if_not_start();
            out.write(&f);
            out.new_line();
        }

        for function in &self.functions {
            if function.extern_decl {
                continue;
            }

            out.new_line_if_not_start();
            function.write(&self.config, &mut out);
            out.new_line();
        }

        if self.config.language == Language::Cxx {
            let mut wrote_namespace: bool = false;
            if let Some(ref namespaces) = self.config.namespaces {
                wrote_namespace = true;

                for namespace in namespaces.iter().rev() {
                    out.new_line_if_not_start();
                    out.write("} // namespace ");
                    out.write(namespace);
                }
            }
            if let Some(ref namespace) = self.config.namespace {
                wrote_namespace = true;

                out.new_line_if_not_start();
                out.write("} // namespace ");
                out.write(namespace);
            }
            if wrote_namespace {
                out.new_line();
            }

            out.new_line_if_not_start();
            out.write("} // extern \"C\"");
            out.new_line();
        }

        if let Some(ref f) = self.config.autogen_warning {
            out.new_line_if_not_start();
            out.write(&f);
            out.new_line();
        }
        if let Some(ref f) = self.config.include_guard {
            out.new_line_if_not_start();
            out.write(&format!("#endif // {}", f));
            out.new_line();
        }
        if let Some(ref f) = self.config.trailer {
            out.new_line_if_not_start();
            out.write(&f);
            out.new_line();
        }
    }
}