blob: f4d643dc652e6a3ba484710cd8123ea87267853f [file] [log] [blame]
David Tolnayb4dba232020-05-11 00:55:29 -07001// Functionality that is shared between the cxx_build::bridge entry point and
2// the cxxbridge CLI command.
David Tolnay7db73692019-10-20 14:51:12 -04003
David Tolnaybb3ba502020-08-30 19:59:41 -07004pub(super) mod error;
David Tolnayfcd8f462020-08-29 12:13:09 -07005mod file;
David Tolnay0d85ccd2020-08-30 20:18:13 -07006pub(super) mod fs;
David Tolnay7db73692019-10-20 14:51:12 -04007pub(super) mod include;
8pub(super) mod out;
9mod write;
10
David Tolnay0d47a532020-07-30 19:39:04 -070011#[cfg(test)]
12mod tests;
13
David Tolnaye9c533e2020-08-29 23:03:51 -070014pub(super) use self::error::Error;
David Tolnay6f7f6862020-08-29 22:55:03 -070015use self::error::{format_err, Result};
David Tolnayfcd8f462020-08-29 12:13:09 -070016use self::file::File;
David Tolnay0dd85ff2020-05-03 23:43:33 -070017use crate::syntax::report::Errors;
David Tolnayb6cf3142020-04-19 20:56:09 -070018use crate::syntax::{self, check, Types};
David Tolnay7db73692019-10-20 14:51:12 -040019use std::path::Path;
David Tolnay7db73692019-10-20 14:51:12 -040020
Adrian Taylor0926f642020-08-25 13:08:06 -070021/// Options for C++ code generation.
David Tolnayec088152020-08-29 23:29:26 -070022///
23/// We expect options to be added over time, so this is a non-exhaustive struct.
24/// To instantiate one you need to crate a default value and mutate those fields
25/// that you want to modify.
26///
27/// ```
28/// # use cxx_gen::Opt;
29/// #
30/// let impl_annotations = r#"__attribute__((visibility("default")))"#.to_owned();
31///
32/// let mut opt = Opt::default();
33/// opt.cxx_impl_annotations = Some(impl_annotations);
34/// ```
David Tolnayec088152020-08-29 23:29:26 -070035#[non_exhaustive]
Adrian Taylor0926f642020-08-25 13:08:06 -070036pub struct Opt {
David Tolnaydf2f78d2020-08-29 23:31:53 -070037 /// Any additional headers to #include. The cxxbridge tool does not parse or
38 /// even require the given paths to exist; they simply go into the generated
39 /// C++ code as #include lines.
David Tolnay33d30292020-03-18 18:02:02 -070040 pub include: Vec<String>,
David Tolnaydf2f78d2020-08-29 23:31:53 -070041 /// Optional annotation for implementations of C++ function wrappers that
42 /// may be exposed to Rust. You may for example need to provide
43 /// `__declspec(dllexport)` or `__attribute__((visibility("default")))` if
44 /// Rust code from one shared object or executable depends on these C++
45 /// functions in another.
Adrian Taylor21f0ff02020-07-21 16:21:48 -070046 pub cxx_impl_annotations: Option<String>,
David Tolnay8238d4a2020-08-30 00:34:17 -070047
48 pub(super) gen_header: bool,
49 pub(super) gen_implementation: bool,
David Tolnay33d30292020-03-18 18:02:02 -070050}
51
David Tolnay19cb7852020-08-30 00:04:59 -070052/// Results of code generation.
53pub struct GeneratedCode {
54 /// The bytes of a C++ header file.
55 pub header: Vec<u8>,
56 /// The bytes of a C++ implementation file (e.g. .cc, cpp etc.)
David Tolnayd3659d82020-08-30 00:12:25 -070057 pub implementation: Vec<u8>,
David Tolnay19cb7852020-08-30 00:04:59 -070058}
59
David Tolnay318c3532020-08-30 00:50:05 -070060impl Default for Opt {
61 fn default() -> Self {
62 Opt {
63 include: Vec::new(),
64 cxx_impl_annotations: None,
David Tolnay8238d4a2020-08-30 00:34:17 -070065 gen_header: true,
66 gen_implementation: true,
David Tolnay318c3532020-08-30 00:50:05 -070067 }
68 }
69}
70
David Tolnay8238d4a2020-08-30 00:34:17 -070071pub(super) fn generate_from_path(path: &Path, opt: &Opt) -> GeneratedCode {
David Tolnaydbff3c42020-08-31 00:41:53 -070072 let source = match read_to_string(path) {
David Tolnay7db73692019-10-20 14:51:12 -040073 Ok(source) => source,
David Tolnaydbff3c42020-08-31 00:41:53 -070074 Err(err) => format_err(path, "", err),
David Tolnay7db73692019-10-20 14:51:12 -040075 };
David Tolnay8238d4a2020-08-30 00:34:17 -070076 match generate_from_string(&source, opt) {
Adrian Taylor8205e622020-07-21 21:53:59 -070077 Ok(out) => out,
David Tolnay7db73692019-10-20 14:51:12 -040078 Err(err) => format_err(path, &source, err),
Adrian Taylor593eddb2020-08-21 23:46:08 -070079 }
80}
81
David Tolnaydbff3c42020-08-31 00:41:53 -070082fn read_to_string(path: &Path) -> Result<String> {
83 let bytes = fs::read(path)?;
84 match String::from_utf8(bytes) {
85 Ok(string) => Ok(string),
86 Err(err) => Err(Error::Utf8(path.to_owned(), err.utf8_error())),
87 }
88}
89
David Tolnay8238d4a2020-08-30 00:34:17 -070090fn generate_from_string(source: &str, opt: &Opt) -> Result<GeneratedCode> {
David Tolnay5fc28552020-08-29 22:05:53 -070091 let mut source = source;
David Tolnay17c32302020-08-29 12:21:16 -070092 if source.starts_with("#!") && !source.starts_with("#![") {
93 let shebang_end = source.find('\n').unwrap_or(source.len());
94 source = &source[shebang_end..];
95 }
David Tolnay5fc28552020-08-29 22:05:53 -070096 let syntax: File = syn::parse_str(source)?;
David Tolnay8238d4a2020-08-30 00:34:17 -070097 generate(syntax, opt)
David Tolnay7db73692019-10-20 14:51:12 -040098}
Adrian Taylor8205e622020-07-21 21:53:59 -070099
David Tolnay8238d4a2020-08-30 00:34:17 -0700100pub(super) fn generate(syntax: File, opt: &Opt) -> Result<GeneratedCode> {
Adrian Taylor8205e622020-07-21 21:53:59 -0700101 proc_macro2::fallback::force();
102 let ref mut errors = Errors::new();
David Tolnay3c64a4e2020-08-29 14:07:38 -0700103 let bridge = syntax
104 .modules
105 .into_iter()
106 .next()
107 .ok_or(Error::NoBridgeMod)?;
Adrian Taylor8205e622020-07-21 21:53:59 -0700108 let ref namespace = bridge.namespace;
David Tolnay805dca32020-08-29 19:09:55 -0700109 let trusted = bridge.unsafety.is_some();
110 let ref apis = syntax::parse_items(errors, bridge.content, trusted);
Adrian Taylor8205e622020-07-21 21:53:59 -0700111 let ref types = Types::collect(errors, apis);
112 errors.propagate()?;
113 check::typecheck(errors, namespace, apis, types);
114 errors.propagate()?;
Adrian Taylor9fc08462020-08-14 10:51:00 -0700115 // Some callers may wish to generate both header and C++
116 // from the same token stream to avoid parsing twice. But others
117 // only need to generate one or the other.
David Tolnay19cb7852020-08-30 00:04:59 -0700118 Ok(GeneratedCode {
David Tolnay8238d4a2020-08-30 00:34:17 -0700119 header: if opt.gen_header {
David Tolnay19cb7852020-08-30 00:04:59 -0700120 write::gen(namespace, apis, types, opt, true).content()
121 } else {
122 Vec::new()
123 },
David Tolnay8238d4a2020-08-30 00:34:17 -0700124 implementation: if opt.gen_implementation {
David Tolnay19cb7852020-08-30 00:04:59 -0700125 write::gen(namespace, apis, types, opt, false).content()
126 } else {
127 Vec::new()
128 },
129 })
Adrian Taylor8205e622020-07-21 21:53:59 -0700130}