blob: 5bc51e14a30fef4921f12f3dd33a5113ee9b7a88 [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};
Adrian Taylor9fc08462020-08-14 10:51:00 -070018use std::clone::Clone;
David Tolnay7db73692019-10-20 14:51:12 -040019use std::fs;
David Tolnay7db73692019-10-20 14:51:12 -040020use std::path::Path;
David Tolnay7db73692019-10-20 14:51:12 -040021
Adrian Taylor0926f642020-08-25 13:08:06 -070022/// Options for C++ code generation.
David Tolnayec088152020-08-29 23:29:26 -070023///
24/// We expect options to be added over time, so this is a non-exhaustive struct.
25/// To instantiate one you need to crate a default value and mutate those fields
26/// that you want to modify.
27///
28/// ```
29/// # use cxx_gen::Opt;
30/// #
31/// let impl_annotations = r#"__attribute__((visibility("default")))"#.to_owned();
32///
33/// let mut opt = Opt::default();
34/// opt.cxx_impl_annotations = Some(impl_annotations);
35/// ```
Adrian Taylor9fc08462020-08-14 10:51:00 -070036#[derive(Default, Clone)]
David Tolnayec088152020-08-29 23:29:26 -070037#[non_exhaustive]
Adrian Taylor0926f642020-08-25 13:08:06 -070038pub struct Opt {
David Tolnaydf2f78d2020-08-29 23:31:53 -070039 /// Any additional headers to #include. The cxxbridge tool does not parse or
40 /// even require the given paths to exist; they simply go into the generated
41 /// C++ code as #include lines.
David Tolnay33d30292020-03-18 18:02:02 -070042 pub include: Vec<String>,
David Tolnaydf2f78d2020-08-29 23:31:53 -070043 /// Optional annotation for implementations of C++ function wrappers that
44 /// may be exposed to Rust. You may for example need to provide
45 /// `__declspec(dllexport)` or `__attribute__((visibility("default")))` if
46 /// Rust code from one shared object or executable depends on these C++
47 /// functions in another.
Adrian Taylor21f0ff02020-07-21 16:21:48 -070048 pub cxx_impl_annotations: Option<String>,
David Tolnay33d30292020-03-18 18:02:02 -070049}
50
David Tolnay7ece56f2020-03-29 21:21:38 -070051pub(super) fn do_generate_bridge(path: &Path, opt: Opt) -> Vec<u8> {
David Tolnay7db73692019-10-20 14:51:12 -040052 let header = false;
Adrian Taylor8205e622020-07-21 21:53:59 -070053 generate_from_path(path, opt, header)
David Tolnay7db73692019-10-20 14:51:12 -040054}
55
David Tolnay7ece56f2020-03-29 21:21:38 -070056pub(super) fn do_generate_header(path: &Path, opt: Opt) -> Vec<u8> {
David Tolnay7db73692019-10-20 14:51:12 -040057 let header = true;
Adrian Taylor8205e622020-07-21 21:53:59 -070058 generate_from_path(path, opt, header)
David Tolnay7db73692019-10-20 14:51:12 -040059}
60
Adrian Taylor8205e622020-07-21 21:53:59 -070061fn generate_from_path(path: &Path, opt: Opt, header: bool) -> Vec<u8> {
David Tolnay7db73692019-10-20 14:51:12 -040062 let source = match fs::read_to_string(path) {
63 Ok(source) => source,
64 Err(err) => format_err(path, "", Error::Io(err)),
65 };
Adrian Taylor593eddb2020-08-21 23:46:08 -070066 match generate_from_string(&source, opt, header) {
Adrian Taylor8205e622020-07-21 21:53:59 -070067 Ok(out) => out,
David Tolnay7db73692019-10-20 14:51:12 -040068 Err(err) => format_err(path, &source, err),
Adrian Taylor593eddb2020-08-21 23:46:08 -070069 }
70}
71
72fn generate_from_string(source: &str, opt: Opt, header: bool) -> Result<Vec<u8>> {
David Tolnay5fc28552020-08-29 22:05:53 -070073 let mut source = source;
David Tolnay17c32302020-08-29 12:21:16 -070074 if source.starts_with("#!") && !source.starts_with("#![") {
75 let shebang_end = source.find('\n').unwrap_or(source.len());
76 source = &source[shebang_end..];
77 }
David Tolnay5fc28552020-08-29 22:05:53 -070078 let syntax: File = syn::parse_str(source)?;
Adrian Taylor593eddb2020-08-21 23:46:08 -070079 let results = generate(syntax, opt, header, !header)?;
80 match results {
81 (Some(hdr), None) => Ok(hdr),
82 (None, Some(cxx)) => Ok(cxx),
Adrian Taylor9fc08462020-08-14 10:51:00 -070083 _ => panic!("Unexpected generation"),
David Tolnay7db73692019-10-20 14:51:12 -040084 }
85}
Adrian Taylor8205e622020-07-21 21:53:59 -070086
David Tolnay366c41a2020-08-29 22:28:21 -070087pub(super) fn generate(
Adrian Taylor9fc08462020-08-14 10:51:00 -070088 syntax: File,
89 opt: Opt,
90 gen_header: bool,
91 gen_cxx: bool,
92) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
Adrian Taylor8205e622020-07-21 21:53:59 -070093 proc_macro2::fallback::force();
94 let ref mut errors = Errors::new();
David Tolnay3c64a4e2020-08-29 14:07:38 -070095 let bridge = syntax
96 .modules
97 .into_iter()
98 .next()
99 .ok_or(Error::NoBridgeMod)?;
Adrian Taylor8205e622020-07-21 21:53:59 -0700100 let ref namespace = bridge.namespace;
David Tolnay805dca32020-08-29 19:09:55 -0700101 let trusted = bridge.unsafety.is_some();
102 let ref apis = syntax::parse_items(errors, bridge.content, trusted);
Adrian Taylor8205e622020-07-21 21:53:59 -0700103 let ref types = Types::collect(errors, apis);
104 errors.propagate()?;
105 check::typecheck(errors, namespace, apis, types);
106 errors.propagate()?;
Adrian Taylor9fc08462020-08-14 10:51:00 -0700107 // Some callers may wish to generate both header and C++
108 // from the same token stream to avoid parsing twice. But others
109 // only need to generate one or the other.
110 let hdr = if gen_header {
111 Some(write::gen(namespace, apis, types, opt.clone(), true).content())
112 } else {
113 None
114 };
115 let cxx = if gen_cxx {
116 Some(write::gen(namespace, apis, types, opt, false).content())
117 } else {
118 None
119 };
120 Ok((hdr, cxx))
Adrian Taylor8205e622020-07-21 21:53:59 -0700121}