blob: d21db06e0905d3c6737bcc00807b693fe6ac3417 [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
4mod error;
David Tolnayfcd8f462020-08-29 12:13:09 -07005mod file;
David Tolnay7db73692019-10-20 14:51:12 -04006pub(super) mod include;
7pub(super) mod out;
8mod write;
9
David Tolnay0d47a532020-07-30 19:39:04 -070010#[cfg(test)]
11mod tests;
12
David Tolnaye9c533e2020-08-29 23:03:51 -070013pub(super) use self::error::Error;
David Tolnay6f7f6862020-08-29 22:55:03 -070014use self::error::{format_err, Result};
David Tolnayfcd8f462020-08-29 12:13:09 -070015use self::file::File;
David Tolnay0dd85ff2020-05-03 23:43:33 -070016use crate::syntax::report::Errors;
David Tolnayb6cf3142020-04-19 20:56:09 -070017use crate::syntax::{self, check, Types};
David Tolnay7db73692019-10-20 14:51:12 -040018use std::fs;
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 Tolnay33d30292020-03-18 18:02:02 -070047}
48
David Tolnay19cb7852020-08-30 00:04:59 -070049/// Results of code generation.
50pub struct GeneratedCode {
51 /// The bytes of a C++ header file.
52 pub header: Vec<u8>,
53 /// The bytes of a C++ implementation file (e.g. .cc, cpp etc.)
David Tolnayd3659d82020-08-30 00:12:25 -070054 pub implementation: Vec<u8>,
David Tolnay19cb7852020-08-30 00:04:59 -070055}
56
David Tolnay318c3532020-08-30 00:50:05 -070057impl Default for Opt {
58 fn default() -> Self {
59 Opt {
60 include: Vec::new(),
61 cxx_impl_annotations: None,
62 }
63 }
64}
65
David Tolnaya5cca312020-08-29 23:40:04 -070066pub(super) fn do_generate_bridge(path: &Path, opt: &Opt) -> Vec<u8> {
David Tolnay7db73692019-10-20 14:51:12 -040067 let header = false;
Adrian Taylor8205e622020-07-21 21:53:59 -070068 generate_from_path(path, opt, header)
David Tolnay7db73692019-10-20 14:51:12 -040069}
70
David Tolnaya5cca312020-08-29 23:40:04 -070071pub(super) fn do_generate_header(path: &Path, opt: &Opt) -> Vec<u8> {
David Tolnay7db73692019-10-20 14:51:12 -040072 let header = true;
Adrian Taylor8205e622020-07-21 21:53:59 -070073 generate_from_path(path, opt, header)
David Tolnay7db73692019-10-20 14:51:12 -040074}
75
David Tolnaya5cca312020-08-29 23:40:04 -070076fn generate_from_path(path: &Path, opt: &Opt, header: bool) -> Vec<u8> {
David Tolnay7db73692019-10-20 14:51:12 -040077 let source = match fs::read_to_string(path) {
78 Ok(source) => source,
79 Err(err) => format_err(path, "", Error::Io(err)),
80 };
Adrian Taylor593eddb2020-08-21 23:46:08 -070081 match generate_from_string(&source, opt, header) {
Adrian Taylor8205e622020-07-21 21:53:59 -070082 Ok(out) => out,
David Tolnay7db73692019-10-20 14:51:12 -040083 Err(err) => format_err(path, &source, err),
Adrian Taylor593eddb2020-08-21 23:46:08 -070084 }
85}
86
David Tolnaya5cca312020-08-29 23:40:04 -070087fn generate_from_string(source: &str, opt: &Opt, header: bool) -> Result<Vec<u8>> {
David Tolnay5fc28552020-08-29 22:05:53 -070088 let mut source = source;
David Tolnay17c32302020-08-29 12:21:16 -070089 if source.starts_with("#!") && !source.starts_with("#![") {
90 let shebang_end = source.find('\n').unwrap_or(source.len());
91 source = &source[shebang_end..];
92 }
David Tolnay5fc28552020-08-29 22:05:53 -070093 let syntax: File = syn::parse_str(source)?;
David Tolnay19cb7852020-08-30 00:04:59 -070094 let generated = generate(syntax, opt, header, !header)?;
David Tolnayd3659d82020-08-30 00:12:25 -070095 Ok(if header {
96 generated.header
97 } else {
98 generated.implementation
99 })
David Tolnay7db73692019-10-20 14:51:12 -0400100}
Adrian Taylor8205e622020-07-21 21:53:59 -0700101
David Tolnay366c41a2020-08-29 22:28:21 -0700102pub(super) fn generate(
Adrian Taylor9fc08462020-08-14 10:51:00 -0700103 syntax: File,
David Tolnaya5cca312020-08-29 23:40:04 -0700104 opt: &Opt,
Adrian Taylor9fc08462020-08-14 10:51:00 -0700105 gen_header: bool,
David Tolnayd3659d82020-08-30 00:12:25 -0700106 gen_implementation: bool,
David Tolnay19cb7852020-08-30 00:04:59 -0700107) -> Result<GeneratedCode> {
Adrian Taylor8205e622020-07-21 21:53:59 -0700108 proc_macro2::fallback::force();
109 let ref mut errors = Errors::new();
David Tolnay3c64a4e2020-08-29 14:07:38 -0700110 let bridge = syntax
111 .modules
112 .into_iter()
113 .next()
114 .ok_or(Error::NoBridgeMod)?;
Adrian Taylor8205e622020-07-21 21:53:59 -0700115 let ref namespace = bridge.namespace;
David Tolnay805dca32020-08-29 19:09:55 -0700116 let trusted = bridge.unsafety.is_some();
117 let ref apis = syntax::parse_items(errors, bridge.content, trusted);
Adrian Taylor8205e622020-07-21 21:53:59 -0700118 let ref types = Types::collect(errors, apis);
119 errors.propagate()?;
120 check::typecheck(errors, namespace, apis, types);
121 errors.propagate()?;
Adrian Taylor9fc08462020-08-14 10:51:00 -0700122 // Some callers may wish to generate both header and C++
123 // from the same token stream to avoid parsing twice. But others
124 // only need to generate one or the other.
David Tolnay19cb7852020-08-30 00:04:59 -0700125 Ok(GeneratedCode {
126 header: if gen_header {
127 write::gen(namespace, apis, types, opt, true).content()
128 } else {
129 Vec::new()
130 },
David Tolnayd3659d82020-08-30 00:12:25 -0700131 implementation: if gen_implementation {
David Tolnay19cb7852020-08-30 00:04:59 -0700132 write::gen(namespace, apis, types, opt, false).content()
133 } else {
134 Vec::new()
135 },
136 })
Adrian Taylor8205e622020-07-21 21:53:59 -0700137}