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
//! `safe_bindgen` is a library based on moz-cheddar for converting Rust source files
//! into Java and C# bindings.
//!
//! It is built specifically for the SAFE Client Libs project.

// For explanation of lint checks, run `rustc -W help` or see
// https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md
#![forbid(
    exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings
)]
#![deny(
    deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals,
    plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features,
    unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation,
    unused_attributes, unused_comparisons, unused_features, unused_parens, while_true
)]
#![warn(
    trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces,
    unused_qualifications
)]
#![allow(
    box_pointers, missing_copy_implementations, missing_debug_implementations,
    variant_size_differences
)]
// FIXME: add documentation and deny `missing_documentation`
#![allow(missing_docs)]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private))]
#![recursion_limit = "128"]

extern crate inflector;
#[cfg(not(feature = "with-syntex"))]
extern crate rustc_errors as errors;
#[cfg(not(feature = "with-syntex"))]
extern crate syntax;
#[cfg(feature = "with-syntex")]
extern crate syntex_errors as errors;
#[cfg(feature = "with-syntex")]
extern crate syntex_syntax as syntax;
extern crate toml;
#[macro_use]
extern crate quote;
extern crate jni;
extern crate petgraph;
extern crate rustfmt;

#[cfg(test)]
extern crate colored;
#[cfg(test)]
extern crate diff;
#[cfg(test)]
#[macro_use]
extern crate indoc;
#[macro_use]
extern crate unwrap;

pub use common::FilterMode;
use common::{Lang, Outputs};
pub use csharp::LangCSharp;
pub use errors::Level;
pub use java::LangJava;
pub use lang_c::LangC;
use std::collections::HashMap;
use std::fmt::Display;
use std::fs;
use std::io::Error as IoError;
use std::io::{Read, Write};
use std::path::{self, Component, Path, PathBuf};

mod common;
mod csharp;
mod java;
mod lang_c;
mod output;
mod parse;
mod struct_field;

/// Describes an error encountered by the compiler.
///
/// These can be printed nicely using the `Cheddar::print_err` method.
#[derive(Debug)]
pub struct Error {
    pub level: Level,
    span: Option<syntax::codemap::Span>,
    pub message: String,
}

impl Error {
    pub fn error(message: &str) -> Self {
        Error {
            level: Level::Error,
            span: None,
            message: message.to_string(),
        }
    }
}

impl Display for Error {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(formatter, "{}: {}", self.level, self.message)
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        match self.level {
            Level::Bug => "internal error",
            Level::Fatal | Level::Error => "error",
            Level::Warning => "warning",
            Level::Note => "note",
            Level::Help => "help",
            _ => unreachable!(),
        }
    }
}

impl From<IoError> for Error {
    fn from(e: IoError) -> Self {
        Error {
            level: Level::Fatal,
            span: None,
            message: format!("I/O Error: {}", e),
        }
    }
}

impl From<Error> for Vec<Error> {
    fn from(e: Error) -> Self {
        vec![e]
    }
}

impl Error {
    /// Use a ParseSess to print the error in the correct format.
    #[allow(unused_must_use)]
    fn print(&self, sess: &syntax::parse::ParseSess) {
        // TODO: there must be some way to reduce the amount of code here.
        // Throw away the results (with { ...; }) since they are handled elsewhere.
        if let Some(span) = self.span {
            match self.level {
                Level::Bug => {
                    sess.span_diagnostic.span_bug(span, &self.message);
                }
                Level::Fatal => {
                    sess.span_diagnostic.span_fatal(span, &self.message);
                }
                Level::Error => {
                    sess.span_diagnostic.span_err(span, &self.message);
                }
                Level::Warning => {
                    sess.span_diagnostic.span_warn(span, &self.message);
                }
                Level::Note => {
                    sess.span_diagnostic
                        .span_note_without_error(span, &self.message);
                }
                Level::Help => {
                    sess.span_diagnostic
                        .struct_dummy()
                        .span_help(span, &self.message);
                }
                _ => unreachable!(),
            };
        } else {
            match self.level {
                Level::Bug => {
                    sess.span_diagnostic.bug(&self.message);
                }
                Level::Fatal => {
                    sess.span_diagnostic.fatal(&self.message);
                }
                Level::Error => {
                    sess.span_diagnostic.err(&self.message);
                }
                Level::Warning => {
                    sess.span_diagnostic.warn(&self.message);
                }
                Level::Note => {
                    sess.span_diagnostic.note_without_error(&self.message);
                }
                Level::Help => {
                    sess.span_diagnostic.struct_dummy().help(&self.message);
                }
                _ => unreachable!(),
            };
        }
    }
}

