blob: ac8224eb588eb1b687b193bd14ddd9987365451b [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 Tolnay3be0e1f2020-10-31 20:53:00 -07004mod builtin;
David Tolnay75c23852020-10-27 21:07:53 -07005mod check;
David Tolnaybb3ba502020-08-30 19:59:41 -07006pub(super) mod error;
David Tolnayfcd8f462020-08-29 12:13:09 -07007mod file;
David Tolnay0d85ccd2020-08-30 20:18:13 -07008pub(super) mod fs;
David Tolnay3e278d72020-10-31 22:14:35 -07009mod ifndef;
David Tolnay7db73692019-10-20 14:51:12 -040010pub(super) mod include;
Adrian Taylorc8713432020-10-21 18:20:55 -070011mod namespace_organizer;
David Tolnay7db73692019-10-20 14:51:12 -040012pub(super) mod out;
13mod write;
14
David Tolnaye9c533e2020-08-29 23:03:51 -070015pub(super) use self::error::Error;
David Tolnay6f7f6862020-08-29 22:55:03 -070016use self::error::{format_err, Result};
David Tolnayfcd8f462020-08-29 12:13:09 -070017use self::file::File;
David Tolnay700cd0c2020-10-28 12:40:27 -070018use self::include::Include;
David Tolnay0dd85ff2020-05-03 23:43:33 -070019use crate::syntax::report::Errors;
David Tolnay75c23852020-10-27 21:07:53 -070020use crate::syntax::{self, Types};
David Tolnay7db73692019-10-20 14:51:12 -040021use std::path::Path;
David Tolnay7db73692019-10-20 14:51:12 -040022
Adrian Taylor0926f642020-08-25 13:08:06 -070023/// Options for C++ code generation.
David Tolnayec088152020-08-29 23:29:26 -070024///
25/// We expect options to be added over time, so this is a non-exhaustive struct.
26/// To instantiate one you need to crate a default value and mutate those fields
27/// that you want to modify.
28///
29/// ```
30/// # use cxx_gen::Opt;
31/// #
32/// let impl_annotations = r#"__attribute__((visibility("default")))"#.to_owned();
33///
34/// let mut opt = Opt::default();
35/// opt.cxx_impl_annotations = Some(impl_annotations);
36/// ```
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 Tolnay700cd0c2020-10-28 12:40:27 -070042 pub include: Vec<Include>,
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 Tolnay8238d4a2020-08-30 00:34:17 -070049
50 pub(super) gen_header: bool,
51 pub(super) gen_implementation: bool,
David Tolnay75c23852020-10-27 21:07:53 -070052 pub(super) allow_dot_includes: bool,
David Tolnay33d30292020-03-18 18:02:02 -070053}
54
David Tolnay19cb7852020-08-30 00:04:59 -070055/// Results of code generation.
David Tolnayf0277562020-09-24 10:46:14 -040056#[derive(Default)]
David Tolnay19cb7852020-08-30 00:04:59 -070057pub struct GeneratedCode {
58 /// The bytes of a C++ header file.
59 pub header: Vec<u8>,
60 /// The bytes of a C++ implementation file (e.g. .cc, cpp etc.)
David Tolnayd3659d82020-08-30 00:12:25 -070061 pub implementation: Vec<u8>,
David Tolnay19cb7852020-08-30 00:04:59 -070062}
63
David Tolnay318c3532020-08-30 00:50:05 -070064impl Default for Opt {
65 fn default() -> Self {
66 Opt {
67 include: Vec::new(),
68 cxx_impl_annotations: None,
David Tolnay8238d4a2020-08-30 00:34:17 -070069 gen_header: true,
70 gen_implementation: true,
David Tolnay75c23852020-10-27 21:07:53 -070071 allow_dot_includes: true,
David Tolnay318c3532020-08-30 00:50:05 -070072 }
73 }
74}
75
David Tolnay8238d4a2020-08-30 00:34:17 -070076pub(super) fn generate_from_path(path: &Path, opt: &Opt) -> GeneratedCode {
David Tolnaydbff3c42020-08-31 00:41:53 -070077 let source = match read_to_string(path) {
David Tolnay7db73692019-10-20 14:51:12 -040078 Ok(source) => source,
David Tolnaydbff3c42020-08-31 00:41:53 -070079 Err(err) => format_err(path, "", err),
David Tolnay7db73692019-10-20 14:51:12 -040080 };
David Tolnay8238d4a2020-08-30 00:34:17 -070081 match generate_from_string(&source, opt) {
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 Tolnaydbff3c42020-08-31 00:41:53 -070087fn read_to_string(path: &Path) -> Result<String> {
David Tolnayc0e07dc2020-09-02 15:39:28 -070088 let bytes = if path == Path::new("-") {
89 fs::read_stdin()
90 } else {
91 fs::read(path)
92 }?;
David Tolnaydbff3c42020-08-31 00:41:53 -070093 match String::from_utf8(bytes) {
94 Ok(string) => Ok(string),
95 Err(err) => Err(Error::Utf8(path.to_owned(), err.utf8_error())),
96 }
97}
98
David Tolnay8238d4a2020-08-30 00:34:17 -070099fn generate_from_string(source: &str, opt: &Opt) -> Result<GeneratedCode> {
David Tolnay5fc28552020-08-29 22:05:53 -0700100 let mut source = source;
David Tolnay17c32302020-08-29 12:21:16 -0700101 if source.starts_with("#!") && !source.starts_with("#![") {
102 let shebang_end = source.find('\n').unwrap_or(source.len());
103 source = &source[shebang_end..];
104 }
David Tolnay11926532020-11-01 00:06:10 -0700105 proc_macro2::fallback::force();
David Tolnay5fc28552020-08-29 22:05:53 -0700106 let syntax: File = syn::parse_str(source)?;
David Tolnay8238d4a2020-08-30 00:34:17 -0700107 generate(syntax, opt)
David Tolnay7db73692019-10-20 14:51:12 -0400108}
Adrian Taylor8205e622020-07-21 21:53:59 -0700109
David Tolnay8238d4a2020-08-30 00:34:17 -0700110pub(super) fn generate(syntax: File, opt: &Opt) -> Result<GeneratedCode> {
Adrian Taylor8205e622020-07-21 21:53:59 -0700111 let ref mut errors = Errors::new();
David Tolnay3c64a4e2020-08-29 14:07:38 -0700112 let bridge = syntax
113 .modules
114 .into_iter()
115 .next()
116 .ok_or(Error::NoBridgeMod)?;
Adrian Taylor8205e622020-07-21 21:53:59 -0700117 let ref namespace = bridge.namespace;
David Tolnay805dca32020-08-29 19:09:55 -0700118 let trusted = bridge.unsafety.is_some();
Adrian Taylorc8713432020-10-21 18:20:55 -0700119 let ref apis = syntax::parse_items(errors, bridge.content, trusted, namespace);
Adrian Taylor8205e622020-07-21 21:53:59 -0700120 let ref types = Types::collect(errors, apis);
David Tolnay75c23852020-10-27 21:07:53 -0700121 check::precheck(errors, apis, opt);
Adrian Taylor8205e622020-07-21 21:53:59 -0700122 errors.propagate()?;
Adrian Taylorc8713432020-10-21 18:20:55 -0700123 check::typecheck(errors, apis, types);
Adrian Taylor8205e622020-07-21 21:53:59 -0700124 errors.propagate()?;
Adrian Taylor9fc08462020-08-14 10:51:00 -0700125 // Some callers may wish to generate both header and C++
126 // from the same token stream to avoid parsing twice. But others
127 // only need to generate one or the other.
David Tolnay19cb7852020-08-30 00:04:59 -0700128 Ok(GeneratedCode {
David Tolnay8238d4a2020-08-30 00:34:17 -0700129 header: if opt.gen_header {
Adrian Taylorc8713432020-10-21 18:20:55 -0700130 write::gen(apis, types, opt, true).content()
David Tolnay19cb7852020-08-30 00:04:59 -0700131 } else {
132 Vec::new()
133 },
David Tolnay8238d4a2020-08-30 00:34:17 -0700134 implementation: if opt.gen_implementation {
Adrian Taylorc8713432020-10-21 18:20:55 -0700135 write::gen(apis, types, opt, false).content()
David Tolnay19cb7852020-08-30 00:04:59 -0700136 } else {
137 Vec::new()
138 },
139 })
Adrian Taylor8205e622020-07-21 21:53:59 -0700140}