/// Stores configuration for the bindgen.
///
/// # Examples
///
/// Since construction can only fail if there is an error _while_ reading the cargo manifest it is
/// usually safe to call `.unwrap()` on the result (though `.expect()` is considered better
/// practice).
///
/// ```ignore
/// Bindgen::new().expect("unable to read cargo manifest");
/// ```
///
/// If your project is a valid cargo project or follows the same structure, you can simply place
/// the following in your build script.
///
/// ```ignore
/// Bindgen::new().expect("unable to read cargo manifest")
///     .run_build("path/to/output/file");
/// ```
///
/// If you use a different structure you should use `.source_file("...")` to set the path to the
/// root crate file.
///
/// ```ignore
/// Bindgen::new().expect("unable to read cargo manifest")
///     .source_file("src/root.rs")
///     .run_build("include/my_header.h");
/// ```
pub struct Bindgen {
    /// The root source file of the crate.
    input: PathBuf,
    /// The current parser session.
    ///
    /// Used for printing errors.
    session: syntax::parse::ParseSess,
}

impl Bindgen {
    /// Create a new bindgen instance.
    ///
    /// This can only fail if there are issues reading the cargo manifest. If there is no cargo
    /// manifest available then the source file defaults to `src/lib.rs`.
    pub fn new() -> Result<Self, Error> {
        let source_path = source_file_from_cargo()?;
        let input = PathBuf::from(source_path);

        Ok(Bindgen {
            input: input,
            session: syntax::parse::ParseSess::new(),
        })
    }

    /// Set the path to the root source file of the crate.
    ///
    /// This should only be used when not using a `cargo` build system.
    pub fn source_file<T>(&mut self, path: T) -> &mut Self
    where
        PathBuf: From<T>,
    {
        self.input = PathBuf::from(path);
        self
    }

    /// Compile just the code into header declarations.
    ///
    /// This does not add any include-guards, includes, or extern declarations. It is mainly
    /// intended for internal use, but may be of interest to people who wish to embed
    /// moz-cheddar's generated code in another file.
    pub fn compile<L: Lang>(
        &self,
        lang: &mut L,
        outputs: &mut Outputs,
        finalise: bool,
    ) -> Result<(), Vec<Error>> {
        let base_path = self.input.parent().unwrap();
        let mod_path = unwrap!(self.input.to_str()).to_string();

        // Parse the top level mod.
        let krate = syntax::parse::parse_crate_from_file(&self.input, &self.session).unwrap();
        let module = convert_lib_path_to_module(&PathBuf::from(mod_path.clone()));
        eprintln!("Parsing {} ({:?})", module.join("::"), mod_path);

        parse::parse_mod(lang, &krate.module, &module, outputs)?;

        // Parse other mods.
        let modules = parse::imported_mods(&krate.module);
        for module in modules {
            let mut mod_path = base_path.join(&format!(
                "{}.rs",
                module.join(&path::MAIN_SEPARATOR.to_string())
            ));

            if !mod_path.exists() {
                mod_path = base_path.join(&format!(
                    "{}/mod.rs",
                    module.join(&path::MAIN_SEPARATOR.to_string())
                ));
            }

            eprintln!("Parsing {} ({:?})", module.join("::"), mod_path);

            let krate = syntax::parse::parse_crate_from_file(&mod_path, &self.session).unwrap();
            parse::parse_mod(lang, &krate.module, &module, outputs)?;
        }

        if finalise {
            lang.finalise_output(outputs)?;
        }

        Ok(())
    }

    pub fn compile_or_panic<L: Lang>(&self, lang: &mut L, outputs: &mut Outputs, finalise: bool) {
        if let Err(errors) = self.compile(lang, outputs, finalise) {
            for error in &errors {
                self.print_error(error);
            }

            panic!("Failed to compile.");
        }
    }

    /// Writes virtual files to the file system
    pub fn write_outputs<P: AsRef<Path>>(&self, root: P, outputs: &Outputs) -> Result<(), IoError> {
        let root = root.as_ref();

        for (path, contents) in outputs {
            let full_path = root.join(PathBuf::from(path));

            if let Some(parent_dirs) = full_path.parent() {
                fs::create_dir_all(parent_dirs)?;
            }

            let mut f = fs::File::create(full_path)?;
            f.write_all(contents.as_bytes())?;
            f.sync_all()?;
        }

        Ok(())
    }

    pub fn write_outputs_or_panic<P: AsRef<Path>>(&self, root: P, outputs: &Outputs) {
        if let Err(err) = self.write_outputs(root, outputs) {
            self.print_error(&From::from(err));
            panic!("Failed to write output.");
        }
    }

    /// Write the header to a file, panicking on error.
    ///
    /// This is a convenience method for use in build scripts. If errors occur during compilation
    /// they will be printed then the function will panic.
    ///
    /// # Panics
    ///
    /// Panics on any compilation error so that the build script exits and prints output.
    pub fn run_build<P: AsRef<Path>, L: Lang>(&self, lang: &mut L, output_dir: P) {
        let mut outputs = HashMap::new();
        self.compile_or_panic(lang, &mut outputs, true);
        self.write_outputs_or_panic(output_dir, &outputs);
    }

    /// Print an error using the ParseSess stored in Cheddar.
    pub fn print_error(&self, error: &Error) {
        error.print(&self.session);
    }
}

/// Convert a path into a top-level module name (e.g. `ffi_utils/src/lib.rs` -> `ffi_libs`)
fn convert_lib_path_to_module<P: AsRef<Path>>(path: &P) -> Vec<String> {
    let mut res = Vec::new();
    let path = path.as_ref();

    for component in path.components() {
        if let Component::Normal(path) = component {
            let path = unwrap!(path.to_str());
            res.push(path.to_string());
        }
    }

    // Cut off the "src/lib.rs" part
    if res[(res.len() - 2)..] == ["src", "lib.rs"] {
        res = res[..(res.len() - 2)].to_vec();
    }

    res
}

/// Extract the path to the root source file from a `Cargo.toml`.
fn source_file_from_cargo() -> Result<String, Error> {
    let cargo_toml = path::Path::new(
        &std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_else(|| std::ffi::OsString::from("")),
    ).join("Cargo.toml");

    // If no `Cargo.toml` assume `src/lib.rs` until told otherwise.
    let default = "src/lib.rs";
    let mut cargo_toml = match std::fs::File::open(&cargo_toml) {
        Ok(value) => value,
        Err(..) => return Ok(default.to_owned()),
    };

    let mut buf = String::new();
    match cargo_toml.read_to_string(&mut buf) {
        Ok(..) => {}
        Err(..) => {
            return Err(Error {
                level: Level::Fatal,
                span: None,
                message: "could not read cargo manifest".into(),
            })
        }
    };

    let table = match (&buf).parse::<toml::Value>() {
        Ok(value) => value,
        Err(..) => {
            return Err(Error {
                level: Level::Fatal,
                span: None,
                message: "could not parse cargo manifest".into(),
            })
        }
    };

    // If not explicitly stated then defaults to `src/lib.rs`.
    Ok(table
        .get("lib")
        .and_then(|t| t.get("path"))
        .and_then(|s| s.as_str())
        .unwrap_or(default)
        .into())
}